diff --git a/.env.example b/.env.example index b6a7fe9b..db1d8f5a 100644 --- a/.env.example +++ b/.env.example @@ -39,7 +39,7 @@ PROXY= # 单账户初始化超时 INIT_TIMEOUT=2m -# 普通请求最大执行时间 +# 上游连续没有数据的最长时间,从请求开始到首个数据同样计入 REQUEST_TIMEOUT=30m # 常驻预热账户数,未设置时 SpiderMonkey 后端为 10、Camoufox 后端为 5 @@ -60,7 +60,7 @@ ROUTING_STRATEGY=round-robin # fill-first 依次使用的账户 ID,逗号分隔,未列出的账户排在后面并按 ID 排序,保存后立即生效 ACCOUNT_ORDER= -# 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;额度用尽不计入 +# 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;登录失效与额度用尽不计入 MAX_ACCOUNT_SWITCHES=3 # 生成请求使用的上游通道:playground、build(旧通道,上游已停用其生成),逗号分隔 @@ -99,12 +99,24 @@ CONTINUATION_REWRITE=true # 改写时与末尾 assistant 消息一起写入系统指令的续写提示词;设为空时末尾 assistant 消息改作 user 消息发送 CONTINUATION_PROMPT="Continue the assistant response after the following prefix. Return only the continuation, without repeating the prefix." +# 仅限角色扮演场景:声明内部 final 工具让模型一次性交付完整正文以减轻流式截断,思考照常实时输出,保存后立即生效 +REPLY_TOOL=false + +# 角色扮演场景思考防拦截:引导模型在内部思考中保持简洁抽象、不复述敏感词,并将思考强度上限收敛到低档,降低思考阶段触发上游过滤截断的概率,保存后立即生效 +THINKING_GUARD=false + +# 发送前将用户消息中的中文改写为指定文字(不改模型历史回答),并在系统指令中要求模型默认以简体中文回复:off 关闭,traditional 繁体中文,martian 火星文,保存后立即生效 +USER_MESSAGE_REWRITE=off + # 原请求迟迟没有首字时用空闲账户(其他账户优先,没有时用原账户的空闲槽位)发起一个备用请求,先出首字的一方继续:off 关闭,auto 按各模型与通道近 24 小时首字等待的 p95,正整数为等待秒数 FIRST_EVENT_HEDGE=off # 发起备用请求的模型 ID,逗号分隔;备用请求同样计入账户额度 FIRST_EVENT_HEDGE_MODELS=gemini-4-argon +# 一次尝试从取得账户起等待首个上游事件的最长时间,到时取消这次尝试并换号(计入 MAX_ACCOUNT_SWITCHES,不冷却账户),没有可换的账户时返回 504;off 关闭,正整数为秒数 +FIRST_EVENT_TIMEOUT=off + # WAA 后端:spidermonkey 在服务进程内的 SpiderMonkey 中运行,camoufox 使用 Camoufox 页面 WAA_BACKEND=spidermonkey diff --git a/README.md b/README.md index ee5b7a8e..a7ce015b 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ docker compose up -d 设置的生效时机: -- 保存后立即生效:账户选择策略、Worker 容量、换号次数上限、模型映射、非流式保活、假流式、搜索型号、全模型搜索与媒体输出;进行中的请求沿用开始时的设置 +- 保存后立即生效:账户选择策略、Worker 容量、换号次数上限、模型映射、非流式保活、假流式、搜索型号、全模型搜索、回复工具防截断、简体转繁体改写与媒体输出;进行中的请求沿用开始时的设置 - 停止再启动生成服务后生效:其余生成服务配置,启动时读取最新 `.env` - 重启管理进程后生效:管理页面地址、预览地址和 `PROXY_API_KEY` @@ -357,12 +357,13 @@ curl http://127.0.0.1:2048/v1/chat/completions \ 4. API 密钥填写 `.env` 中的 `PROXY_API_KEY` 5. 从 `/v1/models` 获取模型,或手动添加 `gemini-3.8-flash`、`gemini-3.5-flash-lite` -[Claude Code](https://github.com/anthropics/claude-code) 使用 Anthropic 接口,子 Agent 按 opus、sonnet、haiku 档位选择模型,以下变量把它们映射到 AI Studio 模型;WebSearch 由 Google Search 执行: +[Claude Code](https://github.com/anthropics/claude-code) 使用 Anthropic 接口,子 Agent 按 fable、opus、sonnet、haiku 档位选择模型,以下变量把它们映射到 AI Studio 模型;WebSearch 由 Google Search 执行: ```powershell $env:ANTHROPIC_BASE_URL = "http://127.0.0.1:2048" $env:ANTHROPIC_API_KEY = "" $env:ANTHROPIC_MODEL = "gemini-3.8-flash" +$env:ANTHROPIC_DEFAULT_FABLE_MODEL = "gemini-4-argon" $env:ANTHROPIC_DEFAULT_OPUS_MODEL = "gemini-3.1-pro-preview" $env:ANTHROPIC_DEFAULT_SONNET_MODEL = "gemini-3.8-flash" $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = "gemini-3.5-flash-lite" @@ -672,7 +673,7 @@ cp .env.example .env | `ADMIN_PASSWORD` | 空 | 管理员密码,开启登录时必填 | | `PROXY` | 空 | Chrome 导入、登录和账户默认使用的 HTTP、HTTPS 或 SOCKS5 代理,多个代理用逗号分隔组成代理池;留空时使用系统代理 | | `INIT_TIMEOUT` | `2m` | 单账户 WAA 初始化超时 | -| `REQUEST_TIMEOUT` | `30m` | 单次请求最大执行时间,自动续写的每一轮开始时重新计时 | +| `REQUEST_TIMEOUT` | `30m` | 上游连续没有数据的最长时间,从请求开始到首个数据同样计入;上游仍在输出的请求不受总时长限制 | | `WARM_WORKER_LIMIT` | `10`,Camoufox 后端 `5` | 常驻预热账户数 | | `MAX_ACTIVE_WORKERS` | `20`,Camoufox 后端 `10` | 高峰期最多同时运行的 Worker 数 | | `WARM_STARTUP_CONCURRENCY` | `5` | 按需扩容时同时冷启动的 Camoufox Worker 数,预热逐个启动;`WAA_BACKEND=spidermonkey` 时不限制 | @@ -694,8 +695,12 @@ cp .env.example .env | `GOOGLE_SEARCH` | `false` | 为 OpenAI、Anthropic、Gemini 与 Interactions 的生成请求启用 Google 搜索,包含普通型号与携带函数工具的请求 | | `CONTINUATION_REWRITE` | `true` | 以 assistant 消息结尾的请求在不支持原生续写的模型上改写为续写请求;关闭时所有模型原样发送,上游拒绝时返回其错误 | | `CONTINUATION_PROMPT` | 内置英文续写句 | 改写时与末尾 assistant 消息一起写入系统指令的提示词;设为空时末尾 assistant 消息改作 user 消息发送 | +| `REPLY_TOOL` | `false` | 仅限角色扮演场景:声明内部 `final` 工具让模型一次性交付完整正文以减轻流式截断,思考照常实时输出;保存后立即生效 | +| `THINKING_GUARD` | `false` | 角色扮演场景思考防拦截:引导模型在内部思考中保持简洁抽象、不复述敏感词,并将思考强度上限收敛到低档,降低思考阶段触发上游过滤截断的概率;保存后立即生效 | +| `USER_MESSAGE_REWRITE` | `off` | 发送前将用户消息中的中文改写为繁体中文或火星文(不改模型历史回答),并在系统指令中要求模型默认以简体中文回复;取值 `off`、`traditional` 或 `martian`,保存后立即生效 | | `FIRST_EVENT_HEDGE` | `off` | 原请求迟迟没有首字时用空闲账户发起一个备用请求,取值 `off`、`auto` 或等待秒数 | | `FIRST_EVENT_HEDGE_MODELS` | `gemini-4-argon` | 发起备用请求的模型 ID,逗号分隔;备用请求同样计入账户额度 | +| `FIRST_EVENT_TIMEOUT` | `off` | 单次尝试从取得账户起等待首个上游事件的最长时间,到时取消并换号,取值 `off` 或正整数秒 | | `WAA_BACKEND` | `spidermonkey` | WAA 运行的位置,`spidermonkey` 或 `camoufox` | | `MEDIA_OUTPUT` | `inline` | Chat Completions 与 Messages 正文中生成图片与音频的引用方式,`inline` 或 `url` | | `MEDIA_BASE_URL` | 空 | 媒体 URL 使用的服务地址,例如 `https://ai.example.com`;留空时使用每个请求访问的地址,经反向代理时跟随 `X-Forwarded-Proto` | @@ -704,7 +709,7 @@ cp .env.example .env - `PREVIEW_LISTEN_ADDR`:无法监听时改用同一主机上的空闲端口;页面以当前访问的主机名加实际端口打开预览 - `AUTO_START`:网络等原因启动失败时按 5 秒起、翻倍至 5 分钟的间隔重试,手动启动或停止后不再重试 -- `MAX_ACCOUNT_SWITCHES`:额度用尽不计入,照常依次尝试其余账户 +- `MAX_ACCOUNT_SWITCHES`:登录失效与额度用尽不计入,照常依次尝试其余账户 - `NONSTREAM_KEEPALIVE`:返回 200 后每 10 秒写出一个换行直到写出 JSON 正文,经 Cloudflare 等反向代理时连接不会因长时间无数据断开;此后才出现的错误以协议错误正文返回 - `STRIP_THOUGHT_SIGNATURES`:函数调用带 `skip_thought_signature_validator`;之前各轮的思考内容不随签名发给模型,长对话的输入 token 较少 - `DISCOVER_HIDDEN_MODELS`: @@ -715,6 +720,9 @@ cp .env.example .env - 备用请求优先用其他账户,没有时用原账户的空闲槽位;先出首字的一方继续,另一方取消 - `auto` 按各模型与通道近 24 小时首字等待的 p95,请求少于 20 次的模型与通道不发起 - 正整数为等待秒数,设置页选自定义时填入请求最多的模型的近期 p95 +- `FIRST_EVENT_TIMEOUT`: + - 每次尝试从取得账户起独立计时,收到首个语义事件即停止;到时取消这次尝试并换号,计入 `MAX_ACCOUNT_SWITCHES`、不冷却账户,没有可换账户时返回 504 + - 与 `FIRST_EVENT_HEDGE` 同开时原请求与备用请求各自计时,建议大于对冲等待秒数;排除后台请求与 agent 后台任务,慢思考请求的首字可能需要几分钟 - `WAA_BACKEND`: - `spidermonkey` 在服务进程内的 SpiderMonkey 中运行 WAA,不下载也不启动 Camoufox;`camoufox` 在 Camoufox 页面运行 WAA;其他取值按 `spidermonkey` - 未设置时,启动时按 `auth/` 确定后写入 `.env`:已有账户而没有 `auth/.waa-interpreters` 时为 `camoufox`,否则为 `spidermonkey` @@ -806,7 +814,7 @@ API 试用页的 HTML 预览运行在 `PREVIEW_LISTEN_ADDR` 提供的独立来 权益与模型目录的读取: -- “刷新全部”立即读取全部启用账户的权益与模型目录,后台每 24 小时也会读取一次;请求的模型不在目录中且距上次读取超过 10 分钟时,服务先读取一次再处理该请求 +- “刷新全部”立即读取全部启用账户的权益与模型目录,在服务端运行,关闭或刷新管理页后继续,重新打开时显示进度与排队的账户;后台每 24 小时也会读取一次;请求的模型不在目录中且距上次读取超过 10 分钟时,服务先读取一次再处理该请求 - 从未读取成功的账户权益显示为未知,并显示最近一次失败原因;已有目录的账户读取失败时照常使用,账户行显示“目录同步失败”与原因 - 读取报告 AI Studio 不支持当前出口地区时,已有目录的账户同样显示该原因 diff --git a/README_en.md b/README_en.md index 2756eec8..80a26495 100644 --- a/README_en.md +++ b/README_en.md @@ -282,7 +282,7 @@ 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, and media output; requests already in progress keep the settings they started with +- 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` @@ -357,12 +357,13 @@ For Cherry Studio: 4. Set the API key to `PROXY_API_KEY` from `.env` 5. Load models from `/v1/models`, or add `gemini-3.8-flash` and `gemini-3.5-flash-lite` manually -[Claude Code](https://github.com/anthropics/claude-code) uses the Anthropic endpoint. Subagents pick models by the opus, sonnet, and haiku tiers; the variables below map them to AI Studio models. WebSearch runs on Google Search: +[Claude Code](https://github.com/anthropics/claude-code) uses the Anthropic endpoint. Subagents pick models by the fable, opus, sonnet, and haiku tiers; the variables below map them to AI Studio models. WebSearch runs on Google Search: ```powershell $env:ANTHROPIC_BASE_URL = "http://127.0.0.1:2048" $env:ANTHROPIC_API_KEY = "" $env:ANTHROPIC_MODEL = "gemini-3.8-flash" +$env:ANTHROPIC_DEFAULT_FABLE_MODEL = "gemini-4-argon" $env:ANTHROPIC_DEFAULT_OPUS_MODEL = "gemini-3.1-pro-preview" $env:ANTHROPIC_DEFAULT_SONNET_MODEL = "gemini-3.8-flash" $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = "gemini-3.5-flash-lite" @@ -672,7 +673,7 @@ Process environment variables override the same keys in `.env`, and those settin | `ADMIN_PASSWORD` | empty | Administrator password, required when login is enabled | | `PROXY` | empty | HTTP, HTTPS, or SOCKS5 proxy used by Chrome import, login, and accounts without an override; separate several proxies with commas to form a proxy pool; the system proxy is used when empty | | `INIT_TIMEOUT` | `2m` | Per-account WAA initialization timeout | -| `REQUEST_TIMEOUT` | `30m` | Maximum request execution time, restarted at the start of each auto-continuation round | +| `REQUEST_TIMEOUT` | `30m` | Longest time upstream may send no data, counted from the start of the request until the first data too; requests that upstream is still streaming have no total time limit | | `WARM_WORKER_LIMIT` | `10`, `5` with Camoufox | Number of resident prewarmed accounts | | `MAX_ACTIVE_WORKERS` | `20`, `10` with Camoufox | Maximum workers active during peak load | | `WARM_STARTUP_CONCURRENCY` | `5` | Camoufox workers cold-started concurrently during on-demand scaling; prewarming starts workers one at a time; unlimited with `WAA_BACKEND=spidermonkey` | @@ -694,8 +695,12 @@ Process environment variables override the same keys in `.env`, and those settin | `GOOGLE_SEARCH` | `false` | Enable Google Search for OpenAI, Anthropic, Gemini, and Interactions generation requests, including ordinary model IDs and requests with function tools | | `CONTINUATION_REWRITE` | `true` | Rewrite requests ending with an assistant message as continuation requests on models without native continuation; when off, every model receives them unchanged and an upstream rejection is returned as is | | `CONTINUATION_PROMPT` | built-in English sentence | Prompt written into the system instruction together with the trailing assistant message when rewriting; when set empty, the trailing assistant message is sent as a user message | +| `REPLY_TOOL` | `false` | For roleplay only: declare an internal `final` tool so the model delivers the complete reply at once to reduce mid-stream truncation while keeping thinking streamed live; applies on save | +| `THINKING_GUARD` | `false` | Roleplay thinking anti-block: guide internal reasoning to stay brief and abstract without repeating sensitive terms and cap thinking effort at low, reducing upstream filter truncation during reasoning; applies on save | +| `USER_MESSAGE_REWRITE` | `off` | Rewrite Chinese text in user messages to Traditional Chinese or Martian Chinese before sending (leaving assistant history unchanged) and instruct the model to reply in Simplified Chinese by default; `off`, `traditional`, or `martian`; applies on save | | `FIRST_EVENT_HEDGE` | `off` | When a request has no first token for a while, send a backup request on an idle account; `off`, `auto`, or a wait in seconds | | `FIRST_EVENT_HEDGE_MODELS` | `gemini-4-argon` | Comma-separated model IDs that get backup requests; backup requests also count against account quota | +| `FIRST_EVENT_TIMEOUT` | `off` | Longest time a single attempt waits for its first upstream event after taking an account before cancelling and switching accounts; `off` or a positive integer in seconds | | `WAA_BACKEND` | `spidermonkey` | Where WAA runs: `spidermonkey` or `camoufox` | | `MEDIA_OUTPUT` | `inline` | How Chat Completions and Messages include generated images and audio: `inline` or `url` | | `MEDIA_BASE_URL` | empty | Service address used in media URLs, such as `https://ai.example.com`; empty uses the address of each request and follows `X-Forwarded-Proto` behind a reverse proxy | @@ -704,7 +709,7 @@ 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`: 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, and the remaining accounts are still tried in turn - `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`: @@ -715,6 +720,9 @@ Notes: - 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 - A positive integer is the wait in seconds; choosing Custom in settings fills in the recent p95 of the busiest model +- `FIRST_EVENT_TIMEOUT`: + - Each attempt is timed independently from taking an account until the first semantic event arrives; on timeout it cancels the attempt and switches accounts (counts toward `MAX_ACCOUNT_SWITCHES`, does not cool the account), returning 504 if no account is left + - With `FIRST_EVENT_HEDGE` enabled, the primary and backup requests keep separate timers and this should be set higher than the hedge wait; excludes background requests and background agent tasks; slow thinking requests may take several minutes before their first token - `WAA_BACKEND`: - `spidermonkey` runs WAA in SpiderMonkey inside the service process and neither downloads nor starts Camoufox; `camoufox` runs WAA in a Camoufox page; any other value means `spidermonkey` - When unset, startup picks it from `auth/` and writes it to `.env`: `camoufox` if `auth/` already has accounts but no `auth/.waa-interpreters`, otherwise `spidermonkey` @@ -805,7 +813,7 @@ Account actions depend on state. Click the state in an account row to set the ac Reading the benefit tier and model catalog: -- Refresh all reads the benefit tier and model catalog of every enabled account immediately; the service also reads them every 24 hours, and when a request names a model missing from the catalog and the last read was more than 10 minutes ago, the service reads them first and then handles the request +- Refresh all reads the benefit tier and model catalog of every enabled account immediately; it runs on the server and keeps going after the console is closed or reloaded, and reopening the console shows its progress and the queued accounts; the service also reads them every 24 hours, and when a request names a model missing from the catalog and the last read was more than 10 minutes ago, the service reads them first and then handles the request - An account whose catalog has never been read shows an unknown tier and the reason for the last failed read; an account with an existing catalog keeps working when a read fails, and its row shows "Model sync failed" with the reason - When a read reports that AI Studio does not support the current egress region, accounts with an existing catalog show that reason as well diff --git a/docs/build.md b/docs/build.md index 1aaf51e3..6b19c5d5 100644 --- a/docs/build.md +++ b/docs/build.md @@ -121,10 +121,16 @@ The tools listed earlier in your instructions (<工具名>) act on an empty remo - 客户端回传的历史格式不同(例如合并了相邻的 user 轮)时,按回传的格式转录 - trajectory 开启时没有转录历史的,续接时 field 9 只有说明与系统提示 -最后一组是 model 轮,或其本地 Token 数超过 24576 时,开启新 trajectory: +最后一组不是 model 轮、本地 Token 数超过 24576 且对话续接得上已有 trajectory 时,续接原 trajectory,只把最后一组写成 text/plain 最新消息文件: -- 最后一组也转录在 field 9 中 -- field 1 只提交用户轮 `Continue the conversation from the last turn of the conversation history at the end of your instructions.` +- 最新消息文件以说明与 ``、`` 转录最后一组,注明它不是说明文件、不替换之前的系统提示与函数声明 +- 最后一组中的附件按 `[attachment <序号>]` 编号,紧跟在最新消息文件之后;本轮同时提交说明文件时,最新消息文件排在说明文件之后 +- field 1 的文本为 `Continue the conversation from the attached latest user message file (not an instructions file).` + +最后一组是 model 轮,或其本地 Token 数超过 24576 且找不到可续接的 trajectory 时,开启新 trajectory: + +- 最后一组也转录在 field 9 或说明文件中 +- field 1 只提交用户轮 `Continue the conversation from the last turn of the conversation history at the end of your instructions.`(使用说明文件时为 `the instructions file`) - 转录轮次中的附件放在这一轮开头 ### 说明文件 @@ -193,6 +199,12 @@ Right after the block, call your ask_question tool once with the question "Run t The conversation before the first user message of this chat is transcribed at the end of this file between and : user turns between and , and your own earlier replies, including your function_calls blocks, between and . Attachments in it are numbered like [attachment 1] and are attached in the same order after this file at the start of the first user message of this chat. Continue the conversation from the latest message and never write these tags yourself. ```` +续接 trajectory 且最后一组超过 24576 token 时,最新消息文件开头的说明: + +````text +Latest user message (not an instructions file; keep all earlier system instructions, client functions and conversation history unchanged). The latest user message and tool results of this chat are transcribed below between and in blocks. Attachments in it are numbered like [attachment 1] and are attached right after this file in the same order. Continue the conversation from this latest message and never write these tags yourself. +```` + ### 工具、停止序列与思考强度 - Google Search 工具不写入请求:写代码助手按需调用内置的 `search_web`,搜索步骤按“任务流”输出为 grounding @@ -280,7 +292,7 @@ field 19 的 thinking level 取值: - 对话轮按连续的 model 轮与其余轮次分组,逐组累积 SHA-256 摘要。每组计入非思考正文 Part 直接连接后按空白归一的结果、函数调用的名称与键排序的参数、函数结果键排序的内容,其余 Part 去掉思考签名计入,内联数据以其 SHA-256 计入;调用 ID 不计入,客户端以不同格式回传同一回复时摘要相同 - 本轮回复完整结束、没有以 `malformed_function_call` 结束、没有调用被禁止的工作区内置工具、也没有在函数调用之后继续输出正文时,把“请求的对话 + 本轮回复的正文与函数调用”的续接位置写入该 trajectory,替换它之前的续接位置;最多保存 200 个 trajectory,超过时丢弃最早续接的 - 新请求最后一组之前最近的 model 轮组与某个续接位置相同时,续接该 trajectory:field 1 只提交该组之后的轮次,field 21 为 trajectory ID;回复没有完整结束时删除该续接位置 -- 找不到时在账户的应用中开启新 trajectory,最后一组之前的对话轮转录在 field 9 或说明文件中,见第 3 节;包括新对话、重新生成、编辑或压缩过的历史、回到较早的回复另起分支、另一个 API key、上一轮回复没有完整结束、最后一组过长或是 model 轮 +- 找不到时在账户的应用中开启新 trajectory,最后一组之前的对话轮转录在 field 9 或说明文件中,见第 3 节;包括新对话、重新生成、编辑或压缩过的历史、回到较早的回复另起分支、另一个 API key、上一轮回复没有完整结束或最后一组是 model 轮 - 账户没有应用时照官网新建应用,新应用的应用 ID 写入 `assistant.id` 并清空 trajectory;之后该账户的全部对话都在这个应用中,应用保留在该 Google 账户的 My apps 中 - 应用与续接位置保存在账户目录的运行状态中:同一 Google 账户在多个服务实例或账户目录中使用时,每份运行状态各自新建一个应用、各自续接;管理端删除账户时账户目录与运行状态一并删除,应用留在该 Google 账户的 My apps 中,再次导入该账户后新建应用 - 本进程第一次使用账户的应用时照官网打开它,见“RPC 顺序”;`GetApplet` 返回 404 时新建应用。应用已被删除或续接的 trajectory 不存在时,`CodeAssistantOffline` 返回 404 code 5;已打开的应用上 `CodeAssistantOffline` 返回 404 且还没有取得任务 ID 时,删除本轮续接的续接位置,重新打开应用(应用已不存在时新建)后重新提交本轮一次 diff --git a/docs/development.md b/docs/development.md index d780e9b3..ce2c3e5f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -228,6 +228,29 @@ HTTP route WebSocket 入口沿用相同分层:`internal/api` 解码公开协议,`internal/app` 绑定账户和运行状态,`internal/aistudio` 执行 WebChannel 与规范事件转换。公开适配器只消费规范请求与事件;账户文件、WAA 对象、原始数组和资源粘性由 `internal/aistudio` 与 `internal/app` 管理。 +一次请求中的决策点与负责代码(按请求流转顺序): + +| 决策 | 负责文件与函数 | +| --- | --- | +| 入口鉴权与账户范围 | `internal/api/middleware.go` `authMiddleware` / `accountContextMiddleware` | +| 模型映射、后缀与通道路由 | `internal/app/runtime.go` `trackedService.mappedModel`、`internal/aistudio/channel.go` `AccountPool.selectionChannelsLocked` | +| 模型能力判断 | `internal/aistudio/service.go` `AccountLease.Model`、`internal/aistudio/generate.go` `validateGenerateEntry` | +| 对话中途的系统消息 | `internal/api/generate.go` `appendWithReminders`、`internal/aistudio/turns.go` `normalizeTurns` | +| 续写 | `internal/aistudio/turns.go` `normalizeTurns`、`internal/aistudio/generate.go` `Client.decodePlaygroundRounds` | +| 自动压缩 | `internal/api/responses_compaction.go` `server.generateCompactionSummary`、`internal/api/anthropic_context.go` `server.applyAnthropicContextEdits` | +| 工具约束与 MCP 白名单 | `internal/aistudio/tool_contract.go` `prepareToolRequest`、`internal/api/openai.go` `restrictMCPServer` | +| 用户消息改写、思考防拦截与回复工具 | `internal/aistudio/chinese_rewrite.go` `applyChineseRewrite`、`internal/aistudio/thinking_guard.go` `applyThinkingGuard`、`internal/aistudio/reply_tool.go` `applyReplyTool` | +| 历史回复与状态续接 | `internal/aistudio/model_turns.go` `modelTurnHistory.restore`、`internal/api/responses.go` `server.prepareResponses` | +| 附件与媒体处理 | `internal/aistudio/upload.go` `PooledService.UploadInlineMediaToLease`、`internal/api/remote_media.go` `inlineRemoteMedia` | +| 选账户与 Worker 调度 | `internal/app/runtime.go` `trackedService.acquireWarmLease`、`internal/aistudio/accounts.go` `AccountPool.TryAcquireFor` | +| 备用请求与超时控制 | `internal/app/hedge.go` `trackedService.awaitFirstEvent`、`internal/app/runtime.go` `trackedService.startAttempt` | +| 换号与换号计数 | `internal/app/runtime.go` `trackedService.generateWithRetry` / `countSwitchFailure` | +| 冷却判定与冷却放行 | `internal/aistudio/quota.go` `QuotaCooldownForError`、`internal/aistudio/accounts.go` `selectionCooldown` | +| 认证续签与 DBSC 刷新 | `internal/app/auth_retry.go` `authRuntimeRefresher.do` / `ensureBoundAccount` | +| WAA 证明 | `internal/aistudio/service.go` `WorkerProtectedTransport.DoProtected`、`internal/aistudio/runtime_native.go` `NativeWorker.Prepare` | +| 上游出口与连接隔离 | `internal/aistudio/transport_http.go` `MakerSuiteHTTPTransport.clientForAccount`、`internal/aistudio/transport_browser.go` `browserRoundTripper.RoundTrip` | +| 内容拦截与错误映射 | `internal/aistudio/generate.go` `Client.Generate`、`internal/api/errors.go` `statusFromError` | + ### Camoufox 后端 Camoufox 由 Go 通过 WebDriver BiDi 直接管理。启动数据面时,服务按 `WARM_WORKER_LIMIT` 逐个准备隔离、无头、长驻的账户 runtime,并在需要其他账户能力时替换最久未用的空闲 runtime。 @@ -332,7 +355,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 | `ADMIN_PASSWORD` | 管理员密码 | 空 | | `PROXY` | 全局出口代理或代理池 | 空 | | `INIT_TIMEOUT` | 单账户初始化超时 | `2m` | -| `REQUEST_TIMEOUT` | 单次请求最大执行时间 | `30m` | +| `REQUEST_TIMEOUT` | 上游连续没有数据的最长时间 | `30m` | | `WARM_WORKER_LIMIT` | 常驻预热账户数 | `10`,Camoufox 后端 `5` | | `MAX_ACTIVE_WORKERS` | 活动 Worker 容量上限 | `20`,Camoufox 后端 `10` | | `WARM_STARTUP_CONCURRENCY` | 同时冷启动的 Camoufox Worker 数 | `5` | @@ -356,6 +379,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 | `CONTINUATION_PROMPT` | 续写提示词 | 内置英文续写句 | | `FIRST_EVENT_HEDGE` | 首字超时备用请求阈值 | `off` | | `FIRST_EVENT_HEDGE_MODELS` | 发起备用请求的模型 | `gemini-4-argon` | +| `FIRST_EVENT_TIMEOUT` | 单次尝试首字超时换号阈值 | `off` | | `WAA_BACKEND` | WAA 后端 | `spidermonkey` | | `MEDIA_OUTPUT` | 生成媒体的引用方式 | `inline` | | `MEDIA_BASE_URL` | 媒体 URL 的服务地址 | 空 | @@ -373,12 +397,12 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 - `LOG_MAX_TOTAL_MB`:超出时删除最旧的文件,不小于 20;保存后立即生效 - `ADMIN_PASSWORD`:开启登录时必填 - `PROXY`:setup 与未设置账户代理时使用的出口,多个代理用逗号分隔组成代理池;留空时生成服务使用系统代理 -- `REQUEST_TIMEOUT`:自动续写的每一轮开始时重新计时 +- `REQUEST_TIMEOUT`:从请求开始计时,每收到一次上游数据重新计时,上游仍在输出的请求不受总时长限制 - `MAX_ACTIVE_WORKERS`:必须不小于热池目标 - `WARM_STARTUP_CONCURRENCY`:限制按需扩容时的冷启动数,预热逐个启动;`WAA_BACKEND=spidermonkey` 时不限制 - `ROUTING_STRATEGY`:账户轮询 `round-robin` 或粘性优先 `fill-first` - `ACCOUNT_ORDER`:逗号分隔的账户 ID,`fill-first` 依次使用并按此顺序预热,未列出的账户排在后面并按 ID 排序;保存后立即生效 -- `MAX_ACCOUNT_SWITCHES`:一个请求因上游 401、403、404、5xx、连接断开等非额度失败换号的次数上限,`0` 为不换号,额度失败不计入;保存后立即生效 +- `MAX_ACCOUNT_SWITCHES`:一个请求因上游 403、404、5xx、连接断开、首字超时等非额度失败换号的次数上限,`0` 为不换号,登录失效与额度失败不计入;保存后立即生效 - `UPSTREAM_CHANNELS`:`playground`、`build`(旧通道,上游已停用其生成),逗号分隔 - `MODEL_MAPPING`:逗号分隔,每项以最后一个 `:` 分成别名与模型 ID;保存后立即生效 - `MODEL_CHANNELS`:逗号分隔,每项以最后一个 `:` 分成模型 ID 与通道 `playground` 或 `build`;保存后立即生效 @@ -395,6 +419,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 - `CONTINUATION_PROMPT`:改写时与末尾 assistant 正文一起写入系统指令;键存在且为空时,末尾 assistant 正文作为最后一轮 user;保存后停止再启动生成服务生效 - `FIRST_EVENT_HEDGE`:`off`、`auto`(各模型与通道近 24 小时原请求首字等待的 p95)或正整数秒 - `FIRST_EVENT_HEDGE_MODELS`:模型 ID,逗号分隔 +- `FIRST_EVENT_TIMEOUT`:`off` 或正整数秒,每次尝试从取得账户起到首个语义事件的上限;保存后停止再启动生成服务生效 - `WAA_BACKEND`:`spidermonkey` 或 `camoufox`,其他取值按 `spidermonkey`;未设置时,启动时按 `auth/` 确定后写入 `.env`:已有账户而没有 `.waa-interpreters` 时为 `camoufox`,否则为 `spidermonkey` - `MEDIA_OUTPUT`:Chat Completions 与 Messages 正文中生成媒体的引用方式,`inline` 或 `url` - `MEDIA_BASE_URL`:`http` 或 `https`;留空时取请求的协议与 Host @@ -420,7 +445,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等 | `discover_hidden_models` | 下一次启动生成服务时使用的官网隐藏模型探测开关 | | `google_search` | 保存后立即作用于新请求的全模型 Google 搜索开关 | | `continuation_rewrite`、`continuation_prompt` | 下一次启动生成服务时使用的末尾 assistant 轮改写开关与续写提示词 | -| `first_event_hedge`、`first_event_hedge_models` | 下一次启动生成服务时使用的首字超时备用请求设置与模型 | +| `first_event_hedge`、`first_event_hedge_models`、`first_event_timeout` | 下一次启动生成服务时使用的首字超时备用请求与单次首字超时设置 | | `strip_thought_signatures` | 下一次启动生成服务时使用的思考签名去除开关 | | `routing_strategy`、`account_order` | 保存后立即作用于账户选择的策略与 `fill-first` 顺序 | | `max_account_switches` | 保存后立即作用于换号判断的次数上限 | @@ -622,6 +647,11 @@ Worker 容量由热池目标、活动上限和单账户并发共同约束。 - 被取消的请求同样计入上游的每日与每分钟请求额度 - 账本的 `attempts` 以 `hedge` 标记备用请求,以 `superseded` 标记被取代的一方 +`FIRST_EVENT_TIMEOUT` 不为 `off` 时,除后台 Responses、后台 Interactions 与经后台任务生成的 agent(`interaction_task`)外,每次生成尝试(含 `-build` 写代码助手)从取得账户起等待首个语义事件达到阈值后,取消该尝试并换号: + +- 计入 `MAX_ACCOUNT_SWITCHES`,不冷却账户、不改账户状态、不重建 Worker;没有可换账户或换号用尽时返回 504 并写明 `FIRST_EVENT_TIMEOUT` +- 与 `FIRST_EVENT_HEDGE` 同开时原请求与备用请求各自计时,一方到期取消不影响另一方继续等待;`REQUEST_TIMEOUT` 管整个请求,更早到期时直接结束请求不换号 + 同一模型与通道最近两个请求都在本请求开始前 30 秒内以连接断开失败、其间没有请求收到首个事件时,本请求在前两个账户上的尝试也都以连接断开失败就以原错误结束。 故障重置先等待同账户的活动请求释放租约;等待期间该账户暂停接收新请求。客户端取消只结束自身请求。启动预热在官网 Run 按钮启用后提交,请求在发送前再次检查账户冷却状态。 @@ -730,7 +760,7 @@ Worker 容量由热池目标、活动上限和单账户并发共同约束。 | 健康与状态 | `GET /health`、`GET /api/status` | | 模型与账户 | `GET /api/models`、`GET/POST /api/accounts`、`GET /api/accounts/exits`、`GET/POST /api/accounts/import/chrome`、`GET /api/accounts/import/browsers`、`POST /api/accounts/import/cookies/discover`、`POST /api/accounts/import/cookies`、`PUT/DELETE /api/accounts/{id}`、`PUT /api/accounts/{id}/state` | | 账户任务 | `GET /api/accounts/tasks`、`DELETE /api/accounts/tasks/{id}` | -| 登录与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`GET /api/login-view/{view}`(WebSocket) | +| 登录与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`POST /api/accounts/refresh`、`GET /api/login-view/{view}`(WebSocket) | | 远程配对 | `GET /api/pairing`、`POST /api/pairing`、`POST /api/pairing/accounts`、`PUT /api/pairing/accounts/{account}/cookies` | | 生成服务 | `POST /api/control/start`、`POST /api/control/stop` | | 配置 | `GET /api/config`、`PUT /api/config`、`GET /api/paths?path=`(列出服务所在机器的目录与账户状态文件 `storage-state.json`,`path=roots` 列出文件系统根)、`POST /api/paths/pick?path=`(桌面版以系统对话框选择账户目录) | @@ -935,6 +965,12 @@ Windows 与 Linux 托盘菜单的“开机自启动”每次打开菜单时从 wails3 generate syso -arch amd64 -icon build/windows/icon.ico -manifest build/windows/wails.exe.manifest -info build/windows/info.json -out cmd/aistudio2api/rsrc_windows_amd64.syso ``` +- `internal/chromeauth/native/abe_helper_amd64.bin` 是 Windows Chrome 导入用于解密 App-Bound 主密钥的无导出 x64 DLL,使用上文的 llvm-mingw UCRT 版 clang 从 `abe_helper.c` 编译,只链接 Windows 系统库与系统 UCRT: + +```bash +x86_64-w64-mingw32-clang -shared -O2 -s -o internal/chromeauth/native/abe_helper_amd64.bin internal/chromeauth/native/abe_helper.c -lole32 -loleaut32 -lcrypt32 +``` + Camoufox 在首次浏览器登录时准备;`WAA_BACKEND=camoufox` 时在管理服务启动后于后台下载,生成服务等下载完成后就绪。 实现与评审按以下设计原则取舍: diff --git a/docs/images/accounts-dark.webp b/docs/images/accounts-dark.webp index 82ed69a4..0f5b584f 100644 Binary files a/docs/images/accounts-dark.webp and b/docs/images/accounts-dark.webp differ diff --git a/docs/images/accounts-light.webp b/docs/images/accounts-light.webp index 72b0ba2c..e912d9ef 100644 Binary files a/docs/images/accounts-light.webp and b/docs/images/accounts-light.webp differ diff --git a/docs/images/chat-dark.webp b/docs/images/chat-dark.webp index 71229b3e..3442ec48 100644 Binary files a/docs/images/chat-dark.webp and b/docs/images/chat-dark.webp differ diff --git a/docs/images/chat-light.webp b/docs/images/chat-light.webp index 6d2b8502..f560df97 100644 Binary files a/docs/images/chat-light.webp and b/docs/images/chat-light.webp differ diff --git a/docs/images/image-dark.webp b/docs/images/image-dark.webp index 92fa5c65..7b8bcc84 100644 Binary files a/docs/images/image-dark.webp and b/docs/images/image-dark.webp differ diff --git a/docs/images/image-light.webp b/docs/images/image-light.webp index e4bb593d..f073989e 100644 Binary files a/docs/images/image-light.webp and b/docs/images/image-light.webp differ diff --git a/docs/images/logs-dark.webp b/docs/images/logs-dark.webp index 7d770d8e..224565b8 100644 Binary files a/docs/images/logs-dark.webp and b/docs/images/logs-dark.webp differ diff --git a/docs/images/logs-light.webp b/docs/images/logs-light.webp index e40d733f..d9b89220 100644 Binary files a/docs/images/logs-light.webp and b/docs/images/logs-light.webp differ diff --git a/docs/images/models-dark.webp b/docs/images/models-dark.webp index 7d250ac1..1291232a 100644 Binary files a/docs/images/models-dark.webp and b/docs/images/models-dark.webp differ diff --git a/docs/images/models-light.webp b/docs/images/models-light.webp index 59434a35..701ea62b 100644 Binary files a/docs/images/models-light.webp and b/docs/images/models-light.webp differ diff --git a/docs/images/settings-dark.webp b/docs/images/settings-dark.webp index 513b3e5c..11efaf96 100644 Binary files a/docs/images/settings-dark.webp and b/docs/images/settings-dark.webp differ diff --git a/docs/images/settings-light.webp b/docs/images/settings-light.webp index eebf1f14..77ca9310 100644 Binary files a/docs/images/settings-light.webp and b/docs/images/settings-light.webp differ diff --git a/docs/images/usage-dark.webp b/docs/images/usage-dark.webp index a2ba6e0e..f247412a 100644 Binary files a/docs/images/usage-dark.webp and b/docs/images/usage-dark.webp differ diff --git a/docs/images/usage-light.webp b/docs/images/usage-light.webp index b94d1815..ba9b125f 100644 Binary files a/docs/images/usage-light.webp and b/docs/images/usage-light.webp differ diff --git a/docs/logging.md b/docs/logging.md index 0e43f55e..3e4b1c34 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -32,7 +32,7 @@ `INFO` 记录状态推进和完成结果,`WARN` 记录等待、切换与客户端取消,`ERROR` 记录失败结果。管理页面支持按级别、来源、消息、阶段名、字段名与字段取值筛选,日志正文可以选择和横向滚动。 -页面每行的消息列依次为展开箭头、状态位、标题与字段、行尾耗时,各行标题左缘对齐:请求的状态位为 HTTP 状态,阶段为进度或结束状态图标,单条运行事件为中性圆点;字段 `duration` 显示在行尾。 +页面每行的消息列依次为展开箭头、状态标签、标题与字段、行尾耗时,各行标题左缘对齐:请求的状态标签为 HTTP 状态或“处理中”,阶段为进度或结束状态名,单条运行事件没有状态标签;字段 `duration` 显示在行尾。展开的详情从行首开始。 带 `stage` 的运行事件在页面上按来源与阶段名合并为一张卡片,显示阶段名、当前进度 `step/steps` 与最新一步的消息和字段。带 `state` 的事件结束同一来源进行中的卡片并显示结束状态,没有进行中的卡片时自成一张已结束的卡片;步骤号不大于当前步骤时另起一张卡片。卡片位于首条消息的时间位置,展开详情可查看每一步的时间、消息与字段;级别、来源和文本筛选在任一步命中时显示该卡片。 @@ -214,6 +214,7 @@ ERROR account@example.com [WAA Worker 停止 failed] WAA Worker 停止失败 p - 展开详情可查看接口、输入用量、原始终止原因、事件时间线与 JSON - 时间线中每次换号为一行,显示账户、上游状态、按状态归类的原因与上游原文,点击展开该账户的全部事件;请求的来源按换号顺序写成 `A → B`,上游要求验证账户的 403 归为“需要验证账户”,跳转到拒绝页的归为“服务受限” - 连续的同类进度事件合为一行并标出次数,悬停次数查看每一次的时刻与字段 +- 时间线每步一行,依次为时刻、消息与耗时(`duration` 或 `waited`),其余字段在下方按名称与取值对齐;`等待模型继续输出` 与随后的 `模型继续输出` 合为一行“停顿 N 后继续”;`rpc`、`mode`、`network_bytes`、`network_idle`、`reasoning_events`、`text_events`、`last_event`、`current_event` 以及与卡片相同的模型和通道只在 JSON 中 ```text 22:11:47 200 gemini-3.8-flash 换号 5 403 ×3 429 ×2 4.76 s 工具调用 1 @@ -257,7 +258,7 @@ ERROR account@example.com [WAA Worker 停止 failed] WAA Worker 停止失败 p ## 流式等待 -连续 15 秒没有阶段进展时会写入诊断日志。请求在收到上游终态、客户端取消或达到 `REQUEST_TIMEOUT` 时结束。 +连续 15 秒没有阶段进展时会写入诊断日志。请求在收到上游终态、客户端取消或上游连续 `REQUEST_TIMEOUT` 没有数据时结束。流在完成前中断或上游异常结束而重新生成时,记一条“重新生成”,`attempt` 为第几次,`reason` 为中断错误或结束原因。 | 事件 | 当前停留位置 | 重点字段 | | --- | --- | --- | diff --git a/docs/protocol.md b/docs/protocol.md index d98ea558..17c99ce4 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -706,7 +706,7 @@ generation config 字段: - 模型只有 thinking level 能力时,显式 budget 按 0、1024、8192 以内与更大预算分别退化为 minimal、low、medium、high - 没有 thinking level 能力的模型忽略其余 effort;两类能力都缺少时同时忽略 budget -生成与计数请求的模型名可以带思考后缀 `<模型 ID>(<值>)`,例如 `gemini-4-argon(low)`、`gemini-2.5-pro(16384)`。值不区分大小写:`none`、`minimal`、`low`、`medium`、`high`、`xhigh`、`extra_high`、`max` 作为思考强度,非负整数作为思考预算,`auto` 与 `-1` 使用模型默认思考设置;后缀覆盖请求体中的思考强度与预算,去掉后缀的模型 ID 用于调度、请求日志与用量统计。其他值返回 400。 +生成与计数请求的模型名可以带思考后缀 `<模型 ID>(<值>)`,例如 `gemini-4-argon(low)`、`gemini-2.5-pro(16384)`。值不区分大小写:`none`、`minimal`、`low`、`medium`、`high`、`xhigh`、`extra_high`、`max` 作为思考强度,非负整数作为思考预算,`auto` 与 `-1` 使用模型默认思考设置;后缀覆盖请求体中的思考强度与预算,去掉后缀的模型 ID 用于调度、请求日志与用量统计。其他值返回 400。Claude Code 1M 上下文模式加在模型名末尾的 `[1m]`(不区分大小写)在完整模型名不是 `MODEL_MAPPING` 别名时去掉,例如 `gemini-4-argon(low)[1m]` 按 `gemini-4-argon(low)` 处理。 能力码 48 的模型在目录中另有 `<模型 ID>-build` 条目,经 Build 写代码助手生成,思考后缀写在 `-build` 之后,例如 `gemini-3.8-flash-build(low)`;条目定义、请求与流格式见 [Build 通道](build.md)。 @@ -955,7 +955,7 @@ ListModels 能力码 91(目录能力 `output_continuation`)的模型由官 - usage 以最后一轮为基础,visible output、thought 与 tool tokens 逐轮累加,total 为最后一轮 total 加之前各轮的这三项 - 未指定输出上限时,输出总量为模型的 `inputTokenLimit` - 输出总量超过 32768 的自动续写请求只经 Playground 调度;未指定输出上限且含 File Search、`serviceTier`、`store:false` 等经 Build 通道发送的设置时仍可经 Build,按 Build 的单轮上限发送 -- 请求期限为 `REQUEST_TIMEOUT`,每个续写轮开始时重新计时 +- 上游连续 `REQUEST_TIMEOUT` 没有数据时请求以超时结束,续写轮之间等待响应的时间同样计入 - 每个续写轮在日志中记一条“上游调用”,模式后附 `续写=<轮次>` 续写 token 可由其他账户接续:续写轮以 401、403、429 或 5xx 失败时,未指定账户、不含文件与内联媒体的请求换到本请求续写轮尚未失败的其他账户,以该账户的新 proof 重发同一续写轮,之后各轮沿用这个 proof。额度失败的账户按额度冷却规则冷却,用量明细记为最后生成的账户。 @@ -989,6 +989,7 @@ Build 通道的 Gemini API 终止原因去掉 `FINISH_REASON_` 前缀后转为 - 非流式请求丢弃被取代那一次的思考;流式请求已输出的思考保留,之后接着输出重新生成那一次的思考 - 每次重新生成从头匹配停止序列,上一次暂存的停止序列前缀丢弃 - 重新生成的请求发送失败时,本次生成以该错误结束 +- 每次重新生成在请求日志中记一条“重新生成”,写明第几次与原因(中断错误或结束原因) 两个通道第一次带终止原因的帧中的内容事件标记为结束帧,自动续写中转入下一轮的帧不标记;Gemini 流式输出把结束帧的内容放进最后一块。 @@ -1669,8 +1670,9 @@ GET/DELETE /v1beta/files/{file} 跨域与请求体: - `/v1*`、`/upload/` 与 `/health` 响应允许任意 origin,并以 `Access-Control-Expose-Headers: *` 暴露响应头 -- OPTIONS 预检跳过 API key 校验,允许 `GET/POST/PUT/DELETE/OPTIONS`,`Access-Control-Allow-Headers` 回显请求的 `Access-Control-Request-Headers` +- OPTIONS 预检跳过 API key 校验,允许 `GET/POST/PUT/PATCH/DELETE/OPTIONS`,`Access-Control-Allow-Headers` 回显请求的 `Access-Control-Request-Headers` - `/v1*` 请求体上限约为 684 MiB,可容纳 Base64 编码的 512 MiB 文件 +- 请求头 `Content-Encoding` 为 `gzip`、`x-gzip`、`zstd` 或它们以逗号相连(多个同名请求头按出现顺序相连)时按顺序解压请求体,解压后的正文同样受上限约束;无法解压返回 400,其他编码返回 415 - `/upload/v1beta/files` 使用相同的认证与请求体上限;可续传上传的分块请求发往 start 响应 `X-Goog-Upload-URL` 给出的地址,凭其中的 `upload_id` 鉴权,无需 API key 公开 `/v1`、`/v1beta` 与 `/upload/` 的请求带 `X-AIStudio-Account: <账户 ID>` 时,账户池只在该账户上选号,视频后台生成与可续传上传同样只用该账户;上游出错时返回该错误,不换到其他账户,账户冷却中的处理与只有这一个可用账户时相同;该账户仍受所用 key 的 `API_KEY_ACCOUNTS` 绑定限制,不受 `MODEL_ACCOUNTS` 限制。 @@ -1696,7 +1698,7 @@ GET/DELETE /v1beta/files/{file} | 生成服务 | `POST /api/control/start`、`POST /api/control/stop` | | 账户 | `GET /api/accounts`、`GET /api/accounts/exits`、`POST /api/accounts`、`GET/POST /api/accounts/import/chrome`、`GET /api/accounts/import/browsers`、`POST /api/accounts/import/cookies/discover`、`POST /api/accounts/import/cookies`、`PUT /api/accounts/{id}`、`PUT /api/accounts/{id}/state`、`DELETE /api/accounts/{id}` | | 账户任务 | `GET /api/accounts/tasks`、`DELETE /api/accounts/tasks/{id}` | -| 账户认证与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`GET /api/login-view/{view}`(WebSocket) | +| 账户认证与刷新 | `POST /api/accounts/{id}/login`、`POST /api/accounts/{id}/refresh`、`POST /api/accounts/refresh`、`GET /api/login-view/{view}`(WebSocket) | | 远程配对 | `GET /api/pairing`、`POST /api/pairing`、`POST /api/pairing/accounts`、`PUT /api/pairing/accounts/{account}/cookies` | | 配置 | `GET /api/config`、`PUT /api/config`、`GET /api/first-event-latency` | | 冷却与请求 | `GET /api/cooldowns`、`DELETE /api/accounts/{id}/cooldowns/{scope}`、`GET /api/requests`、`POST /api/requests/{id}/cancel` | @@ -1730,6 +1732,7 @@ GET/DELETE /v1beta/files/{file} | `PUT /api/accounts/{id}/state` | 200 | `{"account":AdminAccount}` | | `POST /api/accounts/{id}/login` | 202 | `{"task":AccountTask}` | | `POST /api/accounts/{id}/refresh` | 200 | `AccountRefresh` | +| `POST /api/accounts/refresh` | 202 | `{"task":AccountTask}` | | `DELETE /api/accounts/{id}` | 204 | 空 body | | `POST /api/control/start`、`stop` | 200 | `AdminStatus` | | `GET /api/config`、`PUT /api/config` | 200 | `RuntimeConfig` | @@ -1766,9 +1769,10 @@ GET/DELETE /v1beta/files/{file} - `GET /api/accounts/import/browsers` 为每个浏览器的每个会话各列一项,查询参数 `proxy` 为识别账户的请求出口,省略时用默认出口 - `POST /api/accounts/import/cookies` 中每项的 `auth_user` 选择导入的会话,省略时为 0;`email` 为识别会话时列出的邮箱,作为导入账户的邮箱,为空时按该会话的对话页识别 - 账户的 `auth_user` 写入 `account.json`,运行时以 `/u/N/` 页面与 `X-Goog-AuthUser: N` 访问官网;浏览器重新登录后为 0 -- 添加、导入与重新登录账户在账户任务中运行: +- 添加、导入、重新登录与刷新账户在账户任务中运行: - 请求解析 body 后返回 202 与任务;任务在服务端运行到结束,请求结束或管理页面关闭时继续 - 任务中的账户同时处理;单个账户失败时在该项记下错误码与原因,其他账户照常处理 + - `POST /api/accounts/refresh` 以 `{"ids":[账户 ID,...]}` 刷新所列账户,任务的 `kind` 为 `refresh`,各项的 `label` 为账户 ID;同时刷新 4 个账户,其余以 `pending` 排队 - 错误码:Cookie 无法解析或缺少登录 Cookie 为 `invalid_cookies`,调试地址连接或读取失败为 `cdp_unavailable`,账户目录已存在而账户不在列表中时为 `account_exists` - 导入或浏览器登录得到账户列表中已有的账户时,就地替换它的认证状态,保留文件资源绑定 - 有账户失败时任务以 `failed` 结束,否则为 `done` @@ -2361,7 +2365,7 @@ OpenAI Chat 与 Anthropic 省略转换后没有 parts 的空历史消息;纯 message 字段为 `role`、`content`、可选 `name`、`tool_call_id`、`tool_calls`、`function_call`,assistant 另有 `refusal` 与 `audio`。 -system、developer、user 与 assistant 消息的 `name` 以 `: ` 写在该消息第一段文本前,例如 `{"role":"system","name":"example_user","content":"Hi"}` 在系统指令中为 `example_user: Hi`;tool 消息的 `name` 为函数名。assistant tool call: +对话开头的 system 与 developer 消息进入系统指令,对话中途的按出现位置以 `` 并入相邻 user 轮。system、developer、user 与 assistant 消息的 `name` 以 `: ` 写在该消息第一段文本前,例如 `{"role":"system","name":"example_user","content":"Hi"}` 在系统指令中为 `example_user: Hi`;tool 消息的 `name` 为函数名。assistant tool call: ```json { @@ -2505,15 +2509,17 @@ Responses 的图片、视频与文件 Part 复用上述 data URL、file ID 与 Y | item | 映射 | | --- | --- | -| system/developer message | 文本进入系统指令,图片与文件移到首个 user 轮 | +| system/developer message | 开头的文本进入系统指令、图片与文件移到首个 user 轮;对话中途的(含经 `previous_response_id` 续接)按出现位置以 `` 与其媒体并入相邻 user 轮 | | `agent_message` | user 轮,`content` 中 `input_text` 的 `text` 与 `encrypted_content` 的 `encrypted_content` 依次作为文本 | | `custom_tool_call` | 函数调用,参数为 `{"input":}` | | `local_shell_call` | `local_shell` 函数调用,参数为去掉 `type` 的 `action` | | `shell_call` | `shell` 函数调用,参数为 `action` | | `apply_patch_call` | `apply_patch` 函数调用,参数为 `operation` | -| `custom_tool_call_output`、`local_shell_call_output`、`shell_call_output`、`apply_patch_call_output` | 按 `call_id` 关联的函数结果 | +| `custom_tool_call_output`、`local_shell_call_output`、`shell_call_output`、`apply_patch_call_output` | 按 `call_id` 关联的函数结果;`function_call_output` 等的 `status` 为 `incomplete` 时结果为 `{"status":"incomplete","output":...}`,`output` 为带媒体内容字段(如 `image_url`、`file_data`、`source`、`data`)的单个媒体块对象时按只含它的块数组处理 | +| `reasoning` | `encrypted_content` 作为随后函数调用的签名,没有 `encrypted_content` 的 reasoning 项不改变待用的签名 | | `computer_call` | `computer` 函数调用,参数为 `action`,或 `{"actions":[...]}` | -| `web_search_call`、`code_interpreter_call`、`file_search_call`、`mcp_call`、`mcp_list_tools`、`mcp_approval_request`、`tool_search_call`、`tool_search_output`、`program`、`program_output` | assistant 文本摘要 ` `;输入含 `mcp_approval_response` 时 `mcp_approval_request` 为 `mcp____` 函数调用,带 `approval_request_id` 的 `mcp_call` 并入对应函数结果 | +| `tool_search_call`、`tool_search_output`(`execution` 为 `client`) | `tool_search` 函数的调用与按 `call_id` 关联的结果,结果为 `{"status","tools":[<工具名>]}`;`tool_search_output.tools` 中的工具并入请求的工具列表,与已有工具同名时只声明一次,同名命名空间合并成员,结果中的命名空间列出 `<命名空间>.<成员>` | +| `web_search_call`、`code_interpreter_call`、`file_search_call`、`mcp_call`、`mcp_list_tools`、`mcp_approval_request`、服务端执行的 `tool_search_call` 与 `tool_search_output`、`program`、`program_output` | assistant 文本摘要 ` `;输入含 `mcp_approval_response` 时 `mcp_approval_request` 为 `mcp____` 函数调用,带 `approval_request_id` 的 `mcp_call` 并入对应函数结果 | | `additional_tools` | `tools` 并入请求的工具列表 | | `configuration_update` | 最后一个带 `reasoning.effort` 的项覆盖请求的推理强度 | | `image_generation_call` | assistant 文本摘要与 `result` 图片 | @@ -2523,7 +2529,7 @@ Responses 的图片、视频与文件 Part 复用上述 data URL、file ID 与 Y | `compaction` | 摘要 user 轮与原样保留的条目,见下文上下文压缩 | | `compaction_trigger` | 压缩当前上下文,必须是最后一个输入项,其他位置返回 400 | -文本摘要的 JSON 省略 `id`、`type` 与 `status`。函数结果项缺少 `call_id` 时使用 `id`;`apply_patch_call_output` 的结果为 `{"status","output"}`。没有 `type` 与 `role`、只带 `id` 的项按 `item_reference` 展开,找不到同 ID 的项时返回 400。system/developer message 的图片与文件在没有 user 轮时单独组成首个 user 轮。 +文本摘要的 JSON 省略 `id`、`type` 与 `status`。函数结果项缺少 `call_id` 时使用 `id`;`apply_patch_call_output` 的结果为 `{"status","output"}`。没有 `type` 与 `role`、只带 `id` 的项按 `item_reference` 展开,找不到同 ID 的项时返回 400。开头 system/developer message 的图片与文件在没有 user 轮时单独组成首个 user 轮。 Responses tool 字段: @@ -2540,7 +2546,8 @@ Responses tool 字段: | `image_generation` | 图片模型按与 `POST /v1/images/generations` 相同的规则处理 `size`、`quality`、`output_format` 与 `output_compression`;`input_image_mask` 见下文 | | `computer_use_preview`、`computer` | 名为 `computer` 的函数;`computer_use_preview` 的 `display_width`、`display_height` 与 `environment` 写入描述,参数为单个 `action`,`computer` 的参数为 `actions` 列表 | | `mcp` | 上游 MCP 服务器:`server_label`、`server_url`、`authorization`、`headers`、`allowed_tools`(数组或 `tool_names`),`server_description` 写入系统指令 | -| `file_search`、`tool_search`、`programmatic_tool_calling` | 接受但不声明 | +| `tool_search`(`execution:"client"`) | 名为 `tool_search` 的函数,说明与参数取声明中的 `description` 与 `parameters`,没有时参数为 `query` 与 `limit` | +| `file_search`、服务端执行的 `tool_search`、`programmatic_tool_calling` | 接受但不声明 | - web search 工具的 `search_context_size`、`user_location` 与 `filters.allowed_domains` 写入搜索指令,域名限制使用 `site:` 查询;上游 grounding query 与 sources 原样返回 - `search_content_types` 只含 `image` 时只开启图片搜索,同时含 `text` 时同时开启网页搜索;图片搜索查询同样输出为 `web_search_call` @@ -2550,7 +2557,7 @@ Responses tool 字段: - 需要批准的工具由服务经出口代理读取 `tools/list`,声明为 `mcp____` 函数;模型调用时输出 `mcp_approval_request` 项(`id` 为 `mcpr_` 加调用 ID)并结束本轮 - 下一轮输入给出 `mcp_approval_response` 且 `approve` 为 true 时,服务以 `tools/call` 调用该工具,结果以带 `approval_request_id` 的 `mcp_call` 项排在本轮输出首位;客户端回传该 `mcp_call` 时服务直接使用其中的结果 - `mcp_call` 失败时 `status` 为 `failed`,流式输出以 `response.mcp_call.failed` 结束该项:工具结果的 `isError` 为 true 时 `error.type` 为 `mcp_tool_execution_error`、`content` 为结果内容;服务调用批准的工具时连接或协议出错为 `mcp_protocol_error` - - 需要批准的工具按 `tool_choice` 展开:为 `none` 或指定函数时跳过 `tools/list`;为 `mcp` 或 `allowed_tools` 时只声明其中列出的服务器与工具;`allowed_tools` 同时列出函数时,声明的 MCP 工具函数也加入允许调用的函数 + - 需要批准的工具按 `tool_choice` 展开:为 `none` 或指定函数时跳过 `tools/list`;为 `mcp` 或 `allowed_tools` 时与服务器的 `allowed_tools` 取交集,交集为空或白名单为空时不声明也不发送该服务器;`allowed_tools` 同时列出函数时,声明的 MCP 工具函数也加入允许调用的函数 - `additional_tools` 输入项中的 `mcp` 工具与 `tools` 中的相同 - `connector_id` 返回 400 - `allowed_tools.read_only:true` 时服务经出口代理以 `server_url` 与请求头读取该服务器的 `tools/list`,只允许 `annotations.readOnlyHint` 为 true 的工具;同时给出 `tool_names` 时取交集;没有允许的工具时跳过该服务器;`tools/list` 失败返回 400 并说明原因 @@ -2566,7 +2573,7 @@ Responses tool 字段: | `allowed_tools` | `mode`(`auto` 或 `required`)与允许的函数名,请求只发送列表中的函数与托管工具对应的 Google 工具 | | `web_search`、`web_search_2025_08_26`、`web_search_preview`、`web_search_preview_2025_03_11`、`code_interpreter`、`url_context`、`google_maps`、`image_search` | `required`,本次只允许该工具 | | `computer`、`computer_use`、`computer_use_preview` | 必须调用 `computer` 函数 | -| `mcp` | `required`,带 `name` 时只允许该服务器的该工具 | +| `mcp` | `required`,带 `name` 时与服务器的 `allowed_tools` 取交集,交集为空时不发送该服务器 | | `file_search`、`image_generation`、`programmatic_tool_calling`、`tool_search` | `auto` | 响应 shell 的字段始终存在: @@ -2611,9 +2618,10 @@ output item 联合类型: | type | 字段 | | --- | --- | | `reasoning` | `id`、`status`、`summary:[{type:"summary_text",text}]`、可选 `encrypted_content`;摘要文本只在请求 `reasoning.summary`(或 `generate_summary`)为 `auto`、`concise`、`detailed` 时返回 | -| `message` | `id`、`status`、`role:"assistant"`、`content:[{type:"output_text",text,annotations}]` | -| `function_call` | `id`、`status`、`call_id`、`name`、`arguments` | -| `custom_tool_call` | `id`、`status`、`call_id`、`name`、`input`,可选 `namespace` | +| `message` | `id`、`status`、`role:"assistant"`、`content:[{type:"output_text",text,annotations,logprobs:[]}]` | +| `function_call` | `id`(`fc_` 开头)、`status`、`call_id`、`name`、`arguments`;`collaboration` 命名空间的 `spawn_agent`、`send_message`、`followup_task` 另带 `encrypted_function_args:[]` | +| `custom_tool_call` | `id`(`ctc_` 开头)、`status`、`call_id`、`name`、`input`,可选 `namespace` | +| `tool_search_call` | 客户端执行的 `tool_search` 被调用时输出:`id`(`tsc_` 开头)、`status`、`call_id`、`execution:"client"`、`arguments` 对象 | | `local_shell_call` | `id`、`status`、`call_id`、`action:{type:"exec",command,env,...}` | | `shell_call` | `id`、`status`、`call_id`、`action:{commands,timeout_ms,max_output_length}`、`environment:null` | | `apply_patch_call` | `id`、`status`、`call_id`、`operation:{type,path,diff}` | @@ -2685,7 +2693,7 @@ Responses usage: - `POST /v1/responses/compact` 为无状态端点,接受 `model`(必需)、`input`、`instructions`、`tools` 与 `previous_response_id`;`input` 的转换、`item_reference`、媒体与续接链同 `POST /v1/responses` - 压缩先在续接链与输入的条目中确定原样保留部分:从最新条目向前,以完整的模型侧条目组(reasoning、assistant 消息与各类调用,连同其后的工具输出)或 user 消息为单位累计,约 20000 token 内的部分原样保留,最新一组总是保留,切点不落在工具输出上;token 按每 4 字节 1 个估算,消息只计文本、每张图片计 765,其他条目不计 `encrypted_content` - 原样保留部分之前的条目去掉 developer 与 system 消息后由请求的模型非流式生成摘要,去掉后没有条目时不调用上游、摘要为空: - - 系统指令与工具同请求,`tool_choice` 为 `none`,末尾追加一个 user 轮,为 OMP 的结构化交接摘要提示词(Goal、Constraints & Preferences、Progress、Key Decisions、Next Steps、Critical Context、Additional Notes) + - 系统指令与工具同请求,`tool_choice` 为 `none`,不沿用调用方的输出格式、输出上限与停止词,末尾追加一个 user 轮,为 OMP 的结构化交接摘要提示词(Goal、Constraints & Preferences、Progress、Key Decisions、Next Steps、Critical Context、Additional Notes) - 输入已含 compaction 项时,只摘要其原样条目与之后的新条目,旧摘要以 `` 包裹作为首个 user 轮,末尾改用增量摘要提示词 - 没有需要摘要的条目时不调用上游 - 摘要的结束原因不是 `stop` 时返回错误 @@ -2718,8 +2726,10 @@ Responses usage: | `context_management` | `{edits:[...]}`,见下文上下文管理 | - `system` 消息以 `` 包裹并入相邻的用户内容:前一条为 user 时追加在其末尾,否则并入下一条 user 消息、排在其 `tool_result` 之后,使函数调用之后紧跟函数结果 -- `system` 消息中的 `tool_addition` 与 `tool_removal` 块按出现顺序增删声明的工具:`tool_reference` 按 `name` 引用 `tools` 中的工具(含 `defer_loading` 工具,`tools` 中的工具都声明给上游),`tool_definition` 的 `definition` 加入工具列表,`tool_removal` 移除同名工具 +- `system`、`user` 与 `assistant` 消息中的 `tool_addition` 与 `tool_removal` 块按出现顺序增删声明的工具,块以 `tool` 给出一个工具或以 `tools` 给出多个,这两类块不进入对话内容:`tool_reference` 按 `name` 引用 `tools` 中的工具(含 `defer_loading` 工具,`tools` 中的工具都声明给上游),`tool_definition` 的 `definition` 加入工具列表,`tool_removal` 移除同名工具 - `output_config.format` 的 `json_schema` 设置结构化输出,其他 type 返回 `400 invalid_request_error` +- `thinking.type:"disabled"` 时使用模型最低思考档位,`output_config.effort` 不改变它;对话中途 `system` 消息的 `output_config.effort` 覆盖顶层的 `output_config.effort`,最后一个生效 +- 已开始流式响应后,5xx 原因的流内 `error` 事件 `error.type` 为 `overloaded_error`,消息为真实原因 - `thinking.display:"omitted"` 时 thinking block 的正文为空,签名照常返回 message content 可以是 string 或 block 数组: @@ -2815,7 +2825,7 @@ Anthropic 定义的客户端工具以请求中的 `name` 声明为函数,描 - `clear_tool_inputs` 为 true 或包含该工具名时调用的 input 改为 `{}` - 清理的 token 少于 `clear_at_least.value` 时不清理 - `compact_20260112`: - - 输入超过 `trigger.value`(默认 150000)时,请求的模型以 `instructions` 非流式生成摘要,省略时使用官方文档的摘要提示词,`tool_choice` 为 none + - 输入超过 `trigger.value`(默认 150000)时,请求的模型以 `instructions` 非流式生成摘要,省略时使用官方文档的摘要提示词,`tool_choice` 为 none,不沿用调用方的输出格式、输出上限与停止词 - 摘要以 `` 包裹时取其中的文本,与 Responses 相同的摘要 user 轮替换全部历史后继续生成。响应 content 首个 block 为 `{type:"compaction",content:<摘要>,encrypted_content:null}`,`pause_after_compaction:true` 时只返回该块,stop reason 为 `compaction` - 未知 edit type 与 `keep`、`trigger` 形状返回 `400 invalid_request_error` - 带 `context_management` 时,非流式响应与流式 `message_delta` 输出 `context_management:{applied_edits:[...]}`,列出实际清理的编辑及其 `cleared_tool_uses` 或 `cleared_thinking_turns` 与 `cleared_input_tokens`: @@ -2962,7 +2972,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,Lyria 等返回的 MP3 先解码为 PCM;请求 `audio/mp3` 且未改采样率、未指定 `bit_rate` 时原样返回上游 MP3 +- TTS 上游为 24 kHz、16-bit 小端、单声道 PCM,上游返回 WAV 时剥去 RIFF 头取 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` 逐块输出,其余情况在音频汇总完成后发送一个完整块 @@ -3201,7 +3211,7 @@ tool group 字段: `:countTokens` 也接受把生成请求放在 `generateContentRequest`(或 `generate_content_request`)中的包装形式,按其中的 `contents`、`systemInstruction` 与 `tools` 计数。 -`systemInstruction` 的各文本 Part 作为系统指令的独立分段发送,图片与文件 Part 移到首个 user 轮开头,函数调用与函数结果各以 Gemini API JSON 文本(如 `{"functionCall":{"args":{"city":"Paris"},"name":"get_weather"}}`)作为一个分段。 +`systemInstruction` 的各文本 Part 作为系统指令的独立分段发送,图片与文件 Part 移到首个 user 轮开头,函数调用与函数结果各以 Gemini API JSON 文本(如 `{"functionCall":{"args":{"city":"Paris"},"name":"get_weather"}}`)作为一个分段。`contents` 中 `role` 为 `system` 或 `developer` 的轮按 `systemInstruction` 的方式把函数调用与函数结果转为 JSON 文本,在首个对话轮之前时文本并入系统指令,在对话中途时以 `` 包裹并入相邻的 user 轮,图片与文件移到首个 user 轮开头。 `serviceTier` 取 `standard`、`flex`、`priority`,`store:false` 与 `labels` 经 Build 通道发送;`safetySettings` 中的 `HARM_CATEGORY_JAILBREAK` 同样经 Build 通道发送。Build 通道响应的 `usageMetadata.serviceTier` 为上游实际使用的等级。 @@ -3931,9 +3941,9 @@ Gemini 列中注明状态码的行以该状态码返回;Interactions 路由与 | 候选账户均在冷却且在本请求累计排队 1 分钟内不恢复,或已试账户都因额度失败而其余账户在冷却(套餐限额与每日限额冷却中的账户逐个发送一次,其中 5 到 60 分钟内拒绝过同样大或更小请求的账户、收到其他额度失败且该失败的冷却没有结束的账户跳过,全部拒绝时返回最后一次拒绝,全部跳过时立即返回;带 `Retry-After`,Gemini 错误体带 `RetryInfo`) | 429 | `rate_limit_exceeded` | `rate_limit_error` | `RESOURCE_EXHAUSTED` | | 上游过载 | 529 | `upstream_error` | `overloaded_error` | `INTERNAL` | | 当前客户端请求被管理端取消 | 503 | `request_canceled` | `api_error` | `UNAVAILABLE` | -| 生成服务已停止 | 503 | `service_stopped` | `api_error` | `UNAVAILABLE` | +| 生成服务已停止,包括停止时进行中的请求 | 503 | `service_stopped` | `api_error` | `UNAVAILABLE` | | 生成服务正在启动且模型目录尚未就绪 | 503 | `service_starting` | `api_error` | `UNAVAILABLE` | -| 请求期限到期 | 504 | `upstream_error` | `timeout_error` | `DEADLINE_EXCEEDED` | +| 上游连续 `REQUEST_TIMEOUT` 没有数据 | 504 | `upstream_error` | `timeout_error` | `DEADLINE_EXCEEDED` | | 传输、Content-Type、解码或缺失终态 | 502 | `upstream_error` | `api_error` | `INTERNAL` | | 上游以内容策略类原因结束生成或以 `other`、`image_safety` 拦截请求 | 502 | `upstream_error` | `api_error` | `INTERNAL` | | 上游异常结束、重新生成后仍如此且没有输出 | 502 | `upstream_error` | `api_error` | 200 与对应 `finishReason` | @@ -3944,7 +3954,7 @@ Gemini 列中注明状态码的行以该状态码返回;Interactions 路由与 - “支持请求的账户均不可调度”指这些账户都处于需要重新登录、服务受限、不可用或已停用状态,错误消息按状态给出账户数,例如 `No account can serve this request (accounts sign-in required: 2, service restricted: 1)` - 管理端启动生成服务期间到达的公开 API 请求等启动结束再处理;生成服务处于 `STOPPED` 时,生成与计数端点返回 `service_stopped`,错误消息说明在管理页面点击“启动服务”或开启“自动启动生成服务” - OpenAI 错误对象的 `type` 在参数、认证、权限与资源不存在时为 `invalid_request_error`,429 为 `requests`,其余为 `server_error`;`param` 为 `null` -- Responses 流中的 `response.failed` 的 `error.code` 取官方枚举:429 为 `rate_limit_exceeded`,400 为 `invalid_prompt`,其余为 `server_error` +- Responses 流中的 `response.failed` 的 `error.code` 取官方枚举:429 为 `rate_limit_exceeded`,400 为 `invalid_prompt`,其余为 `server_error`;输入 token 超过模型上限时为 `context_length_exceeded` - 错误消息为英文:上游错误为上游原文,例如 `You've reached your usage limit…`;服务自身的错误为英文说明,5xx 只给出最内层原因;消息中的邮箱地址写作 `[account]`;管理端请求记录保留完整原因,含上游方法、HTTP 状态、协议错误码与账户 - 可重试的 OpenAI 与 Anthropic 错误消息末尾另起一句 `Please try again in <秒数>s.`,秒数与 Retry-After 相同;已开始流式响应后的错误事件同样带这句,Gemini 流内错误对象带 RetryInfo - 候选账户均在冷却时,消息在最早恢复时间后附上该冷却的类型与触发它的上游原文,例如 `Daily limit: … limit: 100, model: gemini-3.8-flash …` diff --git a/go.mod b/go.mod index 80e38cb7..590eea87 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/bogdanfinn/utls v1.7.7-barnius github.com/brainplusplus/go-browserforge v0.1.0 github.com/dlclark/regexp2/v2 v2.5.2 + github.com/go-ego/gocc v0.10.0 github.com/godbus/dbus/v5 v5.2.2 github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 @@ -66,6 +67,7 @@ require ( github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect github.com/tphakala/simd v1.15.0 // indirect + github.com/vcaesar/cedar v0.50.1 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect golang.org/x/crypto v0.57.0 // indirect diff --git a/go.sum b/go.sum index 1d7c850d..1d7fb42f 100644 --- a/go.sum +++ b/go.sum @@ -40,6 +40,8 @@ github.com/dlclark/regexp2/v2 v2.5.2 h1:HAsucWRhsqcDzl6Ua9aR8JwYOTzrZyPrF0/FNxJV github.com/dlclark/regexp2/v2 v2.5.2/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0= github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= +github.com/go-ego/gocc v0.10.0 h1:PLgtMnmP1eGs1pjNxIB0kZCdgAss2/U2ZkTrUptLIeY= +github.com/go-ego/gocc v0.10.0/go.mod h1:Ek/gRkY2iOZ/bNe8pxZcDFyUPSzW4bLO+bbAf73amN8= github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU= github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= @@ -115,6 +117,10 @@ github.com/tphakala/go-aac v0.7.2 h1:jUJG92lq5tNLEABdL1Ph4whaTgPwopiA+t8FKwaMXro github.com/tphakala/go-aac v0.7.2/go.mod h1:I+Cu4G/0EvZbLOG1PVyDCKGp6c7Rte838nkCv8r66l8= github.com/tphakala/simd v1.15.0 h1:DFFqn42R1G0U0nSKKZZ0ZHQl8HDvUPTiPnA/hcVQrHU= github.com/tphakala/simd v1.15.0/go.mod h1:eO53GkWg40mRbr2tzs0Xb1IMZQ5U8cMR+Aa1RlXUinE= +github.com/vcaesar/cedar v0.50.1 h1:JhchIiYZyvjT7EhjMR3oN7JH7QNgeqLrw/zaPBrTWRQ= +github.com/vcaesar/cedar v0.50.1/go.mod h1:eHvpmJXJmOowP8mW/Xqjra+HmKovJNcRxRPtezHjh7I= +github.com/vcaesar/tt v0.40.0 h1:vWUNRJn13ozP3xXlAXV5q9WivaDSHRS2jQ2J2ayCvQs= +github.com/vcaesar/tt v0.40.0/go.mod h1:cH2+AwGAJm19Wa6xvEa+0r+sXDJBT0QgNQey6mwqLeU= github.com/vearutop/statigz v1.5.0 h1:FuWwZiT82yBw4xbWdWIawiP2XFTyEPhIo8upRxiKLqk= github.com/vearutop/statigz v1.5.0/go.mod h1:oHmjFf3izfCO804Di1ZjB666P3fAlVzJEx2k6jNt/Gk= github.com/wailsapp/wails/v3 v3.0.0-beta.29 h1:oJbXasfieQmMkYtqPlFSPnDe0RwpzA5BKiov8WPD5lo= diff --git a/internal/aistudio/accounts.go b/internal/aistudio/accounts.go index 10d7924f..074c276f 100644 --- a/internal/aistudio/accounts.go +++ b/internal/aistudio/accounts.go @@ -26,6 +26,7 @@ import ( "sync/atomic" "time" "unicode" + "unicode/utf8" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" appconfig "github.com/Mag1cFall/AIStudio2API/internal/config" @@ -164,9 +165,24 @@ func accountStateReason(account *Account) string { return reason } +// MaxAccountNoteLength 是账户备注允许的最大字符数 +const MaxAccountNoteLength = 120 + +// TruncateAccountNote 规范化账户备注:去掉首尾空白、折叠换行并在超过长度上限时按字符截断 +func TruncateAccountNote(note string) string { + cleaned := strings.Join(strings.FieldsFunc(strings.TrimSpace(note), func(r rune) bool { + return r == '\r' || r == '\n' + }), " ") + if utf8.RuneCountInString(cleaned) <= MaxAccountNoteLength { + return cleaned + } + return strings.TrimSpace(string([]rune(cleaned)[:MaxAccountNoteLength])) +} + // AccountConfig 表示账户目录中的固定最小配置 type AccountConfig struct { Label string `json:"label"` + Note string `json:"note,omitempty"` Enabled bool `json:"enabled"` Proxy string `json:"proxy"` Locale string `json:"locale"` @@ -359,6 +375,7 @@ type Account struct { type AccountStatus struct { ID string `json:"id"` Label string `json:"label"` + Note string `json:"note,omitempty"` State AccountState `json:"state"` Enabled bool `json:"enabled"` Proxy string `json:"proxy"` @@ -389,6 +406,10 @@ type AccountStatus struct { // HiddenDiscovered 表示账户目录同步时探测过官网隐藏模型,HiddenModels 是目录中的官网隐藏模型数 HiddenDiscovered bool `json:"-"` HiddenModels int `json:"-"` + // VerificationRequired 表示账户因上游要求验证而受限,可在官网验证页完成验证后恢复 + VerificationRequired bool `json:"verification_required,omitempty"` + // DeviceBoundSession 表示账户会话带 __Secure-1PSIDRTS 且缺少本地续签材料,约 2 小时内失效 + DeviceBoundSession bool `json:"device_bound_session,omitempty"` } // AccountTransition 是账户正在进行的后台操作 @@ -861,6 +882,9 @@ func (c AccountConfig) Validate() error { if c.AuthUser < 0 || c.AuthUser > 9 { return fmt.Errorf("账户 auth_user 无效: %d", c.AuthUser) } + if utf8.RuneCountInString(strings.TrimSpace(c.Note)) > MaxAccountNoteLength { + return fmt.Errorf("账户备注不能超过 %d 个字符", MaxAccountNoteLength) + } if err := appconfig.ValidateProxy(c.Proxy); err != nil { return fmt.Errorf("账户 proxy 无效: %w", err) } @@ -1890,6 +1914,34 @@ func (p *AccountPool) applyEnabledLocked(account *Account) { p.notifyLocked() } +// SetNote 写回账户备注并立即生效,不等待账户上的在途请求 +func (p *AccountPool) SetNote(accountID string, note string) (*Account, error) { + accountID = strings.TrimSpace(accountID) + note = strings.TrimSpace(note) + p.mu.Lock() + account := p.byID[accountID] + p.mu.Unlock() + if account == nil { + return nil, fmt.Errorf("%w: %s", ErrAccountNotFound, accountID) + } + account.storageMu.Lock() + defer account.storageMu.Unlock() + p.mu.Lock() + value := account.Config + p.mu.Unlock() + value.Note = note + if err := value.Validate(); err != nil { + return nil, err + } + if err := writeAccountConfig(account.ConfigPath, value); err != nil { + return nil, err + } + p.mu.Lock() + defer p.mu.Unlock() + account.Config.Note = note + return account, nil +} + // SetEnabled 写回账户启用状态并立即生效,不等待账户上的在途请求 func (p *AccountPool) SetEnabled(accountID string, enabled bool) (*Account, error) { accountID = strings.TrimSpace(accountID) @@ -1947,6 +1999,29 @@ func (p *AccountPool) setProgressLocked(current *accountProgress, next accountPr p.notifyLocked() } +// ReloadStorageState 重新读取账户的认证状态 +func (p *AccountPool) ReloadStorageState(accountID string) (StorageState, error) { + account, err := p.Account(accountID) + if err != nil { + return StorageState{}, err + } + return p.reloadStorageState(account) +} + +// reloadStorageState 在账户存储锁内从磁盘读取认证状态并同步到池内缓存 +func (p *AccountPool) reloadStorageState(account *Account) (StorageState, error) { + account.storageMu.Lock() + defer account.storageMu.Unlock() + state, err := LoadStorageState(account.StoragePath) + if err != nil { + return StorageState{}, err + } + p.mu.Lock() + account.StorageState = state + p.mu.Unlock() + return state, nil +} + // ReloadStorageState 在租约内重新读取认证状态 func (l *AccountLease) ReloadStorageState() (StorageState, error) { l.operation.Lock() @@ -1954,16 +2029,7 @@ func (l *AccountLease) ReloadStorageState() (StorageState, error) { if l.released { return StorageState{}, fmt.Errorf("账户租约已释放") } - l.account.storageMu.Lock() - defer l.account.storageMu.Unlock() - state, err := LoadStorageState(l.account.StoragePath) - if err != nil { - return StorageState{}, err - } - l.pool.mu.Lock() - l.account.StorageState = state - l.pool.mu.Unlock() - return state, nil + return l.pool.reloadStorageState(l.account) } // ReplaceCookies 以固定指纹浏览器当前 Cookie 替换账户最新持久状态,只有轮换 Cookie 变化且磁盘状态在 rotatingCookieWriteInterval 内写过时不写盘 @@ -2055,30 +2121,44 @@ func (l *AccountLease) ReplaceResource(previousResourceID string, resourceID str } // MergeSetCookieHeaders 将响应 Cookie 合并到账户最新持久状态 -func (l *AccountLease) MergeSetCookieHeaders(headers []string, requestURL string, now time.Time) error { - l.operation.Lock() - defer l.operation.Unlock() - if l.released { - return fmt.Errorf("账户租约已释放") +func (p *AccountPool) MergeSetCookieHeaders(accountID string, headers []string, requestURL string, now time.Time) error { + account, err := p.Account(accountID) + if err != nil { + return err } - l.account.storageMu.Lock() - defer l.account.storageMu.Unlock() - state, err := LoadStorageState(l.account.StoragePath) + return p.mergeSetCookieHeaders(account, headers, requestURL, now) +} + +// mergeSetCookieHeaders 在账户存储锁内合并响应 Cookie、写回磁盘并同步到池内缓存 +func (p *AccountPool) mergeSetCookieHeaders(account *Account, headers []string, requestURL string, now time.Time) error { + account.storageMu.Lock() + defer account.storageMu.Unlock() + state, err := LoadStorageState(account.StoragePath) if err != nil { return err } if err := state.MergeSetCookieHeaders(headers, requestURL, now); err != nil { return err } - if err := WriteStorageState(l.account.StoragePath, state); err != nil { + if err := WriteStorageState(account.StoragePath, state); err != nil { return err } - l.pool.mu.Lock() - l.account.StorageState = state - l.pool.mu.Unlock() + p.mu.Lock() + account.StorageState = state + p.mu.Unlock() return nil } +// MergeSetCookieHeaders 将响应 Cookie 合并到账户最新持久状态 +func (l *AccountLease) MergeSetCookieHeaders(headers []string, requestURL string, now time.Time) error { + l.operation.Lock() + defer l.operation.Unlock() + if l.released { + return fmt.Errorf("账户租约已释放") + } + return l.pool.mergeSetCookieHeaders(l.account, headers, requestURL, now) +} + // Release 释放账户文件和进程内租约 func (l *AccountLease) Release() error { l.operation.Lock() @@ -2806,6 +2886,11 @@ func verificationRestriction(reason string) bool { return reason == verificationDenial } +// VerificationRequired 判断账户是否因上游要求验证而受限 +func (p *AccountPool) VerificationRequired(accountID string) bool { + return p.verificationRestricted(accountID) +} + // verificationRestricted 判断账户因上游要求验证而服务受限 func (p *AccountPool) verificationRestricted(accountID string) bool { p.mu.Lock() @@ -2928,6 +3013,7 @@ func (p *AccountPool) Status() []AccountStatus { status := AccountStatus{ ID: account.ID, Label: account.Config.Label, + Note: account.Config.Note, State: state, Enabled: account.Config.Enabled, Proxy: account.Config.Proxy, @@ -2947,9 +3033,11 @@ func (p *AccountPool) Status() []AccountStatus { TransitionSince: progress.since, CatalogError: catalogError, ActiveRequests: account.active, - CatalogSyncedAt: account.catalogSyncedAt, - HiddenDiscovered: account.hiddenDiscovered, - HiddenModels: len(account.hiddenModels), + CatalogSyncedAt: account.catalogSyncedAt, + HiddenDiscovered: account.hiddenDiscovered, + HiddenModels: len(account.hiddenModels), + VerificationRequired: state == AccountRestricted && verificationRestriction(account.runtime.Restricted), + DeviceBoundSession: account.StorageState.DeviceBoundSession(), } if !account.LastUsed.IsZero() { status.LastUsed = timePointer(account.LastUsed) diff --git a/internal/aistudio/assistant.go b/internal/aistudio/assistant.go index f0bbb129..15d47a25 100644 --- a/internal/aistudio/assistant.go +++ b/internal/aistudio/assistant.go @@ -79,10 +79,17 @@ const ( assistantHistoryRule = "The conversation before the first user message of this chat is transcribed at the end of %s between and : user turns between and , and your own earlier replies, including your function_calls blocks, between and . Attachments in it are numbered like [attachment 1] and are attached in the same order %sat the start of the first user message of this chat. Continue the conversation from the latest message and never write these tags yourself." // assistantInstructionLimit 是上游不截断的自定义指令字节数,超过时上游截到 24KB 并加截断标记 assistantInstructionLimit = 24000 - // assistantTurnTokenLimit 是最后一组留在 field 1 提交的本地 Token 数上限,超过时与之前的对话一起转录在自定义指令中 + // assistantTurnTokenLimit 是最后一组直接留在 field 1 提交的本地 Token 数上限,超过时续接原 trajectory 写成最新消息文件、查不到 trajectory 时与之前的对话一起转录 assistantTurnTokenLimit = 24576 // assistantLatestPrompt 是对话全部转录时提交的用户轮,%s 为转录所在的位置 assistantLatestPrompt = "Continue the conversation from the last turn of the conversation history at the end of %s." + // assistantMessageOpen 与 assistantMessageClose 包住写在最新消息文件中的超长对话轮 + assistantMessageOpen = "\n" + assistantMessageClose = "" + // assistantMessageRule 是写在最新消息文件开头的说明,与说明文件区分 + assistantMessageRule = "Latest user message (not an instructions file; keep all earlier system instructions, client functions and conversation history unchanged). The latest user message and tool results of this chat are transcribed below between and in blocks. Attachments in it are numbered like [attachment 1] and are attached right after this file in the same order. Continue the conversation from this latest message and never write these tags yourself." + // assistantMessagePrompt 是最新一组写在最新消息文件中提交时的用户轮正文 + assistantMessagePrompt = "Continue the conversation from the attached latest user message file (not an instructions file)." // assistantEmptyReplyPrompt 是模型一轮结束时没有正文与函数调用后在同一 trajectory 中追加的用户轮 assistantEmptyReplyPrompt = "Your last turn ended without any visible reply. Continue now and give your reply." // assistantCallFormat 是要求重写调用时附带的 function_calls 代码块格式与交回调用的说明 @@ -321,7 +328,7 @@ func assistantToolPrompt(request GenerateRequest, transcriptEnd int, start int, var transcript string var attachments []Part if transcriptEnd > 0 { - transcript, attachments = assistantTranscript(request.Contents[:transcriptEnd], turns) + transcript, attachments = assistantTranscript(request.Contents[:transcriptEnd], turns[:transcriptEnd], assistantHistoryOpen, assistantHistoryClose) } tools := "" if declarations != "" { @@ -358,12 +365,22 @@ func assistantToolPrompt(request GenerateRequest, transcriptEnd int, start int, latest = "the instructions file" } request.System = []string{instructions} - contents := make([]Content, 0, len(turns)-start+1) - for _, parts := range turns[start:] { - contents = append(contents, Content{Role: RoleUser, Parts: parts}) - } - if len(contents) == 0 { - contents = append(contents, Content{Role: RoleUser, Parts: []Part{{Text: fmt.Sprintf(assistantLatestPrompt, latest)}}}) + var contents []Content + if start < len(turns) && assistantPartsTooLong(request.Contents[start:]) { + message, messageAttachments := assistantTranscript(request.Contents[start:], turns[start:], assistantMessageOpen, assistantMessageClose) + parts := make([]Part, 0, 2+len(messageAttachments)) + parts = append(parts, Part{InlineData: &Blob{MIME: "text/plain", Data: []byte(assistantMessageRule + "\n\n" + message)}}) + parts = append(parts, messageAttachments...) + parts = append(parts, Part{Text: assistantMessagePrompt}) + contents = []Content{{Role: RoleUser, Parts: parts}} + } else { + contents = make([]Content, 0, len(turns)-start+1) + for _, parts := range turns[start:] { + contents = append(contents, Content{Role: RoleUser, Parts: parts}) + } + if len(contents) == 0 { + contents = append(contents, Content{Role: RoleUser, Parts: []Part{{Text: fmt.Sprintf(assistantLatestPrompt, latest)}}}) + } } if start == transcriptEnd && len(attachments) > 0 { contents[0].Parts = append(attachments, contents[0].Parts...) @@ -376,11 +393,11 @@ func assistantToolPrompt(request GenerateRequest, transcriptEnd int, start int, return request, file, nil } -// assistantTranscript 返回 contents 转录成的对话历史与其中的附件:各轮取 turns 中同一位置改写后的 Part,去掉思考与空 Part,附件写为编号,附件依次以编号文本 Part 与附件 Part 返回 -func assistantTranscript(contents []Content, turns [][]Part) (string, []Part) { +// assistantTranscript 返回 contents 按 open 与 close 包住转录成的文本与其中的附件:各轮取 turns 中同一位置改写后的 Part,去掉思考与空 Part,附件写为编号,附件依次以编号文本 Part 与附件 Part 返回 +func assistantTranscript(contents []Content, turns [][]Part, open string, close string) (string, []Part) { var transcript strings.Builder var attachments []Part - transcript.WriteString(assistantHistoryOpen) + transcript.WriteString(open) for index, content := range contents { tag := "user_turn" if content.Role == RoleAssistant { @@ -400,7 +417,7 @@ func assistantTranscript(contents []Content, turns [][]Part) (string, []Part) { } fmt.Fprintf(&transcript, assistantHistoryTurn, tag, strings.Join(texts, "\n"), tag) } - transcript.WriteString(assistantHistoryClose) + transcript.WriteString(close) return transcript.String(), attachments } @@ -416,21 +433,21 @@ type assistantTurn struct { context string } -// assistantLatest 表示最后一组也要转录在说明文件中:最后一组是模型轮,或本地 Token 数超过 assistantTurnTokenLimit -func assistantLatest(contents []Content, links []turnLink) bool { - count := len(links) - if count == 0 { - return false - } - tail := 0 - if count > 1 { - tail = links[count-2].end - } - var parts []Part - for _, content := range contents[tail:] { - parts = append(parts, content.Parts...) +// assistantModelTail 表示对话最后一组是模型轮 +func assistantModelTail(links []turnLink) bool { + return len(links) > 0 && links[len(links)-1].model +} + +// assistantPartsTooLong 表示 contents 中各轮的本地 Token 数之和超过 assistantTurnTokenLimit +func assistantPartsTooLong(contents []Content) bool { + var total int64 + for _, content := range contents { + total += localPartsTokens(content.Parts) + if total > assistantTurnTokenLimit { + return true + } } - return links[count-1].model || localPartsTokens(parts) > assistantTurnTokenLimit + return false } // planAssistantTurn 按续接的 trajectory 改写请求,返回本轮之后自定义指令中转录的开头分组数与说明文件摘要 @@ -442,15 +459,19 @@ func planAssistantTurn(request GenerateRequest, links []turnLink, trajectory *as return request, 0, "", err } groups := 0 + tail := 0 + if len(links) > 1 { + tail = links[len(links)-2].end + } switch { case trajectory != nil: groups = trajectory.HistoryGroups - case assistantLatest(request.Contents, links): + case assistantModelTail(links) || len(links) > 0 && assistantPartsTooLong(request.Contents[tail:]): groups = len(links) start = len(request.Contents) case len(links) > 1: groups = len(links) - 1 - start = links[groups-1].end + start = tail } transcribed := 0 if groups > 0 { @@ -489,7 +510,7 @@ func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease, } var trajectory *assistantTrajectory start := 0 - if applet != "" && !assistantLatest(request.Contents, links) { + if applet != "" { trajectory, start = lease.findAssistantTrajectory(apiKey, links) } prepared, groups, context, err := planAssistantTurn(request, links, trajectory, start) diff --git a/internal/aistudio/assistant_session.go b/internal/aistudio/assistant_session.go index 29ce0072..fa3cc211 100644 --- a/internal/aistudio/assistant_session.go +++ b/internal/aistudio/assistant_session.go @@ -36,13 +36,12 @@ func assistantTip(apiKey string, digest string) string { return hex.EncodeToString(sum[:]) } -// assistantTipLink 返回 links 最后一组之前最近的模型轮分组,没有时为 -1 +// assistantTipLink 返回非模型结尾对话最后一组之前的模型轮分组,最后一组是模型轮或之前没有模型轮时为 -1 func assistantTipLink(links []turnLink) int { - index := len(links) - 2 - if index >= 0 && !links[index].model { - index-- + if len(links) < 2 || links[len(links)-1].model { + return -1 } - return index + return len(links) - 2 } // matchAssistantTrajectory 返回应用中续接位置为 tip 的 trajectory diff --git a/internal/aistudio/auth.go b/internal/aistudio/auth.go index 2b10775d..58888e8c 100644 --- a/internal/aistudio/auth.go +++ b/internal/aistudio/auth.go @@ -124,6 +124,28 @@ func (s StorageState) AuthExtension() (AuthExtension, bool, error) { return extension, true, nil } +// HasBoundCookie 表示认证状态包含设备绑定的 __Secure-1PSIDRTS Cookie +func (s StorageState) HasBoundCookie() bool { + for _, cookie := range s.Cookies { + if cookie.Name == "__Secure-1PSIDRTS" { + return true + } + } + return false +} + +// DeviceBoundSession 表示会话带 __Secure-1PSIDRTS 且缺少本地 Chrome OAuth 续签材料,属于约 2 小时内失效的设备绑定副本 +func (s StorageState) DeviceBoundSession() bool { + if !s.HasBoundCookie() { + return false + } + extension, exists, err := s.AuthExtension() + if err == nil && exists && extension.OAuth != nil && strings.TrimSpace(extension.OAuth.RefreshToken) != "" { + return false + } + return true +} + // BoundCookieLifetime 按 Chromium MinimumBoundCookieLifetime 返回 DBSC 会话绑定 Cookie 中最早到期者的剩余时间,缺少或已到期时为 0 func (s StorageState) BoundCookieLifetime(session BoundSession, now time.Time) time.Duration { lifetime := time.Duration(1<<63 - 1) @@ -146,20 +168,27 @@ func (s StorageState) BoundCookieLifetime(session BoundSession, now time.Time) t // IsolatedLoginRequest 描述独立浏览器登录所需的稳定环境,View 不为空时登录画面显示在管理页登录窗口 type IsolatedLoginRequest struct { - Directory string - Proxy string - Locale string - Timezone string - View *camoufoxnative.LiveView + Directory string + Proxy string + Locale string + Timezone string + View *camoufoxnative.LiveView + OnLoggedIn func(context.Context, IsolatedLoginResult) error + CheckVerification func(context.Context, StorageState) (bool, error) + OnVerifyStep func(string) + VerifyPollInterval time.Duration } // IsolatedLoginResult 返回独立浏览器导出的认证状态 type IsolatedLoginResult struct { - StorageState StorageState - Email string - VerifiedAt time.Time - DriveError string - CloseError string + StorageState StorageState + Email string + VerifiedAt time.Time + DriveError string + CloseError string + Saved bool + VerificationPending bool + VerificationError string } // IsolatedLoginDriver 定义独立浏览器登录 @@ -167,6 +196,25 @@ type IsolatedLoginDriver interface { Login(context.Context, IsolatedLoginRequest) (IsolatedLoginResult, error) } +// AccountVerifyRequest 描述在独立浏览器中打开账户验证页所需的环境与核对回调 +type AccountVerifyRequest struct { + Directory string + StorageState StorageState + AuthUser int + Proxy string + Locale string + Timezone string + View *camoufoxnative.LiveView + CheckVerification func(context.Context, StorageState) (bool, error) + OnVerifyStep func(string) + PollInterval time.Duration +} + +// AccountVerifyDriver 定义在独立浏览器中打开账户验证页并自动再核对的能力 +type AccountVerifyDriver interface { + Verify(context.Context, AccountVerifyRequest) (bool, error) +} + // LoadStorageState 读取并校验 Playwright storage state func LoadStorageState(filePath string) (StorageState, error) { data, err := os.ReadFile(filePath) diff --git a/internal/aistudio/benefit.go b/internal/aistudio/benefit.go index 13f8ec26..ba286222 100644 --- a/internal/aistudio/benefit.go +++ b/internal/aistudio/benefit.go @@ -68,6 +68,11 @@ func (c *Client) setBenefitTier(accountID string, tier BenefitTier) { c.tierMu.Unlock() } +// DecodeBenefitTier 解码 GetAiStudioBenefitTier 响应正文为账户权益等级 +func DecodeBenefitTier(raw []byte) (BenefitTier, error) { + return decodeBenefitTier(raw) +} + func decodeBenefitTier(raw []byte) (BenefitTier, error) { value, err := decodeJSONValue(raw) if err != nil { diff --git a/internal/aistudio/channel.go b/internal/aistudio/channel.go index 15c564e9..e565015d 100644 --- a/internal/aistudio/channel.go +++ b/internal/aistudio/channel.go @@ -373,13 +373,6 @@ func (p *AccountPool) assistantBusyLocked(account *Account, selection AccountSel return account.assistantBusy && p.assistantSelectionLocked(selection) } -// InteractionAgentModel 判断模型是否为经 CreateInteraction 后台任务生成的 agent,如 Deep Research 与 Antigravity -func (p *AccountPool) InteractionAgentModel(modelID string) bool { - p.mu.Lock() - defer p.mu.Unlock() - return p.modelCapabilityLocked(modelID, "interaction_task") -} - // modelCapabilityLocked 返回目录中首个同 ID 模型的能力标记 func (p *AccountPool) modelCapabilityLocked(modelID string, capability string) bool { modelID = strings.TrimPrefix(strings.TrimSpace(modelID), "models/") @@ -409,6 +402,11 @@ func (p *AccountPool) buildSupportsModelLocked(account *Account, modelID string, if !found { return false } + for _, model := range account.Models { + if modelMatchesID(model, modelID) { + return !buildExcludedPlaygroundModel(model) && (anyTier || modelAllowedByTier(model, account.BenefitTier)) + } + } for _, candidate := range p.accounts { for _, model := range candidate.Models { if modelMatchesID(model, modelID) { diff --git a/internal/aistudio/chinese_rewrite.go b/internal/aistudio/chinese_rewrite.go new file mode 100644 index 00000000..5356ea26 --- /dev/null +++ b/internal/aistudio/chinese_rewrite.go @@ -0,0 +1,129 @@ +package aistudio + +import ( + _ "embed" + "slices" + "strings" + "sync" + + "github.com/go-ego/gocc" +) + +const ( + userMessageRewriteOff = "off" + userMessageRewriteTraditional = "traditional" + userMessageRewriteMartian = "martian" +) + +// userMessageRewriteReplyInstruction 是用户消息改写开启时追加到系统指令的回复语言要求,繁体中文与火星文模式共用 +const userMessageRewriteReplyInstruction = "User messages may be converted to Traditional Chinese or Martian Chinese (Huoxingwen) for transmission. Understand their intended meaning and always write your reply in Simplified Chinese, ignoring the converted characters in user messages, unless the user explicitly asks you to reply in another language or script." + +//go:embed martian_table.tsv +var martianTableTSV string + +// openCCS2T 懒初始化用于简体转繁体的 OpenCC s2t 转换器 +var openCCS2T = sync.OnceValues(func() (*gocc.Converter, error) { + return gocc.New("s2t") +}) + +// martianTable 懒初始化由自制火星文码表构建的只读字符映射,每行记录同一原字的简繁变体及其唯一替换字 +var martianTable = sync.OnceValue(func() map[rune]rune { + lines := strings.Split(strings.TrimRight(martianTableTSV, "\r\n"), "\n") + table := make(map[rune]rune, len(lines)*2) + for _, line := range lines { + line = strings.TrimRight(line, "\r") + sources, targetText, ok := strings.Cut(line, "\t") + if !ok || sources == "" || targetText == "" { + continue + } + target := []rune(targetText)[0] + for _, r := range sources { + table[r] = target + } + } + return table +}) + +// convertMartian 先经 OpenCC s2t 消歧,再按火星文码表逐字替换,表外生僻字保留繁体且不改动 ASCII 与标点 +func convertMartian(text string, converter *gocc.Converter) string { + converted := converter.Convert(text) + table := martianTable() + var builder strings.Builder + for i, r := range converted { + mapped, ok := table[r] + if !ok || mapped == r { + if builder.Len() > 0 { + builder.WriteRune(r) + } + continue + } + if builder.Len() == 0 { + builder.Grow(len(converted)) + builder.WriteString(converted[:i]) + } + builder.WriteRune(mapped) + } + if builder.Len() > 0 { + return builder.String() + } + return converted +} + +// chineseRewriteEligible 判断本次生成是否启用用户消息文字改写 +func chineseRewriteEligible(request GenerateRequest, entry modelEntry) bool { + switch request.UserMessageRewrite { + case userMessageRewriteTraditional, userMessageRewriteMartian: + return !nonTextGeneration(request, entry) + default: + return false + } +} + +// applyChineseRewrite 按配置模式改写用户消息中的中文并追加简体中文回复系统指令,保留模型历史回答、非文本块与调用方入参 +func applyChineseRewrite(request GenerateRequest) (GenerateRequest, error) { + converter, err := openCCS2T() + if err != nil { + return request, err + } + convert := converter.Convert + if request.UserMessageRewrite == userMessageRewriteMartian { + convert = func(text string) string { + return convertMartian(text, converter) + } + } + var contents []Content + for index, content := range request.Contents { + if content.Role != RoleUser { + continue + } + var parts []Part + for partIndex, part := range content.Parts { + if part.Text == "" || part.Thought { + continue + } + converted := convert(part.Text) + if converted == part.Text { + continue + } + if parts == nil { + parts = slices.Clone(content.Parts) + } + parts[partIndex].Text = converted + } + if parts != nil { + if contents == nil { + contents = slices.Clone(request.Contents) + } + contents[index].Parts = parts + } + } + if contents != nil { + request.Contents = contents + } + instruction := userMessageRewriteReplyInstruction + if len(request.System) > 0 { + instruction = "\n" + instruction + } + request.System = appendSystem(request.System, instruction) + return request, nil +} diff --git a/internal/aistudio/client.go b/internal/aistudio/client.go index 2e56447c..1245e1f8 100644 --- a/internal/aistudio/client.go +++ b/internal/aistudio/client.go @@ -227,12 +227,27 @@ func newRPCRequest(method string, accountID string, requestID string, body []byt } } +// ResponseReadError 表示收到上游非 200 响应头后读取错误响应体失败 +type ResponseReadError struct { + Err error +} + +// Error 返回错误文本 +func (e *ResponseReadError) Error() string { + return e.Err.Error() +} + +// Unwrap 返回底层读取错误 +func (e *ResponseReadError) Unwrap() error { + return e.Err +} + func validateRPCResponse(method string, response *RPCResponse) (*RPCResponse, error) { if response.StatusCode != http.StatusOK { defer response.Body.Close() raw, readErr := io.ReadAll(response.Body) if readErr != nil { - return nil, fmt.Errorf("读取 AI Studio %s 错误响应: %w", method, readErr) + return nil, &ResponseReadError{Err: fmt.Errorf("读取 AI Studio %s 错误响应: %w", method, readErr)} } rpcError := DecodeRPCError(method, response.StatusCode, raw) if rpcError.RetryDelay <= 0 { diff --git a/internal/aistudio/cookie_import.go b/internal/aistudio/cookie_import.go index 95ae1187..e3b59157 100644 --- a/internal/aistudio/cookie_import.go +++ b/internal/aistudio/cookie_import.go @@ -173,6 +173,9 @@ func parseCookieHeader(header string) ([]StateCookie, error) { } cookies := make([]StateCookie, 0) for _, item := range strings.Split(header, ";") { + if strings.TrimSpace(item) == "" { + continue + } name, value, found := strings.Cut(strings.TrimSpace(item), "=") name = strings.TrimSpace(name) if !found || name == "" { diff --git a/internal/aistudio/generate.go b/internal/aistudio/generate.go index 37172248..cf5e61ad 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 entry.defaults.InteractionStream || entry.defaults.InteractionTask { + if stream, task := interactionRoute(entry.model, entry.defaults, ChannelPlayground); stream || task { return nil } if _, err := encodeGenerationConfig(applyModelMediaDefaults(request.Config, entry.model), entry.defaults); err != nil { @@ -793,9 +793,23 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan if err != nil { return nil, err } + channel := ChannelPlayground + if build { + channel = ChannelBuild + } + interaction, task := interactionRoute(entry.model, entry.defaults, channel) apiKey, _ := ctx.Value(apiKeyContextKey{}).(string) assistant := entry.model.Capabilities["assistant_route"] - restoring := request.restoreModelTurns && !build && !assistant && !entry.defaults.InteractionStream && !entry.defaults.InteractionTask + if chineseRewriteEligible(request, entry) { + request, err = applyChineseRewrite(request) + if err != nil { + return nil, err + } + } + 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) @@ -814,8 +828,6 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } } - interaction := entry.defaults.InteractionStream && !build - task := entry.defaults.InteractionTask && !build if interaction { request.Tools = Tools{} } @@ -823,6 +835,14 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan if err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } + if !interaction && !task && replyToolEligible(request, entry, build, assistant) { + request = applyReplyTool(request) + if contract == nil { + contract = &toolContract{} + } + contract.replyTool = true + contract.stopSequences = request.Config.StopSequences + } if err := validateTranscriptionConfig(request.Config.TranscriptionConfig, entry.model); err != nil { return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err) } @@ -972,6 +992,11 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan err := decodeStream(observeStreamActivity(ctx, response.Body), roundEmit()) // 写代码助手的调用块错误已在 trajectory 内重答,这里只重新生成发送与读取失败 for regenerated := 0; regenerated < regenerations && regenerable(ctx, err, finish, committed) && (err != nil || !assistant); regenerated++ { + if err != nil { + reportRegeneration(ctx, regenerated+1, err.Error()) + } else { + reportRegeneration(ctx, regenerated+1, fmt.Sprintf("结束原因 %s", finish.FinishReason)) + } stopClose() _ = response.Body.Close() usage, finish, held, turn, roundUsage, output = nil, nil, nil, modelTurn{}, nil, Output{} @@ -1070,7 +1095,7 @@ func (c *Client) Generate(ctx context.Context, request GenerateRequest) (<-chan finish.TrailingError = trailing _ = send(*finish) } - if restoring && trailing == nil { + if restoring && trailing == nil && !(contract != nil && contract.replyTool && calledReplyTool(output)) { c.turns.store(apiKey, request.turnChain.tip, turn) } }() @@ -1326,7 +1351,6 @@ func (c *Client) decodePlaygroundRounds(ctx context.Context, request GenerateReq } request.continuationRound++ request.continuationToken = decoder.continuation - reportContinuationRound(ctx) reportUpstreamMode(ctx, "GenerateContent", "stream", request.continuationRound, "") body, proofAt, err := EncodeGenerateContentRequest(request, defaults, runtime) if err != nil { diff --git a/internal/aistudio/login_native.go b/internal/aistudio/login_native.go index 845ff6e3..e51f87fb 100644 --- a/internal/aistudio/login_native.go +++ b/internal/aistudio/login_native.go @@ -19,6 +19,7 @@ type NativeLoginDriver struct { } var _ IsolatedLoginDriver = (*NativeLoginDriver)(nil) +var _ AccountVerifyDriver = (*NativeLoginDriver)(nil) // NewNativeLoginDriver 创建纯 Go Camoufox 登录驱动 func NewNativeLoginDriver(camoufoxPath string) (*NativeLoginDriver, error) { @@ -29,29 +30,97 @@ func NewNativeLoginDriver(camoufoxPath string) (*NativeLoginDriver, error) { return &NativeLoginDriver{camoufox: absolute}, nil } +// decodeIsolatedLoginState 解析隔离登录导出的 storage state 并标记 camoufox 来源 +func decodeIsolatedLoginState(raw []byte, email string) (StorageState, error) { + var state StorageState + if err := json.Unmarshal(raw, &state); err != nil { + return StorageState{}, fmt.Errorf("解析隔离登录状态: %w", err) + } + state.SetAuthExtension(AuthExtension{ + Source: AuthSource{Browser: "camoufox", Email: email}, + }) + return state, nil +} + // Login 启动隔离 Camoufox 供用户登录并导出认证状态 func (driver *NativeLoginDriver) Login(ctx context.Context, request IsolatedLoginRequest) (IsolatedLoginResult, error) { - result, err := camoufoxnative.Login(ctx, camoufoxnative.LoginOptions{ - ExecutablePath: driver.camoufox, - Directory: request.Directory, - Locale: request.Locale, - Timezone: request.Timezone, - Proxy: request.Proxy, - Timeout: loginTimeout, - View: request.View, - }) + options := camoufoxnative.LoginOptions{ + ExecutablePath: driver.camoufox, + Directory: request.Directory, + Locale: request.Locale, + Timezone: request.Timezone, + Proxy: request.Proxy, + Timeout: loginTimeout, + View: request.View, + OnVerifyStep: request.OnVerifyStep, + VerifyPollInterval: request.VerifyPollInterval, + } + if request.OnLoggedIn != nil { + options.OnLoggedIn = func(callbackCtx context.Context, raw camoufoxnative.LoginResult) error { + state, err := decodeIsolatedLoginState(raw.StorageStateJSON, raw.Email) + if err != nil { + return err + } + return request.OnLoggedIn(callbackCtx, IsolatedLoginResult{ + StorageState: state, Email: raw.Email, VerifiedAt: raw.VerifiedAt, DriveError: raw.DriveError, + }) + } + } + if request.CheckVerification != nil { + options.CheckVerification = func(callbackCtx context.Context, raw []byte) (bool, error) { + var state StorageState + if len(raw) > 0 { + if err := json.Unmarshal(raw, &state); err != nil { + return true, fmt.Errorf("解析验证状态: %w", err) + } + } + return request.CheckVerification(callbackCtx, state) + } + } + result, err := camoufoxnative.Login(ctx, options) if err != nil { return IsolatedLoginResult{}, err } - var state StorageState - if err := json.Unmarshal(result.StorageStateJSON, &state); err != nil { - return IsolatedLoginResult{}, fmt.Errorf("解析隔离登录状态: %w", err) + state, err := decodeIsolatedLoginState(result.StorageStateJSON, result.Email) + if err != nil { + return IsolatedLoginResult{}, err } - state.SetAuthExtension(AuthExtension{ - Source: AuthSource{Browser: "camoufox", Email: result.Email}, - }) return IsolatedLoginResult{ StorageState: state, Email: result.Email, VerifiedAt: result.VerifiedAt, DriveError: result.DriveError, CloseError: result.CloseError, + Saved: result.Saved, VerificationPending: result.VerificationPending, VerificationError: result.VerificationError, }, nil } + +// Verify 启动隔离 Camoufox 载入已有账户的认证状态并停在官网验证页,自动再核对直到通过或窗口关闭 +func (driver *NativeLoginDriver) Verify(ctx context.Context, request AccountVerifyRequest) (bool, error) { + encoded, err := json.Marshal(request.StorageState) + if err != nil { + return true, fmt.Errorf("编码账户认证状态: %w", err) + } + options := camoufoxnative.VerifyOptions{ + ExecutablePath: driver.camoufox, + Directory: request.Directory, + StorageStateJSON: encoded, + AuthUser: request.AuthUser, + Locale: request.Locale, + Timezone: request.Timezone, + Proxy: request.Proxy, + Timeout: loginTimeout, + View: request.View, + OnVerifyStep: request.OnVerifyStep, + PollInterval: request.PollInterval, + } + if request.CheckVerification != nil { + options.CheckVerification = func(callbackCtx context.Context, raw []byte) (bool, error) { + var state StorageState + if len(raw) > 0 { + if err := json.Unmarshal(raw, &state); err != nil { + return true, fmt.Errorf("解析验证状态: %w", err) + } + } + return request.CheckVerification(callbackCtx, state) + } + } + return camoufoxnative.Verify(ctx, options) +} diff --git a/internal/aistudio/martian_table.tsv b/internal/aistudio/martian_table.tsv new file mode 100644 index 00000000..d2b8cd19 --- /dev/null +++ b/internal/aistudio/martian_table.tsv @@ -0,0 +1,7150 @@ +一 壹 +丁 仃 +七 柒 +万萬 腕 +丈 仗 +三 叁 +上 尚 +下 夏 +丌 磯 +不 簿 +与與 屿 +丐 鈣 +丑 瞅 +专專 砖 +且 惬 +丕 邳 +世 轼 +丘 邱 +丙 禀 +业業 烨 +丛叢 淙 +东東 鸫 +丝絲 鸶 +丞 懲 +丢丟 銩 +两兩 魉 +严嚴 沿 +丧喪 桑 +丨 袞 +个個 箇 +丫 鸭 +丬 蹣 +中 忠 +丰豐 封 +串 钏 +临臨 邻 +丶 矚 +丸 纨 +丹 耽 +为為 蔚 +主 拄 +丽麗 俪 +举舉 矩 +丿 苤 +乃 艿 +久 玖 +乇 托 +么 庅 +义義 忆 +之 芝 +乌烏 呜 +乍 蚱 +乎 呼 +乏 筏 +乐樂 勒 +乒 娉 +乓 滂 +乔喬 侨 +乖 枴 +乘 城 +乙 矣 +乜 灭 +九 灸 +乞 企 +也 冶 +习習 席 +乡鄉 厢 +书書 殳 +乩 羈 +买買 蕒 +乱亂 峦 +乳 汝 +乾 柑 +了 瞭 +予 禹 +争爭 睁 +事 柿 +二 贰 +亍 触 +于於 盂 +亏虧 盔 +云 芸 +互 沪 +亓 臍 +五 伍 +井 憬 +亘亙 茛 +亚亞 娅 +些 歇 +亟 殛 +亠 偷 +亡 妄 +亢 伉 +交 浇 +亥 骸 +亦 屹 +产產 铲 +亨 哼 +亩畝 拇 +享 飨 +京 鲸 +亭 廷 +亮 谅 +亲親 钦 +亳 脖 +亵褻 谢 +人 仁 +亻 人 +亿億 艺 +什 神 +仁 壬 +仂 鳓 +仃 钉 +仄 昃 +仅僅 瑾 +仆僕 葡 +仇 绸 +仉 掌 +今 襟 +介 芥 +仍 礽 +从從 丛 +仑侖 纶 +仓倉 舱 +仔 籽 +仕 逝 +他 牠 +仗 账 +付 咐 +仙 鲜 +仝 僮 +仞 刃 +仟 扦 +仡 割 +代 黛 +令 玲 +以 倚 +仨 洒 +仪儀 宜 +仫 鉬 +们們 闷 +仰 鞅 +仲 肿 +仳 庀 +仵 忤 +件 健 +价價 稼 +任 韧 +份 忿 +仿 纺 +企 绮 +伉 闶 +伊 揖 +伋 芨 +伍 舞 +伎 績 +伏 茯 +伐 阀 +休 羞 +伕 跗 +众眾 仲 +优優 悠 +伙 火 +会會 烩 +伛傴 嶼 +伞傘 馓 +伟偉 纬 +传傳 椽 +伢 枒 +伤傷 殇 +伥倀 阊 +伦倫 仑 +伧傖 仓 +伪偽 伟 +伫佇 贮 +伯 舶 +估 沽 +伲 暱 +伴 绊 +伶 羚 +伸 绅 +伺 饲 +似 嗣 +伽 笳 +佃 店 +但 诞 +佈 瓿 +位 卫 +低 堤 +住 柱 +佐 左 +佑 诱 +体體 躰 +佔 棧 +何 荷 +佗 駝 +佘 蛇 +余 愉 +佚 軼 +佛 仏 +作 佐 +佝 鉤 +佞 宁 +佟 砼 +你 祢 +佣傭 庸 +佤 娃 +佥僉 铅 +佧 卡 +佩 霈 +佬 姥 +佯 洋 +佰 百 +佳 珈 +佴 貳 +併 並 +佶 姞 +佺 顴 +佻 祧 +佼 鉸 +佾 怿 +使 驶 +侃 檻 +侄姪 职 +侈 耻 +侉 胯 +例 励 +侍 士 +侏 硃 +侑 又 +侔 蛑 +侗 胴 +供 恭 +依 伊 +侠俠 峡 +侣侶 吕 +侥僥 脚 +侦偵 帧 +侧側 恻 +侨僑 憔 +侩儈 狯 +侪儕 柴 +侬儂 噥 +侮 五 +侯 猴 +侵 亲 +侷 橘 +便 辫 +係 郤 +促 簇 +俄 蛾 +俅 毬 +俊 峻 +俎 組 +俏 峭 +俐 莉 +俑 永 +俗 苏 +俘 蜉 +俚 李 +俜 呯 +保 堡 +俞 瑜 +俟 涘 +信 伩 +俣俁 娛 +俦儔 躊 +俨儼 琰 +俩倆 唡 +俪儷 酈 +俭儉 睑 +修 馐 +俯 抚 +俱 具 +俳 簰 +俸 奉 +俺 埯 +俾 彼 +倌 冠 +倍 焙 +倏 输 +倒 祷 +倔 决 +倖 婞 +倘 淌 +候 厚 +倚 乙 +倜 替 +借 诫 +倡 昌 +倣 昉 +倥 控 +倦 眷 +倨 聚 +倩 茜 +倪 霓 +倬 繳 +倭 挝 +倮 蠃 +债債 寨 +值 殖 +倾傾 氢 +偃 郾 +假 贾 +偈 继 +偌 婼 +偎 微 +偏 翩 +偕 諧 +做 柞 +停 蜓 +健 键 +偬傯 縱 +偭 喕 +偯 釔 +偶 藕 +偷 偸 +偺 喒 +偻僂 蝼 +偾僨 奮 +偿償 嫦 +傀 魁 +傅 缚 +傈 慄 +傍 磅 +傚 校 +傢 镓 +傣 歹 +傥儻 帑 +傧儐 濱 +储儲 杵 +傩儺 诺 +催 摧 +傲 奥 +傺 熾 +傻 纱 +僇 鷺 +僎 馔 +像 橡 +僖 锡 +僚 撩 +僦 鷲 +僧 鬙 +僩 腺 +僬 鷦 +僭 鉴 +僮 曈 +僳 宿 +僵 疆 +僻 譬 +儅 裆 +儆 景 +儇 諼 +儋 担 +儒 孺 +儘 饉 +儡 诔 +儳 讒 +儸 籮 +儿兒 鸸 +兀 靰 +允 陨 +元 园 +兄 汹 +充 忡 +兆 召 +兇 忷 +先 仙 +光 咣 +克 恪 +免 勉 +兑兌 碓 +兔 菟 +兕 俟 +兖兗 堰 +党黨 挡 +兜 篼 +兢 精 +入 褥 +全 痊 +八 叭 +公 肱 +六 遛 +兮 熙 +兰蘭 栏 +共 拱 +关關 倌 +兴興 惺 +兵 氷 +其 琪 +具 惧 +典 碘 +兹茲 滋 +养養 氧 +兼 坚 +兽獸 寿 +冀 驥 +冁囅 蒇 +冂 扃 +内內 馁 +冈岡 缸 +冉 苒 +册冊 测 +再 宰 +冑 绉 +冒 茂 +冕 娩 +冖 謐 +冗 茸 +写寫 冩 +军軍 钧 +农農 侬 +冠 观 +冢 塚 +冤 渊 +冥 螟 +冩 撷 +冫 冰 +冬 咚 +冯馮 逢 +冰 槟 +冱 滬 +冲 充 +决決 诀 +况況 矿 +冶 野 +冷 棱 +冻凍 栋 +冼 跣 +冽 列 +净淨 靖 +凄悽 萋 +准 諄 +凇 淞 +凉涼 粮 +凋 碉 +凌 陵 +减減 碱 +凑湊 腠 +凛凜 廪 +凝 咛 +几幾 脊 +凡 矾 +凤鳳 俸 +凫鳧 氟 +凭憑 坪 +凯凱 铠 +凰 煌 +凳 瞪 +凵 莰 +凶 匈 +凸 突 +凹 熬 +出 橱 +击擊 基 +凼 荡 +函 含 +凿鑿 遭 +刀 叨 +刁 叼 +刂 忉 +刃 纫 +分 吩 +切 怯 +刈 乂 +刊 堪 +刍芻 雛 +刎 脗 +刑 形 +划 桦 +刖 躍 +列 裂 +刘劉 琉 +则則 泽 +刚剛 冈 +创創 怆 +初 锄 +删刪 珊 +判 畔 +刨 狍 +利 俐 +别別 蹩 +刭剄 颈 +刮 呱 +到 悼 +刳 绔 +制 帙 +刷 唰 +券 劝 +刹剎 裟 +刺 伺 +刻 溘 +刽劊 檜 +刿劌 跪 +剀剴 愷 +剁 跺 +剂劑 济 +剃 惕 +削 销 +剋 缂 +剌 旯 +前 钳 +剐剮 褂 +剑劍 箭 +剔 梯 +剖 掊 +剜 琬 +剞 唧 +剡 掞 +剥剝 钵 +剧劇 遽 +剩 嵊 +剪 拣 +副 富 +割 搁 +剷 鏟 +剽 漂 +剿 勦 +劁 譙 +劂 橛 +劃 樺 +劈 霹 +劐 镬 +劓 挹 +力 荔 +劝勸 颧 +办辦 伴 +功 攻 +加 枷 +务務 雾 +劢勱 邁 +劣 烈 +动動 硐 +助 驻 +努 弩 +劫 截 +劬 璩 +劭 绍 +励勵 厉 +劲勁 浸 +劳勞 唠 +劻 誆 +劾 核 +势勢 世 +勃 渤 +勇 涌 +勉 冕 +勋 熏 +勐 艋 +勒 叻 +勖 溆 +勗 昫 +勘 刊 +勛 埙 +募 慕 +勣 迹 +勤 芹 +勦 攪 +勰 脅 +勳 燻 +勹 龅 +勺 芍 +勾 篝 +勿 误 +匀勻 纭 +包 胞 +匆 囱 +匈 胸 +匍 仆 +匏 皰 +匐 幅 +匕 笔 +化 画 +北 碑 +匙 池 +匚 倣 +匝 紮 +匠 犟 +匡 筐 +匣 遐 +匦匭 轨 +匪 斐 +匮匱 篑 +匹 痞 +区區 躯 +医醫 漪 +匾 贬 +匿 逆 +十 拾 +千 仟 +卅 颯 +升 甥 +午 武 +卉 惠 +半 拌 +华華 骅 +协協 胁 +卑 陂 +卒 足 +卓 酌 +单單 郸 +卖賣 迈 +南 楠 +博 搏 +卜 捕 +卞 弁 +卟 鳪 +占 栈 +卡 咔 +卢盧 芦 +卣 銪 +卤滷 鲁 +卦 罣 +卧臥 握 +卩 孑 +卫衛 慰 +卮 祗 +卯 铆 +印 荫 +危 巍 +即 集 +却卻 鹊 +卵 挛 +卷 绢 +卸 械 +卹 洫 +卺巹 紧 +卿 青 +厂廠 氅 +厄 扼 +厅廳 汀 +历 沥 +厉厲 砺 +压壓 押 +厌厭 燕 +厍厙 社 +厕廁 侧 +厘釐 梨 +厚 侯 +厝 错 +原 缘 +厢廂 相 +厣厴 魇 +厥 蹶 +厦廈 霎 +厨廚 雏 +厩廄 救 +厮廝 思 +厶 蛳 +去 祛 +县縣 献 +叁 弎 +参參 飡 +又 佑 +叉 杈 +及 极 +友 黝 +双雙 霜 +反 返 +发 発 +叔 疏 +取 娶 +受 授 +变變 変 +叙敘 绪 +叛 袢 +叟 擞 +叠疊 迭 +口 扣 +古 诂 +句 据 +另 呤 +叨 刀 +叩 寇 +只 旨 +叫 轿 +召 诏 +叭 扒 +叮 玎 +可 渴 +台 苔 +叱 饬 +史 豕 +右 幼 +叵 笸 +叶葉 曳 +号號 浩 +司 撕 +叹嘆 炭 +叻 乐 +叼 貂 +叽嘰 讥 +吁籲 喻 +吃 嗤 +各 鉻 +吆 幺 +合 禾 +吉 及 +吊 钓 +吋 存 +同 桐 +名 铭 +后 鲎 +吏 利 +吐 土 +向 巷 +吒咤 詐 +吓嚇 丅 +吕呂 铝 +吖 阿 +吗嗎 骂 +君 均 +吝 赁 +吞 暾 +吟 寅 +吠 肺 +吡 妣 +吣 撳 +否 缶 +吧 芭 +吨噸 墩 +吩 汾 +含 涵 +听聽 厅 +吭 坑 +吮 楯 +启啟 乞 +吱 知 +吲 蔭 +吴吳 梧 +吵 炒 +吸 溪 +吹 炊 +吻 刎 +吼 後 +吾 毋 +呀 丫 +呃 軛 +呆 岱 +呈 程 +告 诰 +呋 伕 +呎 齿 +呐吶 捺 +呒嘸 撫 +呓囈 肄 +呔 逮 +呕嘔 耦 +呖嚦 靂 +呗唄 狽 +员員 圆 +呙咼 锅 +呛嗆 锵 +呜嗚 邬 +呢 讷 +呤 令 +呦 优 +周 舟 +呱 瓜 +呲 疵 +味 谓 +呵 何 +呶 蟯 +呷 狎 +呸 胚 +呻 娠 +呼 忽 +命 鸣 +咀 沮 +咂 臢 +咄 掇 +咆 刨 +咋 咂 +和 啝 +咎 舅 +咏詠 泳 +咐 附 +咒 宙 +咔 佧 +咕 辜 +咖 喀 +咙嚨 笼 +咚 冻 +咛嚀 泞 +咝 司 +咣 胱 +咦 痍 +咧 洌 +咨 资 +咩 乜 +咪 眯 +咫 枳 +咬 窈 +咭 乩 +咯 哥 +咱 簪 +咲 效 +咳 壳 +咴 麾 +咸鹹 贤 +咻 修 +咽 淹 +咿 噫 +哀 埃 +品 榀 +哂 审 +哄 烘 +哆 咄 +哇 蛙 +哈 鉿 +哉 载 +哌 派 +响響 饷 +哎 唉 +哏 艮 +哐 匡 +哑啞 雅 +哒噠 褡 +哓嘵 枭 +哔嗶 筚 +哕噦 约 +哗譁 铧 +哙噲 块 +哚 躲 +哜嚌 寄 +哝噥 农 +哞 牟 +哟喲 唷 +哥 歌 +哦 噢 +哧 笞 +哨 劭 +哩 理 +哪 娜 +哭 枯 +哮 肖 +哲 辙 +哳 扎 +哺 补 +哼 亨 +哽 耿 +哿 舸 +唁 彦 +唆 娑 +唇脣 淳 +唉 挨 +唏 烯 +唐 塘 +唑 侳 +唔 鼯 +唛嘜 劢 +唠嘮 崂 +唢嗩 锁 +唣 譟 +唤喚 浣 +唧 畸 +唪 讽 +唬 琥 +售 瘦 +唯 惟 +唰 耍 +唱 倡 +唳 戾 +唷 哟 +唸 埝 +唼 嗄 +唾 拓 +唿 乎 +啁 周 +啃 垦 +啄 卓 +商 墒 +啉 临 +啊 吖 +啐 翠 +啕 逃 +啖 蛋 +啗 但 +啜 辍 +啡 霏 +啣 閑 +啤 脾 +啥 砂 +啦 腊 +啧嘖 仄 +啪 趴 +啬嗇 穑 +啭囀 顓 +啮齧 镊 +啰囉 锣 +啵 播 +啶 掟 +啷 朗 +啸嘯 哮 +啻 赤 +啼 醍 +啾 阄 +喀 咖 +喁 顒 +喂 魏 +喃 赧 +善 膳 +喇 辣 +喈 階 +喉 篌 +喊 罕 +喋 叠 +喏 懦 +喑 愔 +喔 倭 +喘 舛 +喙 绘 +喜 禧 +喝 呵 +喟 聩 +喧 暄 +喫 絺 +喱 籬 +喳 渣 +喵 秒 +喷噴 瓫 +喹 窺 +喻 裕 +喽嘍 蒌 +喾嚳 库 +嗄 歃 +嗅 袖 +嗉 愫 +嗌 缢 +嗍 嗦 +嗑 客 +嗒 哒 +嗓 搡 +嗔 抻 +嗖 馊 +嗜 势 +嗝 镉 +嗟 疖 +嗡 蓊 +嗣 寺 +嗤 魑 +嗥 蚝 +嗦 蓑 +嗨 海 +嗪 懃 +嗫囁 躡 +嗬 喝 +嗯 恩 +嗳噯 曖 +嗵 蓪 +嗷 鳌 +嗽 叟 +嗾 搜 +嘀 低 +嘁 慼 +嘈 槽 +嘉 迦 +嘌 票 +嘎 旮 +嘏 毂 +嘐 蕭 +嘘噓 戌 +嘛 麻 +嘞 累 +嘟 独 +嘣 甭 +嘤嚶 鹰 +嘧 汨 +嘩 猾 +嘬 坐 +嘭 怦 +嘱囑 瞩 +嘲 晁 +嘴 檇 +嘶 厮 +嘹 遼 +嘻 嬉 +嘿 黑 +噌 蹭 +噍 醮 +噎 椰 +噔 灯 +噗 铺 +噘 撅 +噙 勤 +噜嚕 櫓 +噢 喔 +噤 尽 +器 契 +噩 鱷 +噪 躁 +噫 癔 +噬 氏 +噱 穴 +噶 嘎 +噹 筜 +噻 賽 +噼 丕 +嚅 燸 +嚆 郝 +嚎 毫 +嚏 剃 +嚐 萇 +嚓 叉 +嚣囂 萧 +嚥 赝 +嚮 曏 +嚯 货 +嚷 攘 +嚼 焦 +囊 馕 +囌 甦 +囔 囊 +囗 嵬 +囚 泅 +四 肆 +囝 儉 +回 茴 +囟 衅 +因 茵 +囡 难 +团團 抟 +囤 屯 +囫 壶 +园園 袁 +困 捆 +囱囪 葱 +围圍 韦 +囵圇 崙 +囹 泠 +固 锢 +国國 帼 +图圖 徒 +囿 宥 +圃 蹼 +圄 齬 +圆圓 援 +圈 蜷 +圉 窳 +圊 清 +圜 嬛 +土 涂 +圣聖 晟 +在 栽 +圩 韋 +圪 仡 +圬 屋 +圭 閨 +圮 疋 +圯 頤 +地 蒂 +圳 镇 +圹壙 况 +场場 昶 +圻 颀 +圾 肌 +址 趾 +坂 板 +均 菌 +坊 枋 +坌 锛 +坍 攤 +坎 砍 +坏壞 淮 +坐 座 +坑 硁 +块塊 筷 +坚堅 煎 +坛壇 檀 +坜壢 呖 +坝壩 灞 +坞塢 物 +坟墳 焚 +坠墜 缀 +坡 颇 +坤 昆 +坦 袒 +坨 佗 +坩 疳 +坪 评 +坫 鈿 +坭 鈮 +坯 披 +坳 拗 +坶 鉧 +坷 可 +坻 迟 +坼 蚸 +垂 锤 +垃 拉 +垄壟 拢 +垅 壟 +垆壚 廬 +型 陉 +垌 棟 +垒壘 儡 +垓 赅 +垛 剁 +垠 鄞 +垡 茷 +垢 诟 +垣 员 +垤 耋 +垦墾 恳 +垧 殤 +垩堊 锷 +垫墊 奠 +垭埡 鴉 +垮 侉 +垲塏 剀 +垴 瑙 +垸 掾 +埂 哽 +埃 哎 +埋 霾 +城 诚 +埏 閻 +埒 鬣 +埔 普 +埕 珵 +埘塒 识 +埙壎 勳 +埚堝 郭 +埝 廿 +域 誉 +埠 怖 +埤 陴 +埭 紿 +埯 唵 +埴 跖 +埸 蜴 +培 裴 +基 箕 +埽 扫 +堀 矻 +堂 膛 +堆 怼 +堇 锦 +堉 淯 +堋 掤 +堍 鵵 +堑塹 倩 +堕墮 惰 +堙 慇 +堞 牒 +堠 鱟 +堡 宝 +堤 氐 +堪 勘 +堰 嚥 +堵 睹 +塄 薐 +塌 趿 +塍 棖 +塑 速 +塔 獭 +塘 棠 +塚 种 +塞 腮 +塥 鎘 +填 恬 +塬 螈 +塭 轀 +塽 孀 +塾 赎 +墀 遲 +墁 縵 +境 镜 +墅 数 +墉 鳙 +墒 熵 +墓 暮 +墙牆 蔷 +墚 良 +增 赠 +墟 胥 +墦 蹯 +墨 漠 +墩 礅 +墼 屐 +壁 璧 +壅 拥 +壑 鶴 +壕 嚎 +壤 瓤 +士 仕 +壬 任 +壮壯 幢 +声聲 笙 +壳殼 咳 +壶壺 弧 +壹 祎 +夂 酯 +处處 褚 +备備 惫 +変 便 +复 腹 +夏 吓 +夔 奎 +夕 汐 +外 歪 +夙 肅 +多 哆 +夜 腋 +够夠 垢 +夤 齦 +夥 活 +大 达 +天 添 +太 肽 +夫 敷 +夭 腰 +央 秧 +夯 沆 +失 狮 +头頭 骰 +夷 姨 +夸誇 姱 +夹夾 荚 +夺奪 踱 +夼 誑 +奁奩 联 +奂奐 宦 +奄 眼 +奇 崎 +奈 萘 +奉 凤 +奋奮 鲼 +奎 夔 +奏 揍 +契 弃 +奔 贲 +奕 邑 +奖獎 桨 +套 陶 +奘 臓 +奚 谿 +奠 电 +奢 赊 +奥奧 澳 +奭 襫 +女 釹 +奴 努 +奶 乃 +奸 歼 +她 褟 +好 恏 +妁 蒴 +如 茹 +妃 飞 +妄 忘 +妆妝 装 +妇婦 赋 +妈媽 蚂 +妊 飪 +妍 颜 +妒 度 +妓 技 +妖 夭 +妗 劲 +妙 渺 +妞 牛 +妣 秕 +妤 虞 +妥 椭 +妨 防 +妩嫵 侮 +妪嫗 譽 +妫媯 龟 +妮 倪 +妯 碡 +妲 怛 +妳 擬 +妹 寐 +妻 栖 +妾 挈 +姅 絆 +姆 牡 +姊 秭 +始 矢 +姐 解 +姑 菇 +姒 泗 +姓 杏 +委 玮 +姗姍 删 +姘 拼 +姚 摇 +姜 僵 +姝 樞 +姣 鲛 +姥 栳 +姦 鲣 +姨 胰 +姬 嵇 +姹奼 汊 +姻 氤 +姿 咨 +威 葳 +娃 洼 +娄婁 喽 +娅婭 氬 +娆嬈 饒 +娇嬌 骄 +娈孌 卵 +娉 乒 +娌 礼 +娑 缩 +娓 尾 +娘 酿 +娜 纳 +娟 鹃 +娠 身 +娣 递 +娥 莪 +娩 腼 +娱娛 愚 +娲媧 袜 +娴嫻 痫 +娶 衢 +娼 猖 +婀 屙 +婆 鄱 +婉 宛 +婊 彪 +婕 节 +婚 荤 +婢 痺 +婧 净 +婪 兰 +婴嬰 缨 +婵嬋 潺 +婶嬸 沈 +婷 停 +婺 鹜 +婿 旭 +媒 煤 +媚 昧 +媛 愿 +媪媼 袄 +媲 闢 +媳 袭 +媵 硬 +媸 喫 +媾 构 +嫁 驾 +嫂 騒 +嫉 蒺 +嫌 咸 +嫒嬡 爱 +嫔嬪 贫 +嫖 瓢 +嫘 縲 +嫜 鄣 +嫠 蜊 +嫡 涤 +嫣 湮 +嫦 尝 +嫩 恁 +嫫 馍 +嫱嬙 墙 +嬉 熹 +嬖 躄 +嬗 鱔 +嬝 鳥 +嬲 鸟 +嬴 赢 +嬷嬤 麽 +孀 双 +孃 釀 +子 梓 +孑 杰 +孓 绝 +孔 恐 +孕 蕴 +字 渍 +存 忖 +孙孫 狲 +孚 涪 +孛 褙 +孜 兹 +孝 傚 +孟 猛 +孢 褒 +季 悸 +孤 箍 +孥 笯 +学學 峃 +孩 亥 +孪孿 鸾 +孬 闹 +孰 熟 +孱 纏 +孳 諮 +孵 麸 +孺 濡 +孽 蘖 +宀 麪 +宁寧 柠 +它 塌 +宄 軌 +宅 翟 +宇 羽 +守 艏 +安 鞍 +宋 颂 +完 顽 +宏 弘 +宓 祕 +宕 凼 +宗 棕 +官 鳏 +宙 昼 +定 锭 +宛 惋 +宜 夷 +宝寶 葆 +实實 鲥 +宠寵 冲 +审審 婶 +客 刻 +宣 萱 +室 侍 +宥 祐 +宦 患 +宪憲 羡 +宫宮 功 +宰 仔 +害 骇 +宴 晏 +宵 硝 +家 佳 +宸 沉 +容 熔 +宽寬 髋 +宾賓 滨 +宿 肃 +寂 计 +寄 霁 +寅 龈 +密 蜜 +寇 蔻 +富 负 +寐 媚 +寒 函 +寓 育 +寝寢 沁 +寞 蓦 +察 茬 +寡 剐 +寤 焐 +寥 疗 +寨 砦 +寮 獠 +寰 鬟 +寸 吋 +对對 兑 +寺 四 +寻尋 浔 +导導 捣 +寿壽 售 +封 烽 +射 麝 +将將 浆 +尉 位 +尊 遵 +小 晓 +少 哨 +尔爾 迩 +尕 尜 +尖 监 +尘塵 辰 +尚 赏 +尜 轧 +尝嘗 裳 +尢 尪 +尤 鱿 +尥 鐐 +尧堯 谣 +尬 噶 +就 臼 +尴尷 泔 +尸屍 湿 +尹 引 +尺 侈 +尻 攷 +尼 鲵 +尽 烬 +尾 委 +尿 脲 +局 焗 +屁 辟 +层層 噌 +居 拘 +屈 区 +屉屜 嚏 +届屆 界 +屋 乌 +屎 使 +屏 瓶 +屐 飢 +屑 泄 +展 辗 +屘 螨 +屙 婀 +屝 蜚 +属屬 鼠 +屠 途 +屡屢 侣 +屣 喜 +履 屡 +屦屨 飓 +屮 扯 +屯 饨 +山 衫 +屹 义 +屺 綺 +屿嶼 舆 +岁歲 穗 +岂豈 杞 +岈 睚 +岌 棘 +岍 騫 +岐 歧 +岑 涔 +岔 诧 +岖嶇 屈 +岗崗 港 +岘峴 莧 +岙嶴 襖 +岚嵐 攔 +岛島 蹈 +岜 吧 +岢 砢 +岣 狗 +岩巖 严 +岫 琇 +岬 假 +岭嶺 零 +岱 待 +岳嶽 阅 +岵 瓠 +岷 旻 +岸 黯 +岽崠 冬 +岿巋 愧 +峁 卯 +峄嶧 懌 +峋 巡 +峒 同 +峙 稚 +峡峽 狭 +峤嶠 僑 +峥崢 争 +峦巒 孪 +峨 讹 +峪 玉 +峭 鞘 +峰 锋 +峻 竣 +崁 看 +崂嶗 牢 +崃崍 萊 +崆 孔 +崇 虫 +崎 骑 +崑 鯤 +崔 催 +崖 涯 +崙 淪 +崛 厥 +崞 蟈 +崤 淆 +崦 腌 +崧 松 +崩 绷 +崭嶄 盏 +崮 痼 +崴 竵 +崽 灾 +崾 窅 +嵇 缉 +嵊 賸 +嵋 鹛 +嵌 芡 +嵘嶸 溶 +嵛 妤 +嵝嶁 簍 +嵩 崧 +嵫 孳 +嵬 潍 +嵯 痤 +嵴 麂 +嶂 幛 +嶔 衾 +嶙 麟 +嶝 鐙 +嶷 沂 +巅巔 顛 +巉 饞 +巍 煨 +巛 氚 +川 穿 +州 粥 +巡 循 +巢 潮 +工 躬 +左 昨 +巧 愀 +巨 炬 +巩鞏 汞 +巫 诬 +差 岔 +巯巰 俅 +己 几 +已 蚁 +巳 飼 +巴 笆 +巷 像 +巽 训 +巾 筋 +币幣 蔽 +市 嗜 +布 埠 +帅帥 蟀 +帆 藩 +师師 诗 +希 稀 +帏幃 闈 +帐帳 杖 +帑 傥 +帔 辔 +帕 啪 +帖 铁 +帘簾 镰 +帙 摯 +帚 轴 +帛 伯 +帜幟 志 +帝 缔 +帟 嶧 +带帶 戴 +帧幀 祯 +席 檄 +帮幫 幇 +帱幬 俦 +帷 帏 +常 徜 +帻幘 责 +帼幗 腘 +帽 貌 +幂冪 觅 +幄 渥 +幅 辐 +幌 恍 +幔 谩 +幕 募 +幛 脹 +幞 菔 +幡 翻 +幢 撞 +干 竿 +平 萍 +年 黏 +并並 摒 +幸 荇 +幹 旰 +幺 妖 +幻 唤 +幼 釉 +幽 攸 +广廣 犷 +庀 圮 +庄莊 桩 +庆慶 磬 +庇 陛 +床牀 闯 +庋 匭 +序 叙 +庐廬 卢 +庑廡 嫵 +库庫 酷 +应應 樱 +底 邸 +庖 疱 +店 惦 +庙廟 缪 +庚 赓 +府 俯 +庞龐 彷 +废廢 沸 +庠 詳 +庥 貅 +度 杜 +座 祚 +庭 霆 +庳 髀 +庵 鹌 +庶 树 +康 慷 +庸 慵 +庹 妥 +庾 瘐 +廉 帘 +廊 榔 +廑 馑 +廒 鏖 +廓 蛞 +廖 撂 +廛 瀍 +廨 邂 +廪廩 檩 +廴 喑 +延 蜒 +廷 庭 +建 鍵 +廾 鞏 +廿 念 +开開 揩 +弁 辩 +异異 翼 +弃棄 砌 +弄 秾 +弈 繹 +弊 敝 +弋 羿 +式 试 +弑弒 礻 +弓 宫 +弔 釣 +引 蚓 +弗 彿 +弘 鸿 +弛 馳 +弟 第 +张張 彰 +弥彌 猕 +弦 舷 +弧 狐 +弩 奴 +弪弳 迳 +弭 米 +弯彎 豌 +弱 偌 +弹彈 惮 +强強 樯 +弼 皕 +彀 够 +彆 瘪 +彊 薔 +彐 覬 +归歸 圭 +当當 铛 +录錄 禄 +彖 湍 +彗 秽 +彘 擲 +彙 繪 +彝 移 +彡 釤 +形 型 +彤 佟 +彦彥 谚 +彩 睬 +彪 膘 +彫 鯛 +彬 斌 +彭 澎 +彰 樟 +影 颖 +彳 翅 +彷 旁 +役 毅 +彻徹 澈 +彼 匕 +彿 鳧 +往 枉 +征 蒸 +徂 粗 +径徑 痉 +待 玳 +徇 讯 +很 痕 +徉 羊 +徊 槐 +律 虑 +後 逅 +徐 俆 +徒 兔 +徕徠 涞 +得 嘚 +徘 牌 +徙 玺 +徜 償 +御 驭 +徨 隍 +復 鰒 +循 询 +徬 逄 +徭 瑤 +微 薇 +徵 铮 +德 惪 +徼 缴 +徽 辉 +心 芯 +忄 鑫 +必 毖 +忆憶 亿 +忉 舠 +忌 纪 +忍 荏 +忏懺 颤 +忐 钽 +忑 忒 +忒 脦 +忖 寸 +志 智 +忘 望 +忙 芒 +忝 殄 +忠 鍾 +忡 翀 +忤 憮 +忧憂 幽 +忪 菘 +快 脍 +忭 抃 +忮 躓 +忱 陈 +念 艌 +忸 狃 +忻 锌 +忽 惚 +忾愾 愒 +忿 愤 +怀懷 懐 +态態 汰 +怂慫 耸 +怃憮 庑 +怄慪 沤 +怅悵 唱 +怆愴 牀 +怊 鈔 +怍 胙 +怎 譖 +怏 恙 +怒 驽 +怔 症 +怕 帕 +怖 佈 +怙 岵 +怛 打 +怜憐 莲 +思 飔 +怠 殆 +怡 贻 +急 疾 +怦 碰 +性 姓 +怨 院 +怩 妮 +怪 夬 +怫 蚨 +怯 锲 +怵 憷 +总總 偬 +怼懟 队 +怿懌 轶 +恁 您 +恂 珣 +恃 軾 +恋戀 炼 +恍 晃 +恐 倥 +恒恆 珩 +恕 述 +恙 样 +恚 彗 +恝 郏 +恢 詼 +恣 字 +恤 絮 +恧 衄 +恨 詪 +恩 摁 +恪 课 +恫 洞 +恬 田 +恭 龚 +息 熄 +恰 洽 +恳懇 肯 +恶惡 鄂 +恸慟 通 +恹懨 鄢 +恺愷 凱 +恻惻 厕 +恼惱 垴 +恽惲 韫 +恿 勇 +悃 裍 +悄 锹 +悉 夕 +悌 屜 +悍 捍 +悒 翳 +悔 诲 +悖 憊 +悚 慫 +悛 勸 +悝 虧 +悟 坞 +悠 忧 +患 焕 +悦悅 玥 +您 拰 +悫愨 闕 +悬懸 旋 +悭慳 謙 +悯憫 闵 +悱 誹 +悲 卑 +悴 啐 +悸 鯽 +悻 幸 +悼 倒 +情 氰 +惆 籌 +惇 鈍 +惊驚 京 +惋 皖 +惑 霍 +惕 屉 +惘 网 +惚 唿 +惜 昔 +惝 厂 +惟 维 +惠 晦 +惦 殿 +惧懼 俱 +惨慘 蚕 +惩懲 承 +惫憊 倍 +惬愜 窃 +惭慚 璨 +惮憚 澹 +惯慣 掼 +惰 舵 +想 享 +惴 骓 +惶 蝗 +惹 喏 +惺 猩 +愀 鍬 +愁 酬 +愆 韆 +愈 谕 +愉 渝 +愍 閔 +愎 弼 +意 臆 +愒 忾 +愕 颚 +愚 隅 +感 秆 +愠慍 晕 +愣 稜 +愤憤 奋 +愦憒 簣 +愧 溃 +愫 夙 +愿願 苑 +慄 隸 +慇 洇 +慈 磁 +慊 趄 +慌 荒 +慎 蜃 +慑懾 射 +慕 幕 +慝 犆 +慢 曼 +慧 卉 +慨 凯 +慰 尉 +慵 鄘 +慷 糠 +慼 榿 +慾 鈺 +憋 鳖 +憎 矰 +憔 瞧 +憝 兌 +憧 舂 +憨 酣 +憩 磧 +憬 警 +憷 亍 +憾 撼 +懂 董 +懈 蟹 +懊 傲 +懋 袤 +懐 耲 +懑懣 燜 +懒懶 览 +懔懍 凜 +懦 搦 +懵 蜢 +懿 詣 +戆戇 杠 +戈 鸽 +戊 务 +戋戔 牋 +戌 需 +戍 束 +戎 絨 +戏戲 细 +成 铖 +我 硪 +戒 誡 +戕 鏘 +或 惑 +戗戧 嗆 +战戰 湛 +戚 沏 +戛 蛱 +戟 掎 +戡 龛 +戢 楫 +戤 賅 +戥 等 +截 睫 +戬戩 减 +戮 碌 +戳 踔 +戴 代 +户戶 扈 +戽 鄠 +戾 唳 +房 妨 +所 琐 +扁 匾 +扃 坰 +扇 擅 +扈 笏 +扉 菲 +手 首 +扌 守 +才 裁 +扎 楂 +扑撲 噗 +扒 疤 +打 嗒 +扔 仍 +托 捝 +扛 炕 +扣 叩 +扦 阡 +执執 侄 +扩擴 阔 +扪捫 们 +扫掃 嫂 +扬揚 杨 +扭 纽 +扮 瓣 +扯 砗 +扰擾 娆 +扳 颁 +扶 拂 +批 坯 +扼 愕 +找 沼 +承 丞 +技 伎 +抄 钞 +抆 紊 +抉 訣 +把 靶 +抑 亦 +抒 殊 +抓 爪 +投 头 +抖 蚪 +抗 亢 +折 哲 +抚撫 腑 +抛拋 咆 +抟摶 糰 +抠摳 剾 +抡掄 囵 +抢搶 襁 +护護 户 +报報 豹 +抨 砰 +披 砒 +抬 邰 +抱 鲍 +抵 砥 +抹 沫 +抻 琛 +押 鸦 +抽 稠 +抿 闽 +拂 弗 +拄 渚 +担擔 眈 +拆 钗 +拇 母 +拈 蔫 +拉 喇 +拊 簠 +拌 扮 +拍 徘 +拎 淋 +拐 柺 +拒 巨 +拓 萚 +拔 跋 +拖 陀 +拗 坳 +拘 驹 +拙 涿 +拚 襻 +招 昭 +拜 稗 +拟擬 旎 +拢攏 陇 +拣揀 检 +拥擁 雍 +拦攔 澜 +拧擰 狞 +拨撥 玻 +择擇 啧 +括 廓 +拭 式 +拮 颉 +拯 猙 +拱 巩 +拳 诠 +拴 栓 +拶 昝 +拷 栲 +拼 姘 +拽 跩 +拾 食 +拿 呐 +持 驰 +挂掛 卦 +指 芷 +挈 切 +按 胺 +挎 夸 +挑 佻 +挖 娲 +挚摯 鸷 +挛攣 滦 +挝 踒 +挞撻 榻 +挟挾 谐 +挠撓 铙 +挡擋 档 +挢撟 矯 +挣掙 錚 +挤擠 嵴 +挥揮 徽 +挨 哀 +挪 傩 +挫 锉 +振 赈 +挲 桫 +挹 悒 +挺 艇 +挽 輓 +捂 妩 +捃 珺 +捅 桶 +捆 壸 +捉 拙 +捋 缕 +捌 峇 +捍 憾 +捎 蛸 +捏 聂 +捐 娟 +捕 哺 +捞撈 涝 +损損 笋 +捡撿 俭 +换換 涣 +捣搗 岛 +捧 鹏 +捨 灄 +捩 獵 +捭 襬 +据據 踞 +捱 癌 +捲 鐫 +捶 陲 +捷 婕 +捺 鈉 +捻 碾 +掀 锨 +掂 颠 +掇 多 +授 绶 +掉 窎 +掊 抙 +掌 涨 +掎 虮 +掏 滔 +掐 拤 +排 俳 +掖 爷 +掘 倔 +掠 略 +探 叹 +掣 彻 +接 秸 +控 崆 +推 蓷 +掩 奄 +措 挫 +掬 裾 +掭 舚 +掮 鉗 +掰 摆 +掳擄 虏 +掴 乖 +掷擲 至 +掸撣 亶 +掺摻 搀 +掼摜 贯 +掾 瑗 +揄 踰 +揆 逵 +揉 糅 +揍 邹 +揎 媗 +描 苗 +提 缇 +插 锸 +揖 医 +揞 晻 +揠 迓 +握 幄 +揣 搋 +揩 楷 +揪 啾 +揭 嗟 +揲 舌 +援 垣 +揶 爺 +揸 吒 +揹 桮 +揽攬 缆 +揿撳 寝 +搀攙 蝉 +搁擱 鴿 +搂摟 篓 +搅攪 侥 +搆 構 +搋 踹 +搌 嶄 +搏 膊 +搐 怵 +搓 磋 +搔 缫 +搛 縑 +搜 艘 +搞 镐 +搠 碩 +搡 颡 +搦 諾 +搪 唐 +搬 般 +搭 耷 +搴 骞 +携攜 协 +搽 猹 +搾 柵 +搿 擱 +摁 煾 +摄攝 赦 +摅攄 倏 +摆擺 柏 +摇搖 遥 +摈擯 鬓 +摊攤 滩 +摑 膕 +摒 併 +摔 衰 +摘 斋 +摞 落 +摧 崔 +摩 蘑 +摭 蹠 +摸 膜 +摹 謨 +摺 蛰 +撂 镣 +撄攖 櫻 +撅 噘 +撇 瞥 +撑撐 瞠 +撒 仨 +撕 廝 +撖 頷 +撙 噂 +撚 攆 +撞 壮 +撢 赕 +撤 掣 +撩 燎 +撬 窍 +播 菠 +撮 搓 +撰 篆 +撵攆 捻 +撷擷 缬 +撸擼 噜 +撺攛 汆 +撼 旱 +撾 抓 +擀 感 +擂 雷 +擅 赡 +操 糙 +擎 晴 +擐 渙 +擒 禽 +擗 鷿 +擘 檗 +擞擻 薮 +擢 濁 +擤 省 +擦 嚓 +擭 濩 +攀 潘 +攉 劐 +攒攢 趱 +攘 壤 +攥 纂 +攫 掘 +攮 曩 +支 肢 +攴 扑 +攵 潽 +收 狩 +攸 呦 +改 溉 +攻 觥 +放 坊 +政 怔 +故 固 +效 孝 +敉 脒 +敌敵 迪 +敏 悯 +救 鹫 +敔 龉 +敕 飭 +敖 翱 +教 酵 +敛斂 恋 +敝 毙 +敞 场 +敢 橄 +散 糁 +敦 吨 +敫 角 +敬 婧 +数數 庶 +敲 橇 +整 拯 +敷 趺 +文 纹 +斋齋 宅 +斌 濒 +斐 诽 +斑 扳 +斓斕 阑 +斗 窦 +料 廖 +斛 槲 +斜 偕 +斟 甄 +斡 沃 +斤 金 +斥 叱 +斧 釜 +斩斬 崭 +斫 鐲 +断斷 煅 +斯 嘶 +新 薪 +方 芳 +施 师 +旁 螃 +旃 栴 +旄 錨 +旅 履 +旆 呸 +旋 璇 +旌 粳 +旎 泥 +族 卒 +旒 瀏 +旖 苡 +旗 祺 +无無 芜 +既 暨 +日 驲 +旦 淡 +旧舊 桕 +旨 指 +早 枣 +旬 荀 +旭 恤 +旮 尕 +旯 臘 +旰 干 +旱 悍 +时時 莳 +旷曠 框 +旺 汪 +昀 筠 +昂 卬 +昃 赜 +昆 鲲 +昇 陞 +昊 号 +昌 菖 +明 茗 +昏 婚 +易 奕 +昔 析 +昕 鋅 +昙曇 壇 +昝 暂 +星 兴 +映 媵 +昤 鈴 +春 椿 +昧 袂 +昨 琢 +昭 钊 +是 室 +昱 预 +昴 峁 +昵暱 睨 +昶 敞 +昼晝 骤 +显顯 藓 +晁 朝 +晃 幌 +晅 揎 +晋晉 缙 +晌 垧 +晏 燄 +晒曬 筛 +晓曉 筱 +晔曄 謁 +晕暈 氲 +晖暉 挥 +晗 焓 +晚 挽 +晞 豨 +晟 剩 +晡 逋 +晤 寤 +晦 誨 +晨 宸 +普 谱 +景 璟 +晰 惜 +晴 凊 +晶 睛 +晷 氿 +智 治 +晾 量 +暂暫 錾 +暄 轩 +暇 霞 +暌 揆 +暍 鄴 +暑 署 +暖 煖 +暗 按 +暘 颺 +暝 蓂 +暧曖 璦 +暨 稷 +暮 牧 +暴 爆 +暸 繚 +暹 纖 +暾 飩 +曆 莅 +曙 薯 +曛 壎 +曜 钥 +曝 趵 +曦 犧 +曩 齉 +曰 越 +曲 蛐 +曳 页 +更 庚 +曷 阖 +曹 嘈 +曼 幔 +曾 層 +替 涕 +最 醉 +月 悦 +有 酉 +朊 软 +朋 蓬 +服 扶 +朐 鴝 +朔 槊 +朕 阵 +朗 烺 +望 旺 +朝 巢 +期 欺 +朦 盟 +木 沐 +未 味 +末 陌 +本 苯 +札 铡 +朮 杼 +术術 竖 +朱 茱 +朴 浦 +朵 垛 +机機 玑 +朽 休 +杀殺 刹 +杂雜 砸 +权權 拳 +杆 肝 +杈 衩 +杉 姗 +杌 兀 +李 鲤 +杏 悻 +材 才 +村 邨 +杓 烧 +杖 丈 +杗 硭 +杜 渡 +杞 起 +束 漱 +杠槓 罡 +条條 迢 +来來 莱 +杨楊 疡 +杩榪 螞 +杪 緲 +杭 颃 +杯 盃 +杰傑 竭 +杲 稿 +杳 舀 +杵 楚 +杷 耙 +杼 著 +松 凇 +板 阪 +极極 吉 +构構 购 +枇 皮 +枉 魍 +枋 方 +析 晰 +枓 紏 +枕 疹 +林 琳 +枘 汭 +枚 玫 +果 菓 +枝 吱 +枞樅 聪 +枢樞 梳 +枣棗 澡 +枥櫪 瀝 +枧 筧 +枨棖 橙 +枪槍 呛 +枫楓 峰 +枭梟 消 +枯 堀 +枰 凭 +枳 只 +枴 怪 +枵 鴞 +架 嫁 +枷 嘉 +枸 岣 +柁 跎 +柃 舲 +柄 丙 +柏 白 +某 谋 +柑 甘 +柒 漆 +染 冉 +柔 蹂 +柘 这 +柙 轄 +柚 鼬 +柜櫃 鳜 +柝 拖 +柞 酢 +柠檸 拧 +柢 詆 +查 碴 +柩 就 +柬 揀 +柯 珂 +柰 耐 +柱 注 +柳 绺 +柴 豺 +柽檉 蟶 +柿 市 +栀梔 卮 +栅柵 榨 +标標 镖 +栈棧 蘸 +栉櫛 滯 +栊櫳 朧 +栋棟 恫 +栌櫨 爐 +栎櫟 礫 +栏欄 拦 +树樹 墅 +栓 闩 +栖棲 戚 +栗 傈 +栘 嶷 +栝 胍 +校 啸 +栩 诩 +株 诛 +栲 銬 +栳 老 +样樣 漾 +核 阂 +根 哏 +格 骼 +栽 甾 +栾欒 娈 +桀 傑 +桁 姮 +桂 刽 +桃 萄 +桄 洸 +桅 帷 +框 眶 +案 岸 +桉 庵 +桊 雋 +桌 捉 +桎 窒 +桐 铜 +桑 嗓 +桓 寰 +桔 局 +桕 廄 +桠椏 垭 +桡橈 荛 +桢楨 貞 +档檔 宕 +桤榿 棲 +桥橋 荞 +桦樺 话 +桧檜 柜 +桨槳 讲 +桩樁 妝 +桫 簑 +桴 孚 +桶 捅 +桷 谲 +桿 稈 +梁 椋 +梂 赇 +梃 挺 +梅 酶 +梆 帮 +梏 雇 +梓 訾 +梗 埂 +梡 宽 +梢 稍 +梦夢 孟 +梧 吾 +梨 犁 +梭 唆 +梯 踢 +械 泻 +梱 困 +梳 蔬 +梵 泛 +检檢 捡 +棂欞 灵 +棉 眠 +棋 旗 +棍 辊 +棒 傍 +棕 鬃 +棘 輯 +棚 硼 +棠 螳 +棣 締 +森 槮 +棰 槌 +棱稜 楞 +棵 苛 +棹 詔 +棺 关 +棻 紛 +棼 枌 +椁槨 裹 +椅 旖 +椋 凉 +植 直 +椎 隹 +椐 雎 +椒 礁 +椟櫝 牘 +椠槧 欠 +椤欏 邏 +椭橢 庹 +椰 掖 +椴 緞 +椹 甚 +椽 船 +椿 蝽 +楂 揸 +楔 些 +楗 薦 +楚 础 +楛 鵠 +楝 煉 +楞 崚 +楠 腩 +楣 霉 +楦 絢 +楫 籍 +楮 处 +楱 輳 +楷 慨 +楸 秋 +楹 瀛 +楼樓 娄 +榀 聘 +概 钙 +榄欖 懒 +榆 觎 +榇櫬 龀 +榈櫚 闾 +榉櫸 举 +榍 亵 +榔 琅 +榕 戎 +榘 蒟 +榛 蓁 +榜 膀 +榣 徭 +榦 贛 +榧 匪 +榨 乍 +榫 隼 +榭 洩 +榱 凗 +榴 骝 +榷 雀 +榻 踏 +槁 搞 +槃 媻 +槊 妁 +槌 鎚 +槎 茶 +槐 踝 +槔 睾 +槛檻 坎 +槟檳 兵 +槠櫧 猪 +槭 訖 +槲 斛 +槽 曹 +槿 仅 +樊 繁 +樑 踉 +樗 摴 +樘 溏 +樟 章 +模 摹 +樨 錫 +横橫 恒 +樯檣 牆 +樱櫻 婴 +樵 桥 +樸 鏷 +樽 鳟 +樾 嶽 +橄 桿 +橇 跷 +橐 脱 +橘 菊 +橙 澄 +橛 镢 +橡 象 +橥櫫 潴 +橱櫥 刍 +橹櫓 掳 +橼櫞 蝝 +橾 皁 +檀 潭 +檄 媳 +檎 覃 +檐簷 阎 +檑 镭 +檗 擘 +檠 棾 +檩檁 凛 +檫 镲 +檬 蒙 +檮 洮 +檯 駘 +櫂 笊 +櫺 綾 +欐 儷 +欠 嵌 +次 赐 +欢歡 獾 +欣 忻 +欤歟 輿 +欧歐 鸥 +欲 峪 +欷 浠 +欹 攲 +欺 凄 +款 窾 +歃 唼 +歆 心 +歇 蝎 +歉 堑 +歌 戈 +歎 灘 +歙 厙 +歜 绌 +止 址 +正 挣 +此 跐 +步 歩 +武 捂 +歧 岐 +歪 喎 +歷 櫪 +歹 傣 +死 巳 +歼殲 缄 +殁歿 末 +殂 徂 +殃 鸯 +殄 觍 +殆 袋 +殇殤 商 +殉 徇 +殊 姝 +残殘 惭 +殍 瞟 +殒殞 允 +殓殮 练 +殖 姪 +殚殫 簞 +殛 瘠 +殡殯 摈 +殪 曀 +殳 纾 +殴毆 讴 +段 椴 +殷 音 +殿 淀 +毁毀 悔 +毂轂 谷 +毅 役 +毋 蜈 +母 姆 +每 镁 +毒 犊 +毓 鬱 +比 俾 +毕畢 碧 +毖 铋 +毗 枇 +毙斃 弊 +毚 鑱 +毛 茅 +毡氈 沾 +毪 畝 +毫 豪 +毬 梂 +毯 坦 +毳 焠 +毵毿 犙 +毹 菽 +毽 腱 +氅 畅 +氆 鐠 +氇氌 擄 +氍 蠷 +氏 舐 +氐 滴 +民 岷 +氓 盲 +气氣 気 +氕 覕 +氖 奶 +気 汽 +氘 魛 +氙 秈 +氚 釧 +氛 酚 +氟 符 +氡 懂 +氢氫 卿 +氤 因 +氦 害 +氧 痒 +氨 桉 +氩氬 揠 +氪 克 +氮 憚 +氯 率 +氰 擎 +氲氳 煴 +水 睡 +氵 氺 +永 咏 +氽 魨 +氾 汎 +汀 町 +汁 支 +求 裘 +汆 蹿 +汇匯 荟 +汉漢 焊 +汊 侘 +汍 烷 +汎 繙 +汐 矽 +汔 碛 +汕 讪 +汗 翰 +汙 誣 +汛 驯 +汜 耜 +汝 入 +汞 珙 +江 姜 +池 弛 +污 巫 +汤湯 嘡 +汨 冪 +汩 骨 +汪 尫 +汰 泰 +汲 岌 +汴 辨 +汶 揾 +汹洶 雄 +汽 迄 +汾 豮 +沁 揿 +沂 疑 +沃 卧 +沅 元 +沆 航 +沈 哂 +沉 忱 +沌 顿 +沍 冱 +沏 期 +沐 目 +沓 蹋 +沔 鮸 +沖 茺 +沘 舭 +沙 莎 +沛 帔 +沟溝 钩 +没沒 梅 +沣灃 酆 +沤漚 怄 +沥瀝 雳 +沦淪 抡 +沧滄 伧 +沩溈 为 +沪滬 护 +沫 茉 +沬 鎂 +沭 腧 +沮 榉 +沱 酡 +沲 鼉 +河 菏 +沸 吠 +油 邮 +治 秩 +沼 招 +沽 姑 +沾 粘 +沿 言 +泄 卸 +泅 酋 +泉 醛 +泊 箔 +泌 幂 +泐 樂 +泓 閎 +泔 坩 +法 砝 +泖 鉚 +泗 驷 +泛 范 +泜 坻 +泞濘 甯 +泠 瓴 +泡 砲 +波 剥 +泣 气 +泥 尼 +注 伫 +泪淚 肋 +泫 鉉 +泮 判 +泯 敏 +泰 态 +泱 殃 +泳 踊 +泵 蹦 +泶澩 噱 +泷瀧 籠 +泸瀘 颅 +泺濼 駱 +泻瀉 懈 +泼潑 坡 +泽澤 择 +泾涇 经 +洁潔 结 +洄 蛔 +洇 铟 +洋 徉 +洌 趔 +洎 偈 +洒灑 飒 +洗 铣 +洙 侏 +洚 醬 +洛 珞 +洞 侗 +津 今 +洧 鮪 +洩 蠍 +洪 宏 +洫 蓿 +洮 鼗 +洱 珥 +洲 辀 +洳 乳 +洵 峋 +洸 獷 +洹 欢 +活 伙 +洼窪 哇 +洽 髂 +派 湃 +流 硫 +浃浹 夹 +浅淺 遣 +浆漿 缰 +浇澆 娇 +浈湞 禎 +浊濁 镯 +测測 策 +浍澮 儈 +济濟 薺 +浏瀏 刘 +浑渾 馄 +浒滸 虎 +浓濃 哝 +浔潯 鲟 +浙 蔗 +浚 俊 +浜 謗 +浞 斲 +浠 郗 +浣 鲩 +浥 镒 +浦 溥 +浩 皓 +浪 阆 +浬 里 +浮 俘 +浯 汙 +浴 欲 +海 氦 +浸 近 +浼 每 +涂塗 荼 +涅 啮 +消 霄 +涉 设 +涊 辇 +涌 蛹 +涎 嫌 +涑 餗 +涓 镌 +涔 梣 +涕 倜 +涛濤 掏 +涝澇 烙 +涞淶 崃 +涟漣 连 +涠潿 幃 +涡渦 莴 +涣渙 痪 +涤滌 荻 +润潤 闰 +涧澗 件 +涨漲 胀 +涩澀 啬 +涪 浮 +涫 鹳 +涮 腨 +涯 衙 +液 夜 +涵 寒 +涸 頜 +涿 桌 +淀 靛 +淄 孜 +淅 皙 +淆 崤 +淇 棋 +淋 霖 +淌 躺 +淑 叔 +淒 悽 +淖 挠 +淘 啕 +淙 琮 +淝 腓 +淞 嵩 +淠 紕 +淡 氮 +淤 迂 +淦 绀 +淫 吟 +淬 瘁 +淮 徊 +深 呻 +淳 鹑 +混 诨 +淹 焉 +添 舔 +淼 缈 +清 蜻 +渊淵 鹓 +渌淥 祿 +渍漬 眦 +渎瀆 櫝 +渐漸 溅 +渑澠 黾 +渔漁 逾 +渖瀋 嬸 +渗滲 肾 +渚 囑 +渝 俞 +渠 瞿 +渡 镀 +渣 喳 +渤 驳 +渥 龌 +温溫 榅 +渫 屧 +渭 未 +港 刚 +渲 眩 +渴 坷 +游 犹 +渺 眇 +湃 蒎 +湄 黴 +湍 团 +湎 靦 +湓 葐 +湔 鞯 +湖 葫 +湘 箱 +湛 站 +湟 徨 +湣 黽 +湧 踴 +湩 艐 +湫 鰍 +湮 烟 +湲 橼 +湾灣 蜿 +湿 施 +溃潰 馈 +溅濺 贱 +溆漵 酗 +溉 概 +溏 糖 +源 原 +準 埻 +溘 剋 +溜 熘 +溟 暝 +溢 縊 +溥 朴 +溧 隶 +溪 西 +溯 素 +溱 砧 +溲 餿 +溴 秀 +溶 蓉 +溷 混 +溺 匿 +溻 他 +溼 釃 +溽 洳 +滁 厨 +滂 耪 +滇 掂 +滋 淄 +滏 嘸 +滑 哗 +滓 紫 +滔 韬 +滕 疼 +滗潷 嗶 +滚滾 磙 +滞滯 质 +滟灩 諺 +滠灄 歙 +满滿 満 +滢瀅 楹 +滤濾 律 +滥濫 蓝 +滦灤 銮 +滨濱 缤 +滩灘 怹 +滴 嘀 +滹 虖 +漂 缥 +漆 七 +漉 陆 +漏 镂 +漓 縭 +演 掩 +漕 艚 +漠 莫 +漤 攬 +漩 玄 +漪 咿 +漫 蔓 +漭 铓 +漯 摞 +漱 戍 +漳 璋 +漶 煥 +漾 様 +潆瀠 蝇 +潇瀟 簫 +潋瀲 殓 +潍濰 桅 +潘 攀 +潜潛 虔 +潞 璐 +潟 卌 +潠 馴 +潢 黄 +潦 僚 +潭 坛 +潮 嘲 +潲 紹 +潴瀦 銖 +潸 姍 +潺 孱 +潼 朣 +澄 惩 +澈 撤 +澉 敢 +澌 鷥 +澍 沭 +澎 膨 +澜瀾 斓 +澡 藻 +澦 蕷 +澧 鱧 +澱 巔 +澳 懊 +澴 闤 +澶 蟬 +澹 弹 +激 击 +濂 簾 +濉 睢 +濑瀨 癞 +濒瀕 宾 +濕 蓍 +濛 虻 +濞 狴 +濠 嗥 +濡 蠕 +濩 蠖 +濬 駿 +濮 匍 +濯 擢 +瀑 舖 +瀚 汉 +瀛 迎 +瀣 瀉 +瀰 獼 +瀵 僨 +瀹 籥 +灌 罐 +灏灝 颢 +灞 鲅 +火 夥 +灬 鈥 +灭滅 蔑 +灯燈 蹬 +灰 恢 +灵靈 凌 +灶 皂 +灸 久 +灼 啄 +灾災 哉 +灿燦 粲 +炀煬 瘍 +炅 囧 +炉爐 庐 +炊 捶 +炎 研 +炒 抄 +炔 确 +炕 抗 +炖燉 囤 +炙 置 +炜煒 伪 +炝熗 跄 +炤 釗 +炫 渲 +炬 距 +炭 碳 +炮 袍 +炯 窘 +炱 鲐 +炳 柄 +炷 助 +炸 诈 +点點 踮 +炻 实 +炼煉 链 +炽熾 敕 +烀 滹 +烁爍 铄 +烂爛 滥 +烃烴 听 +烈 冽 +烊 旸 +烘 轰 +烙 酪 +烛燭 躅 +烟煙 咽 +烤 犒 +烦煩 樊 +烧燒 梢 +烨燁 晔 +烩燴 薈 +烫燙 趟 +烬燼 晉 +热熱 惹 +烯 晞 +烷 完 +烹 抨 +烽 沣 +焉 嫣 +焊 瀚 +焐 痦 +焓 琀 +焕煥 奂 +焖燜 懑 +焘燾 絛 +焙 碚 +焚 棼 +焜 醌 +焦 蕉 +焯 绰 +焰 艳 +焱 硯 +然 燃 +煅 鍛 +煆 短 +煊 宣 +煌 篁 +煎 殲 +煖 渜 +煜 吁 +煞 厦 +煤 枚 +煦 敘 +照 罩 +煨 威 +煮 嘱 +煲 剝 +煳 糊 +煸 编 +煺 颓 +煽 杉 +熄 螅 +熊 兄 +熏燻 薰 +熔 榕 +熘 溜 +熙 曦 +熟 塾 +熠 驛 +熨 运 +熬 敖 +熳 漫 +熵 觞 +熹 僖 +燃 髯 +燄 彥 +燎 潦 +燐 遴 +燔 蕃 +燕 雁 +燠 瘉 +燥 噪 +燧 髓 +燬 譭 +燮 褻 +燸 薷 +燹 蘚 +爆 曝 +爝 嚼 +爨 窜 +爪 撾 +爬 琶 +爰 蝯 +爱愛 暧 +爵 觉 +父 阜 +爷爺 耶 +爸 霸 +爹 堞 +爻 肴 +爽 塽 +爿 盘 +片 骈 +版 坂 +牌 排 +牍牘 瀆 +牒 鲽 +牖 卣 +牙 芽 +牛 钮 +牝 品 +牟 侔 +牠 溻 +牡 亩 +牢 醪 +牦犛 毛 +牧 睦 +物 勿 +牮 諫 +牯 钴 +牲 声 +牴 骶 +牵牽 千 +特 忑 +牺犧 羲 +牾 唔 +牿 梏 +犀 息 +犁 黎 +犄 鸡 +犊犢 读 +犋 钜 +犍 肩 +犏 谝 +犒 靠 +犟 降 +犬 畎 +犭 犬 +犯 梵 +犰 虬 +犴 堓 +状狀 妆 +犷獷 逛 +犸 瑪 +犹猶 魷 +狁 隕 +狂 诳 +狃 妞 +狄 嫡 +狈狽 备 +狍 鞄 +狎 俠 +狐 胡 +狒 芾 +狗 苟 +狙 鞠 +狞獰 凝 +狠 很 +狡 铰 +狨 融 +狩 受 +独獨 牍 +狭狹 侠 +狮獅 虱 +狯獪 哙 +狰猙 峥 +狱獄 浴 +狲猻 荪 +狳 馀 +狴 蓖 +狷 倦 +狸 厘 +狺 霪 +狻 算 +狼 郎 +猁 吏 +猃獫 嶮 +猊 怩 +猎獵 劣 +猓 粿 +猕獼 糜 +猖 鲳 +猗 衤 +猛 勐 +猜 材 +猝 促 +猞 賒 +猡玀 鑼 +猢 醐 +猥 萎 +猩 腥 +猪豬 朱 +猫貓 锚 +猬蝟 餵 +献獻 陷 +猱 呶 +猴 喉 +猷 楢 +猸 苺 +猹 察 +猾 滑 +猿 辕 +獍 敬 +獐 蟑 +獒 嗷 +獗 蕨 +獠 療 +獬 澥 +獭獺 鳎 +獯 曛 +獾 懽 +玄 悬 +玆 資 +率 滤 +玉 钰 +王 惘 +玎 丁 +玑璣 饑 +玖 九 +玛瑪 马 +玟 紋 +玢 邠 +玥 樾 +玨 孓 +玩 丸 +玫 眉 +玮瑋 緯 +环環 桓 +现現 宪 +玲 聆 +玳 貸 +玷 澱 +玺璽 屣 +玻 波 +珀 皛 +珂 軻 +珈 加 +珉 民 +珊 跚 +珍 贞 +珏 攫 +珐琺 法 +珑瓏 隆 +珙 栱 +珞 犖 +珠 株 +珥 餌 +珧 謠 +珩 衡 +珪 龜 +班 斑 +珮 姵 +珲琿 翬 +球 逑 +琅 锒 +理 醴 +琉 流 +琊 伢 +琍 痢 +琏璉 脸 +琐瑣 索 +琚 鋸 +琛 郴 +琢 灼 +琥 浒 +琦 齐 +琨 崑 +琪 淇 +琬 畹 +琮 悰 +琯 館 +琰 鼹 +琳 磷 +琴 擒 +琵 蚍 +琶 杷 +琼瓊 穹 +瑁 懋 +瑕 匣 +瑗 湲 +瑙 脑 +瑚 湖 +瑛 嬰 +瑜 覦 +瑞 睿 +瑟 涩 +瑭 醣 +瑯 啷 +瑰 归 +瑶瑤 窑 +瑷璦 嫒 +瑾 谨 +璀 缞 +璁 匆 +璃 篱 +璇 漩 +璋 獐 +璎瓔 罂 +璐 露 +璘 鄰 +璜 潢 +璞 僕 +璟 剄 +璧 避 +璨 燦 +璩 龋 +璺 问 +璿 鏇 +瓒瓚 攒 +瓖 鑲 +瓜 鸹 +瓞 昳 +瓠 互 +瓢 飘 +瓣 办 +瓤 禳 +瓦 佤 +瓮甕 翁 +瓯甌 欧 +瓴 翎 +瓶 平 +瓷 茨 +瓿 步 +甄 臻 +甍 矇 +甏 镚 +甑 锃 +甓 淠 +甘 苷 +甙 軑 +甚 葚 +甜 阗 +生 牲 +甥 生 +甦 穌 +用 佣 +甩 摔 +甫 脯 +甬 湧 +甭 崩 +甯 佞 +田 甜 +由 尤 +甲 钾 +申 伸 +电電 甸 +男 喃 +甸 佃 +町 烴 +画畫 婳 +甽 綣 +甾 菑 +畀 荜 +畅暢 怅 +畈 販 +畋 闐 +界 介 +畎 绻 +畏 喂 +畔 叛 +留 榴 +畚 本 +畛 诊 +畜 搐 +略 畧 +畦 奇 +番 幡 +畲 猞 +畴疇 踌 +畸 犄 +畹 菀 +畿 机 +疃 漙 +疆 薑 +疋 癖 +疏 书 +疑 遗 +疒 訥 +疔 耵 +疖癤 街 +疗療 嘹 +疙 胳 +疚 咎 +疝 扇 +疟瘧 虐 +疠癘 礪 +疡瘍 阳 +疢 榇 +疣 游 +疤 巴 +疥 借 +疫 抑 +疬 枥 +疮瘡 创 +疯瘋 风 +疰 鑄 +疱皰 泡 +疲 琵 +疳 咁 +疴痾 訛 +疵 呲 +疸 掸 +疹 缜 +疼 藤 +疽 居 +疾 笈 +痂 袈 +痃 玹 +痄 炸 +病 炳 +症 政 +痈癰 臃 +痉痙 胫 +痊 荃 +痍 遺 +痒癢 仰 +痔 畤 +痕 狠 +痖 哑 +痘 逗 +痛 恸 +痞 劈 +痠 酸 +痢 猁 +痣 幟 +痤 矬 +痦 塢 +痧 紗 +痨癆 劳 +痪瘓 换 +痫癇 鹇 +痰 谈 +痱 费 +痲 嘛 +痳 菻 +痴 哧 +痹 庇 +痺 篳 +痼 錮 +痿 諉 +瘀 淤 +瘁 悴 +瘃 燭 +瘅癉 箪 +瘉 鬻 +瘊 骺 +瘌 剌 +瘐 諛 +瘕 鉀 +瘗瘞 囈 +瘘 鏤 +瘙 骚 +瘛 瘈 +瘟 温 +瘠 亟 +瘢 班 +瘤 馏 +瘥 拆 +瘦 兽 +瘩 搭 +瘪癟 憋 +瘫癱 贪 +瘭 驃 +瘰 裸 +瘳 搊 +瘴 障 +瘵 齋 +瘸 缺 +瘺 摟 +瘼 貘 +瘾癮 饮 +瘿癭 穎 +癀 璜 +癃 栊 +癌 皑 +癍 頒 +癒 毓 +癔 薏 +癖 匹 +癜 玷 +癞癩 赖 +癡 瓻 +癣癬 选 +癥 徵 +癫癲 巅 +癯 渠 +癸 晷 +登 噔 +發 伐 +白 佰 +百 捭 +皂皁 燥 +的 菂 +皆 阶 +皇 凰 +皈 瑰 +皋 膏 +皎 絞 +皑皚 捱 +皓 澔 +皖 晚 +皙 蜥 +皤 婆 +皮 毗 +皱皺 咒 +皲皸 军 +皴 村 +皿 抿 +盂 余 +盃 鵯 +盅 中 +盆 湓 +盈 荧 +益 溢 +盍 闔 +盎 岇 +盏盞 展 +盐鹽 炎 +监監 间 +盒 合 +盔 窥 +盖蓋 丐 +盗盜 稻 +盘盤 磐 +盛 胜 +盟 萌 +盡 藎 +盥 貫 +盪 襠 +目 苜 +盯 叮 +盱 须 +盲 茫 +直 值 +相 湘 +盹 趸 +盼 泮 +盾 遁 +省 眚 +眄 湎 +眇 杪 +眈 单 +眉 楣 +看 瞰 +眍 芤 +眙 飴 +眚 升 +真 斟 +眠 绵 +眢 鸢 +眦眥 胔 +眨 砟 +眩 绚 +眭 綏 +眯 咪 +眵 鸱 +眶 旷 +眷 隽 +眸 哞 +眺 粜 +眼 衍 +着 遮 +睁睜 筝 +睃 羧 +睇 娣 +睏 綑 +睐睞 濑 +睑瞼 撿 +睚 訝 +睛 惊 +睡 涚 +睢 虽 +督 嘟 +睥 裨 +睦 穆 +睨 膩 +睪 縞 +睫 捷 +睬 採 +睹 赌 +睽 馗 +睾 糕 +睿 蕊 +瞀 楙 +瞄 描 +瞅 愁 +瞇 瀰 +瞋 棽 +瞌 稞 +瞍 嗽 +瞎 虾 +瞑 明 +瞒瞞 馒 +瞟 縹 +瞠 秤 +瞢 艨 +瞥 撆 +瞧 樵 +瞩矚 煮 +瞪 镫 +瞬 舜 +瞭 缭 +瞰 阚 +瞳 潼 +瞵 辚 +瞻 詹 +瞽 臌 +瞿 癯 +矇 瞢 +矍 钁 +矓 曨 +矗 畜 +矛 牦 +矜 衿 +矢 蝨 +矣 椅 +知 蜘 +矧 諗 +矩 咀 +矫矯 搅 +矬 蹉 +短 端 +矮 蔼 +石 炻 +矶磯 嘰 +矸 酐 +矽 嘻 +矾礬 烦 +矿礦 邝 +砀碭 盪 +码碼 玛 +砂 沙 +砉 花 +砌 器 +砍 侃 +砑 軋 +砒 批 +研 妍 +砖磚 颛 +砗硨 车 +砘 盾 +砚硯 厌 +砜 風 +砝 发 +砟 眨 +砠 苴 +砣 驮 +砥 诋 +砦 窄 +砧 针 +砩 紼 +砬 蠟 +砭 边 +砰 烹 +砲 萢 +破 魄 +砷 紳 +砸 匝 +砹 礙 +砺礪 勵 +砻礱 瓏 +砼 峒 +砾礫 历 +础礎 楮 +硃 洙 +硅 闺 +硇 鐃 +硌 各 +硎 荥 +硐 凍 +硒 牺 +硕碩 朔 +硖硤 峽 +硗磽 蹺 +硝 逍 +硪 臥 +硫 留 +硬 映 +硭 邙 +确確 榷 +硷 剪 +硼 弸 +硿 空 +碇 錠 +碉 雕 +碌 录 +碍礙 艾 +碎 遂 +碑 悲 +碓 憝 +碗 婉 +碘 点 +碚 鋇 +碛磧 葺 +碜磣 襯 +碟 谍 +碡 肘 +碣 楬 +碥 褊 +碧 壁 +碰 彭 +碱鹼 茧 +碲 禘 +碳 探 +碴 槎 +碹 泫 +碾 撵 +磁 瓷 +磅 镑 +磉 縔 +磊 垒 +磋 撮 +磐 蹒 +磔 轍 +磕 科 +磙 鲧 +磨 摩 +磬 罄 +磲 佢 +磴 鄧 +磷 鱗 +磺 惶 +礁 鹪 +礅 蹲 +礓 豇 +礞 曚 +礤 擦 +礴 薄 +示 誓 +礻 事 +礼禮 澧 +社 涉 +祀 駟 +祁 祈 +祆 暹 +祇 鳍 +祈 祁 +祉 沚 +祐 蚰 +祓 紱 +祕 糸 +祖 俎 +祗 胝 +祚 做 +祛 曲 +祜 怙 +祝 铸 +神 申 +祟 隧 +祠 辞 +祢禰 拟 +祥 翔 +祧 窕 +票 骠 +祭 际 +祯禎 桢 +祷禱 导 +祸禍 豁 +祺 萁 +禀稟 饼 +禁 靳 +禄祿 赂 +禅禪 蟾 +禊 戏 +福 蝠 +禚 諑 +禦 鷸 +禧 洗 +禳 蘘 +禹 语 +禺 嵎 +离離 璃 +禽 噙 +禾 河 +秀 绣 +私 斯 +秃禿 凸 +秆稈 赶 +秉 昺 +秋 鳅 +种種 踵 +科 颗 +秒 淼 +秕 沘 +秘 泌 +租 祖 +秣 妺 +秤 称 +秦 芩 +秧 泱 +秩 掷 +秫 贖 +秭 漬 +积積 矶 +称稱 蛏 +秸 皆 +移 仪 +秽穢 慧 +稀 唏 +稂 螂 +稃 鄜 +稆穭 鋁 +程 裎 +稍 捎 +税稅 水 +稔 忍 +稗 败 +稚 雉 +稞 窠 +稠 綢 +稣穌 窣 +稳穩 吻 +稷 觊 +稹 縝 +稻 鱽 +稼 傢 +稽 圾 +稿 槁 +穀 賈 +穆 木 +穋 辂 +穑穡 色 +穗 邃 +穠 儂 +穫 或 +穰 瀼 +穴 薛 +究 鸠 +穷窮 琼 +穸 硒 +穹 茕 +空 箜 +穿 传 +窀 谆 +突 秃 +窃竊 妾 +窄 摘 +窆 碥 +窈 杳 +窍竅 俏 +窑窯 尧 +窒 蛭 +窕 挑 +窖 教 +窗 窓 +窘 迥 +窜竄 篡 +窝窩 蜗 +窟 骷 +窠 蝌 +窥窺 亏 +窦竇 荳 +窨 印 +窬 欤 +窭窶 屨 +窳 圄 +窿 龙 +立 粒 +竖豎 恕 +站 绽 +竞競 径 +竟 境 +章 漳 +竣 骏 +童 瞳 +竦 悚 +竭 羯 +端 缎 +竹 烛 +竺 竹 +竽 于 +竿 杆 +笃篤 堵 +笄 緝 +笆 粑 +笈 级 +笊 曌 +笋筍 榫 +笏 祜 +笑 咲 +笔筆 鄙 +笕筧 瞼 +笙 昇 +笛 狄 +笞 吃 +笠 立 +笤 条 +笥 覗 +符 伏 +笨 奔 +笪 韃 +笫 子 +第 谛 +笮 则 +笱 詬 +笳 浹 +笸 叵 +笺箋 蒹 +笼籠 胧 +笾籩 鳊 +筅 冼 +筇 瓊 +等 邓 +筋 斤 +筌 銓 +筏 閥 +筐 诓 +筑 住 +筒 茼 +答 鞑 +策 册 +筘 釦 +筚篳 蹕 +筛篩 酾 +筝箏 钲 +筠 鋆 +筢 鈀 +筮 鈰 +筱 篠 +筲 弰 +筵 檐 +筷 快 +筹籌 畴 +筻 槓 +签籤 钎 +简簡 柬 +箄 拍 +箅 愎 +箇 虼 +箍 轱 +箐 庆 +箔 帛 +箕 稽 +算 蒜 +箜 悾 +箝 鈐 +箠 錘 +管 莞 +箢 鵷 +箦簀 舴 +箧篋 竊 +箨籜 唾 +箩籮 逻 +箪簞 鄲 +箫簫 嚣 +箬 蒻 +箭 建 +箱 襄 +箴 鍼 +箸 貯 +篁 遑 +範 犯 +篆 赚 +篇 偏 +築 苧 +篌 瘊 +篑簣 喟 +篓簍 搂 +篙 高 +篚 悱 +篛 弱 +篝 沟 +篠 小 +篡 爨 +篥 溧 +篦 箅 +篪 踟 +篮籃 婪 +篱籬 漓 +篷 棚 +篼 蔸 +篾 咩 +簇 蔟 +簋 詭 +簌 嗉 +簏 轆 +簑 縮 +簖籪 断 +簟 钿 +簦 燈 +簧 磺 +簪 糌 +簸 跛 +簽 慳 +簿 部 +籀 晝 +籁籟 睐 +籍 辑 +籐 腾 +籣 瀾 +籥 钺 +米 靡 +籴糴 敌 +类類 擂 +籼秈 跹 +籽 滓 +粉 纷 +粑 捌 +粒 笠 +粕 破 +粗 蹴 +粘 毡 +粜糶 跳 +粝糲 蠣 +粞 恓 +粟 僳 +粢 輜 +粤粵 岳 +粥 诌 +粪糞 份 +粮糧 梁 +粱 樑 +粲 参 +粳 兢 +粹 萃 +粼 嶙 +粽 纵 +精 菁 +糁糝 伞 +糅 柔 +糇餱 翭 +糈 湑 +糊 蝴 +糌 咱 +糍餈 鹚 +糕 羔 +糖 搪 +糗 求 +糙 漕 +糜 醚 +糟 凿 +糠 康 +糢 嫫 +糨 酱 +糯 挪 +糰 團 +糸 覓 +系 奚 +紊 稳 +素 塑 +索 唢 +紧緊 槿 +紫 姊 +紮 杂 +累 磊 +絃 銜 +絮 续 +絰 咥 +絷縶 执 +綑 阃 +続 序 +綞 缒 +綦 其 +綮 顷 +綵 菜 +緻 豸 +縯 兗 +縴 槧 +縻 彌 +縿 摻 +繁 燔 +繇 餚 +繈 鏹 +繙 帆 +繫 禊 +纂 纘 +纔 綵 +纖 籼 +纛 盗 +纟 私 +纠糾 揪 +纡紆 瘀 +红紅 虹 +纣紂 胄 +纤 先 +纥紇 齕 +约約 曰 +级級 汲 +纨紈 頑 +纩纊 礦 +纪紀 蓟 +纫紉 仞 +纬緯 苇 +纭紜 云 +纯純 醇 +纰紕 屁 +纱紗 鲨 +纲綱 肛 +纳納 钠 +纵縱 粽 +纶綸 轮 +纷紛 芬 +纸紙 咫 +纹紋 蚊 +纺紡 访 +纽紐 忸 +纾紓 枢 +线線 岘 +绀紺 赣 +绁紲 瀣 +绂紱 黻 +练練 楝 +组組 阻 +绅紳 莘 +细細 隙 +织織 栀 +终終 衷 +绉縐 皺 +绊絆 半 +绋紼 怫 +绌絀 黜 +绍紹 邵 +绎繹 驿 +经經 荆 +绐紿 詒 +绑綁 邦 +绒絨 容 +结結 詰 +绔 喾 +绕繞 饶 +绗絎 迒 +绘繪 燴 +给給 戟 +绚絢 炫 +绛絳 洚 +络絡 洛 +绝絕 爵 +绞絞 佼 +统統 筒 +绠綆 骾 +绡綃 魈 +绢絹 狷 +绣繡 锈 +绥綏 随 +绦絛 饕 +继繼 継 +绨綈 题 +绩績 蹟 +绪緒 蓄 +绫綾 鲮 +续續 続 +绮綺 岂 +绯緋 鲱 +绰綽 啜 +绱鞝 上 +绲緄 滚 +绳繩 澠 +维維 唯 +绵綿 棉 +绶綬 壽 +绷繃 嘣 +绸綢 惆 +绺綹 柳 +绻綣 券 +综綜 踪 +绽綻 占 +绾綰 脘 +绿綠 氯 +缀綴 赘 +缁緇 辎 +缂緙 氪 +缃緗 廂 +缄緘 箋 +缅緬 渑 +缆纜 榄 +缇緹 鯷 +缈緲 藐 +缉緝 激 +缋繢 闠 +缌緦 锶 +缍 亸 +缎緞 锻 +缏緶 遍 +缑緱 佝 +缒縋 惴 +缓緩 环 +缔締 諦 +缕縷 屢 +编編 蝙 +缗緡 珉 +缘緣 源 +缙縉 搢 +缚縛 賻 +缛縟 蓐 +缜縝 轸 +缝縫 冯 +缟縞 藁 +缠纏 馋 +缡縭 褵 +缢縊 鎰 +缣縑 鹣 +缤繽 彬 +缥縹 嫖 +缦縵 鏝 +缧縲 嫘 +缨纓 鹦 +缩縮 梭 +缪繆 謀 +缫繅 臊 +缬纈 挾 +缭繚 寮 +缮繕 善 +缯繒 憎 +缰韁 江 +缱繾 浅 +缲繰 巧 +缳繯 圜 +缴繳 矫 +缵纘 躜 +缶 殕 +缸 钢 +缺 炔 +罂罌 纓 +罄 慶 +罅 嚇 +罈 譚 +罐 盥 +网網 罔 +罔 往 +罕 汗 +罗羅 萝 +罘 凫 +罚罰 乏 +罟 牯 +罡 岡 +罢罷 坝 +罨 儼 +罩 棹 +罪 酔 +置 峙 +罱 纜 +署 曙 +罴羆 蜱 +罹 喱 +罾 缯 +羁羈 譏 +羊 佯 +羌 枪 +美 渼 +羔 睪 +羚 苓 +羝 隄 +羞 咻 +羟羥 抢 +羡羨 现 +群 裙 +羧 嗍 +羯 碣 +羰 蹚 +羲 犀 +羸 罍 +羹 畊 +羼 顫 +羽 雨 +羿 佚 +翁 嗡 +翅 斥 +翊 呓 +翌 翊 +翎 蛉 +翔 详 +翕 兮 +翘翹 撬 +翟 债 +翠 粹 +翡 榧 +翥 箸 +翦 揃 +翩 篇 +翮 和 +翰 菡 +翱 遨 +翳 异 +翻 旛 +翼 翌 +耀 鹞 +老 佬 +考 烤 +耄 瑁 +者 赭 +耆 畦 +耋 跌 +而 饵 +耍 刷 +耐 奈 +耑 偳 +耒 誄 +耔 孖 +耕 羹 +耖 吵 +耗 昊 +耘 匀 +耙 爬 +耜 戺 +耠 攉 +耢 捞 +耥 鏜 +耦 偶 +耧耬 嘍 +耨 鎒 +耩 槳 +耪 乓 +耱 殁 +耳 洱 +耵 釘 +耶 噎 +耷 答 +耸聳 竦 +耻恥 豉 +耽 殚 +耿 鲠 +聂聶 蹑 +聃 儋 +聆 鴒 +聊 辽 +聋聾 咙 +职職 植 +聍聹 檸 +聒 堝 +联聯 廉 +聘 牝 +聚 剧 +聩聵 匱 +聪聰 骢 +聱 鰲 +聿 芋 +肀 妪 +肃肅 诉 +肄 益 +肆 祀 +肇 照 +肉 鞣 +肋 类 +肌 姬 +肓 謊 +肖 笑 +肘 帚 +肚 蠹 +肛 扛 +肜 狨 +肝 矸 +肟 齷 +肠腸 常 +股 蛊 +肢 脂 +肤膚 孵 +肥 淝 +肩 尖 +肪 房 +肫 窀 +肭 妠 +肮骯 昂 +肯 啃 +肱 龔 +育 愈 +肴餚 爻 +肷 譴 +肺 杮 +肼 頸 +肽 鈦 +肾腎 慎 +肿腫 冢 +胀脹 帐 +胁脅 斜 +胂 滲 +胃 渭 +胄 冑 +胆膽 疸 +背 蓓 +胍 颳 +胎 台 +胖 庞 +胗 幀 +胙 阼 +胚 醅 +胛 甲 +胜勝 圣 +胝 之 +胞 苞 +胡 瑚 +胤 窨 +胥 噓 +胧朧 嚨 +胨 動 +胩 鉲 +胪臚 蘆 +胫脛 逕 +胬 駑 +胭 醃 +胯 跨 +胰 颐 +胱 广 +胲 頦 +胳 咯 +胴 动 +胶膠 交 +胸 熊 +胺 案 +胼 駢 +能 螚 +脂 汁 +脆 淬 +脉脈 埋 +脊 挤 +脍膾 侩 +脎 薩 +脏 赃 +脐臍 蛴 +脑腦 恼 +脒 羋 +脓膿 浓 +脔臠 攣 +脖 勃 +脘 晼 +脚腳 皎 +脞 剉 +脤 腎 +脩 鵂 +脬 抛 +脯 辅 +脰 餖 +脱脫 驼 +脲 嬲 +脶腡 騾 +脸臉 敛 +脾 郫 +腆 忝 +腈 鼱 +腊臘 蜡 +腋 液 +腌醃 阉 +腐 府 +腑 袱 +腓 肥 +腔 羌 +腕 碗 +腙 蹤 +腚 订 +腠 辏 +腥 星 +腧 藷 +腩 湳 +腭齶 鍔 +腮 鰓 +腰 邀 +腱 濺 +腴 臾 +腹 蝮 +腺 线 +腻膩 溺 +腼靦 緬 +腽膃 襪 +腾騰 滕 +腿 褪 +膀 绑 +膂 縷 +膈 嗝 +膊 博 +膏 篙 +膑臏 殡 +膘 飙 +膛 樘 +膜 模 +膝 吸 +膣 彘 +膦 躏 +膨 篷 +膪 嘬 +膳 缮 +膺 鷹 +膻羶 苫 +臀 豚 +臁 濂 +臂 币 +臃 邕 +臆 逸 +臊 瘙 +臌 穀 +臟 蔵 +臢 拶 +臣 尘 +臧 牂 +自 恣 +臬 鎳 +臭 抽 +至 挚 +致 帜 +臺 薹 +臻 珍 +臼 疚 +臾 谀 +舀 咬 +舁 狳 +舂 崇 +舄 潟 +舅 旧 +舆輿 娱 +舌 佘 +舍 摄 +舐 适 +舒 抒 +舔 腆 +舛 川 +舜 吮 +舞 鹉 +舟 州 +舡 串 +舢 羶 +舣艤 迤 +舨 鈑 +航 杭 +舫 仿 +般 瘢 +舭 吡 +舯 鐘 +舰艦 剑 +舱艙 苍 +舳 逐 +舴 咋 +舵 堕 +舶 泊 +舷 衔 +舸 哿 +船 舡 +舻艫 顱 +舾 蟋 +艄 筲 +艇 铤 +艉 葦 +艋 錳 +艏 手 +艘 嗖 +艚 螬 +艟 罿 +艨 濛 +艮 亘 +良 粱 +艰艱 笺 +色 瑟 +艳 验 +艴 绋 +艷 釅 +艹 草 +艺藝 意 +艽 姣 +艾 隘 +艿 迺 +节節 洁 +芄 紈 +芈羋 敉 +芊 籤 +芋 煜 +芍 杓 +芎 洶 +芏 督 +芑 豈 +芒 氓 +芗薌 乡 +芘 疲 +芙 服 +芜蕪 吴 +芝 织 +芟 膻 +芡 塹 +芣 枹 +芤 口 +芥 戒 +芦蘆 鲈 +芨 羁 +芩 檎 +芪 祇 +芫 簷 +芬 氛 +芭 八 +芮 瑞 +芯 辛 +芰 记 +花 华 +芳 邡 +芴 骛 +芷 纸 +芸 紜 +芹 秦 +芽 蚜 +芾 痱 +苁蓯 樅 +苄 辮 +苇葦 炜 +苈藶 疬 +苊 轭 +苋莧 限 +苌萇 长 +苍蒼 沧 +苎苧 佇 +苏 酥 +苑 怨 +苒 染 +苓 囹 +苔 跆 +苕 调 +苗 瞄 +苘 请 +苛 磕 +苜 钼 +苞 孢 +苟 枸 +苠 緡 +苡 舣 +苣 鉅 +苤 撇 +若 箬 +苦 窟 +苫 舢 +苯 畚 +英 瑛 +苴 罝 +苷 玕 +苹蘋 枰 +苻 罘 +茁 濯 +茂 贸 +范 畈 +茄 伽 +茅 矛 +茆 泖 +茇 犮 +茈 赀 +茉 秣 +茌 持 +茎莖 泾 +茏蘢 矓 +茑蔦 嬝 +茔塋 縈 +茕煢 邛 +茗 名 +茚 廕 +茛 跟 +茜 縴 +茧繭 简 +茨 慈 +茫 杧 +茬 查 +茭 郊 +茯 輻 +茱 铢 +茳 殭 +茴 迴 +茵 阴 +茶 搽 +茸 荣 +茹 襦 +茺 艟 +茼 烔 +荀 洵 +荃 铨 +荆荊 茎 +荇 性 +草 艸 +荏 稔 +荐薦 澗 +荑 緹 +荒 谎 +荔 砾 +荚莢 颊 +荛蕘 扰 +荜蓽 必 +荞蕎 乔 +荟薈 贿 +荠薺 霽 +荡蕩 砀 +荣榮 绒 +荤葷 昏 +荥滎 饧 +荦犖 泺 +荧熒 萦 +荨蕁 寻 +荩藎 贐 +荪蓀 飧 +荫蔭 胤 +荬蕒 买 +荭葒 红 +荮 酎 +药藥 耀 +荷 閡 +荸 痹 +荻 鏑 +荼 禿 +荽 濉 +莅蒞 丽 +莆 菩 +莉 栗 +莎 鯊 +莒 踽 +莓 湄 +莘 深 +莛 鋌 +莜 猶 +莞 馆 +莠 羑 +莨 浪 +莩 郛 +莪 鵝 +莫 寞 +莰 龕 +莱萊 徕 +莲蓮 涟 +莳蒔 塒 +莴萵 窝 +莶薟 憸 +获獲 藿 +莸蕕 鈾 +莹瑩 熒 +莺鶯 英 +莼蓴 脣 +莽 蟒 +菀 綰 +菁 腈 +菅 艱 +菇 估 +菊 桔 +菌 君 +菏 盒 +菔 鵩 +菖 鯧 +菘 鬆 +菜 蔡 +菝 茇 +菟 堍 +菠 啵 +菡 颔 +菥 樨 +菩 蒲 +菪 蕩 +菰 蛄 +菱 绫 +菲 啡 +菴 鵪 +菸 崦 +菹 租 +菽 紓 +萁 麒 +萃 脆 +萄 淘 +萆 跸 +萋 淒 +萌 檬 +萍 鲆 +萎 娓 +萏 啗 +萑 鐶 +萘 柰 +萜 貼 +萝蘿 箩 +萤螢 瑩 +营營 莹 +萦縈 螢 +萧蕭 箫 +萨薩 卅 +萱 煊 +萸 歟 +萼 谔 +落 骆 +葆 保 +葑 灃 +著 筑 +葙 緗 +葚 椹 +葛 阁 +葜 掐 +葡 莆 +董 东 +葩 筢 +葫 鬍 +葬 塟 +葭 浃 +葱蔥 苁 +葳 逶 +葵 睽 +葶 渟 +葸 璽 +葺 槭 +蒂 帝 +蒇蕆 諂 +蒈 锴 +蒉蕢 饋 +蒋蔣 奖 +蒌蔞 耧 +蒎 哌 +蒐 鎪 +蒗 閬 +蒙 朦 +蒜 痠 +蒡 蚌 +蒯 膾 +蒲 璞 +蒴 爍 +蒸 狰 +蒹 搛 +蒺 佶 +蒽 搇 +蒿 薅 +蓁 榛 +蓄 煦 +蓆 隰 +蓉 鎔 +蓊 滃 +蓍 溮 +蓐 鄏 +蓑 挲 +蓓 悖 +蓖 篦 +蓝藍 篮 +蓟薊 剂 +蓠蘺 灕 +蓣蕷 阈 +蓥鎣 塋 +蓦驀 瘼 +蓬 鵬 +蓰 銑 +蓼 暸 +蓿 卹 +蔆 鯪 +蔌 谡 +蔑 篾 +蔓 缦 +蔔 砵 +蔗 柘 +蔚 畏 +蔟 踧 +蔡 采 +蔫 拈 +蔬 舒 +蔷薔 嫱 +蔸 斗 +蔹蘞 琏 +蔺藺 吝 +蔻 抠 +蔼藹 霭 +蔽 斃 +蕃 璠 +蕈 遜 +蕉 澆 +蕊 蕤 +蕖 磲 +蕙 彙 +蕞 槜 +蕤 锐 +蕨 珏 +蕲蘄 旂 +蕴蘊 酝 +蕹 甕 +蕺 戢 +蕻 鬨 +蕾 耒 +薄 雹 +薅 蒿 +薇 偎 +薏 懿 +薑 彊 +薛 靴 +薜 潷 +薤 絏 +薨 轟 +薪 欣 +薮藪 嗾 +薯 暑 +薰 醺 +薷 颥 +薹 檯 +藁 鎬 +藉 玠 +藏 鸧 +藐 邈 +藓蘚 险 +藕 殴 +藜 骊 +藤 誊 +藩 番 +藷 糬 +藻 早 +藿 祸 +蘅 横 +蘇 俗 +蘑 磨 +蘖櫱 蘗 +蘗 聶 +蘧 齲 +蘩 钒 +蘸 战 +蘼 謎 +虍 烀 +虎 唬 +虏虜 卤 +虐 疟 +虑慮 濾 +虔 钱 +虚虛 嘘 +虞 鱼 +虢 幗 +虫蟲 铳 +虬虯 巰 +虮蟣 璣 +虱蝨 溼 +虹 洪 +虺 毁 +虻 甿 +虼 铬 +虽雖 荽 +虾蝦 谺 +虿蠆 瘥 +蚀蝕 湜 +蚁蟻 艤 +蚂螞 码 +蚊 闻 +蚋 枘 +蚌 棒 +蚍 貔 +蚓 飮 +蚕蠶 慚 +蚜 牙 +蚝蠔 濠 +蚣 公 +蚤 棗 +蚧 届 +蚨 麩 +蚩 螭 +蚪 陡 +蚬蜆 显 +蚯 丘 +蚰 疣 +蚱 咤 +蚴 囿 +蚵 貉 +蚶 鼾 +蚺 然 +蛀 炷 +蛄 鴣 +蛆 趋 +蛇 奢 +蛉 姈 +蛊蠱 罟 +蛋 旦 +蛎蠣 癘 +蛏蟶 撑 +蛐 趨 +蛑 鍪 +蛔 回 +蛘 烊 +蛙 窪 +蛛 珠 +蛞 闊 +蛟 茭 +蛤 隔 +蛩 跫 +蛭 輊 +蛮蠻 瞒 +蛰蟄 辄 +蛱蛺 莢 +蛲蟯 撓 +蛳螄 丝 +蛴蠐 芪 +蛸 艄 +蛹 甬 +蛾 鹅 +蜀 黍 +蜂 枫 +蜃 渗 +蜇 嗻 +蜈 蕪 +蜉 桴 +蜊 琍 +蜍 櫥 +蜒 筵 +蜓 亭 +蜕蛻 煺 +蜗蝸 涡 +蜘 梔 +蜚 鯡 +蜜 秘 +蜞 骐 +蜡蠟 瘌 +蜢 锰 +蜣 鎗 +蜥 淅 +蜩 齠 +蜮 彧 +蜱 鼙 +蜴 峄 +蜷 泉 +蜻 鯖 +蜾 槨 +蜿 弯 +蝇蠅 营 +蝈蟈 聒 +蝉蟬 禅 +蝌 瞌 +蝎蠍 楔 +蝓 竽 +蝗 皇 +蝙 煸 +蝠 芙 +蝣 莜 +蝤 璆 +蝥 蟊 +蝮 覆 +蝰 暌 +蝴 煳 +蝶 喋 +蝻 男 +蝼螻 髅 +蝽 春 +蝾蠑 嶸 +螂 狼 +螃 徬 +螅 瘜 +螈 嫄 +螋 廋 +融 嵘 +螓 嗪 +螗 儻 +螟 瞑 +螨 满 +螫 释 +螬 嶆 +螭 摛 +螯 聱 +螳 堂 +螵 慓 +螺 骡 +螽 柊 +蟀 帅 +蟆 蔴 +蟊 貓 +蟋 膝 +蟑 张 +蟒 莽 +蟓 向 +蟛 嘭 +蟠 磻 +蟥 癀 +蟪 穢 +蟮 鄯 +蟹 屑 +蟾 嬋 +蠃 瘰 +蠊 鐮 +蠓 鸏 +蠕 嚅 +蠖 鑊 +蠛 衊 +蠡 鋰 +蠢 唇 +蠲 鵑 +蠹 鍍 +蠼 劬 +血 谑 +衄 朒 +衅釁 信 +行 邢 +衍 俨 +衔銜 弦 +街 揭 +衙 崖 +衝 憧 +衡 桁 +衢 蕖 +衣 依 +衤 禕 +补補 卜 +表 裱 +衩 詫 +衫 煽 +衬襯 谶 +衮袞 棍 +衰 甩 +衲 肭 +衷 钟 +衹 紙 +衽 认 +衾 欽 +衿 妗 +袁 猿 +袂 魅 +袄襖 媪 +袅嫋 茑 +袈 跏 +袋 贷 +袍 匏 +袒 毯 +袖 岫 +袜襪 瓦 +袢 盼 +袤 帽 +被 辈 +袭襲 习 +袱 福 +袷 頰 +袼 閣 +裁 财 +裂 猎 +装裝 莊 +裆襠 珰 +裉 掯 +裊 蔦 +裎 呈 +裏 俚 +裒 抔 +裔 诣 +裕 御 +裘 球 +裙 峮 +裟 痧 +裡 娌 +裢褳 鰱 +裣襝 斂 +裤褲 袴 +裥襉 锏 +裨 婢 +裯 椆 +裰 墮 +裱 錶 +裳 嚐 +裴 陪 +裸 螺 +裹 果 +裼 窸 +製 滞 +裾 琚 +褂 挂 +複 馥 +褊 貶 +褐 赫 +褒 煲 +褓 鸨 +褕 嵛 +褙 揹 +褚 储 +褛褸 旅 +褡 瘩 +褥 溽 +褪 退 +褫 恥 +褰 僉 +褴襤 岚 +褶 輒 +褽 蝟 +襁 强 +襄 香 +襞 蓽 +襟 巾 +襦 缛 +襬 掰 +襻 槃 +西 希 +要 曜 +覃 琴 +覆 副 +覜 糶 +见見 荐 +观觀 官 +规規 硅 +觅覓 谧 +视視 示 +觇覘 掺 +览覽 揽 +觉覺 崛 +觊覬 髻 +觋覡 蓆 +觌覿 滌 +觎覦 揄 +觏覯 購 +觐覲 墐 +觑覷 去 +角 狡 +觔 縉 +觖 譎 +觚 鸪 +觜 谘 +觞觴 湯 +解 檞 +觥 蚣 +触觸 矗 +觫 涑 +觯觶 緻 +觳 鹄 +觼 矍 +言 岩 +訇 薨 +訏 圩 +訑 匜 +託 飥 +訢 妡 +註 祝 +証 正 +訾 龇 +詈 曆 +詖 觱 +詨 嘯 +詹 瞻 +詻 顎 +誉譽 遇 +誊謄 螣 +誌 栉 +誓 谥 +誧 晡 +諮 鯔 +謇 蹇 +謦 頃 +譆 囍 +譟 橾 +警 儆 +譬 媲 +讚 瓚 +讠 闫 +计計 既 +订訂 碇 +讣訃 縛 +认認 妊 +讥譏 饥 +讦訐 劫 +讧訌 蕻 +讨討 涛 +让讓 穰 +讪訕 疝 +讫訖 憩 +训訓 逊 +议議 弈 +讯訊 迅 +记記 骥 +讲講 蒋 +讳諱 蕙 +讴謳 甌 +讵詎 苣 +讶訝 亚 +讷訥 疒 +许許 栩 +讹訛 俄 +论論 伦 +讼訟 诵 +讽諷 丰 +设設 慑 +访訪 舫 +诀訣 抉 +证證 郑 +诂詁 蠱 +诃訶 嗬 +评評 苹 +诅詛 组 +识識 蚀 +诈詐 栅 +诉訴 溯 +诊診 枕 +诋詆 抵 +诌謅 洲 +词詞 祠 +诎詘 軀 +诏詔 肇 +译譯 绎 +诒詒 眙 +诓誆 哐 +诔誄 壘 +试試 拭 +诖詿 刮 +诗詩 失 +诘詰 拮 +诙詼 灰 +诚誠 盛 +诛誅 诸 +诜詵 侁 +话話 化 +诞誕 啖 +诟詬 媾 +诠詮 筌 +诡詭 癸 +询詢 旬 +诣詣 谊 +诤諍 掙 +该該 垓 +详詳 祥 +诧詫 姹 +诨諢 渾 +诩詡 许 +诫誡 藉 +诬誣 污 +语語 予 +诮誚 翘 +误誤 悟 +诰誥 郜 +诱誘 柚 +诲誨 讳 +诳誑 狂 +说說 烁 +诵誦 怂 +诶誒 欸 +请請 箐 +诸諸 蛛 +诹諏 陬 +诺諾 糯 +读讀 渎 +诼諑 斫 +诽誹 翡 +课課 棵 +诿諉 偽 +谀諛 腴 +谁誰 税 +谂諗 瀋 +调調 笤 +谄諂 产 +谅諒 晾 +谆諄 肫 +谇誶 睟 +谈談 谭 +谊誼 易 +谋謀 眸 +谌諶 蔯 +谍諜 蝶 +谎謊 慌 +谏諫 渐 +谐諧 鞋 +谑謔 雪 +谒謁 叶 +谓謂 胃 +谔諤 鹗 +谕諭 癒 +谖諼 軒 +谗讒 缠 +谘 茲 +谙諳 安 +谚諺 焰 +谛諦 棣 +谜謎 弥 +谝諞 骗 +谟謨 饃 +谠讜 党 +谡謖 簌 +谢謝 榭 +谣謠 姚 +谤謗 蒡 +谥諡 謚 +谦謙 迁 +谧謐 密 +谨謹 堇 +谩謾 慢 +谪謫 摺 +谫譾 繭 +谬謬 繆 +谭譚 昙 +谮譖 怎 +谯譙 喬 +谰讕 斕 +谱譜 圃 +谲譎 玦 +谳讞 豔 +谴譴 缱 +谵譫 氈 +谶讖 趁 +谷 古 +谿 鼷 +豁 穫 +豆 痘 +豇 韁 +豉 尺 +豌 湾 +豔 灩 +豕 始 +豚 吞 +象 项 +豢 幻 +豪 壕 +豫 郁 +豭 鎵 +豳 瀕 +豸 炙 +豹 抱 +豺 虿 +貂 彫 +貅 鸺 +貉 涸 +貊 镆 +貌 冒 +貍 釐 +貔 芘 +貘 驀 +賸 勝 +贝貝 狈 +贞貞 偵 +负負 付 +贡貢 共 +财財 纔 +责責 嘖 +贤賢 闲 +败敗 拜 +账賬 瘴 +货貨 获 +质質 致 +贩販 饭 +贪貪 摊 +贫貧 颦 +贬貶 扁 +购購 彀 +贮貯 苎 +贯貫 惯 +贰貳 耳 +贱賤 饯 +贲賁 犇 +贳貰 諡 +贴貼 帖 +贵貴 桂 +贶貺 壙 +贷貸 怠 +贸貿 耄 +费費 狒 +贺賀 鹤 +贻貽 饴 +贼賊 蠈 +贽贄 鷙 +贾賈 胛 +贿賄 汇 +赀貲 髭 +赁賃 蔺 +赂賂 路 +赃贓 臧 +资資 姿 +赅賅 该 +赆贐 噤 +赇賕 犰 +赈賑 鸩 +赉賚 睞 +赊賒 畲 +赋賦 傅 +赌賭 笃 +赍齎 跻 +赎贖 孰 +赏賞 晌 +赐賜 刺 +赓賡 耕 +赔賠 培 +赕賧 胆 +赖賴 籁 +赘贅 坠 +赙賻 訃 +赚賺 撰 +赛賽 鳃 +赜賾 幘 +赝贗 艷 +赞贊 瓒 +赠贈 甑 +赡贍 汕 +赢贏 盈 +赣贛 淦 +赤 炽 +赦 懾 +赧 蝻 +赫 贺 +赭 鍺 +走 奏 +赳 鳩 +赴 讣 +赵趙 兆 +赶趕 擀 +起 启 +趁 衬 +趄 鍥 +超 焯 +越 跃 +趋趨 驱 +趑 锱 +趔 捩 +趟 烫 +趣 觑 +趱趲 赞 +足 族 +趴 葩 +趵 鮑 +趸躉 盹 +趺 肤 +趼 戬 +趾 止 +趿 遢 +跃躍 月 +跄蹌 炝 +跆 骀 +跋 魃 +跌 碟 +跎 鴕 +跏 葭 +跑 庖 +跖蹠 躑 +跗 鮒 +跚 刪 +跛 簸 +距 拒 +跞躒 栎 +跟 根 +跣 蜆 +跤 蛟 +跦 櫧 +跨 挎 +跪 贵 +跫 穷 +跬 傀 +路 鹭 +跳 眺 +践踐 涧 +跷蹺 悄 +跸蹕 滗 +跹躚 氙 +跺 柁 +跻躋 赍 +跼 侷 +跽 忌 +踅 泶 +踉 靓 +踊踴 俑 +踌躊 筹 +踏 沓 +踔 綽 +踝 怀 +踞 锯 +踟 茌 +踡 惓 +踢 剔 +踣 鉑 +踩 彩 +踪蹤 宗 +踫 捧 +踬躓 鑕 +踮 典 +踯躑 縶 +踱 铎 +踵 腫 +踹 揣 +踺 鑑 +踽 齟 +蹀 鰈 +蹁 胼 +蹂 揉 +蹄 啼 +蹇 鹼 +蹈 搗 +蹉 嵯 +蹊 妻 +蹋 挞 +蹑躡 颞 +蹒蹣 蟠 +蹙 猝 +蹟 繫 +蹦 迸 +蹩 彆 +蹬 登 +蹭 曾 +蹯 礬 +蹰躕 鋤 +蹲 敦 +蹴 醋 +蹶 獗 +蹼 樸 +蹿躥 撺 +躁 造 +躂 荅 +躅 舳 +躇 蹰 +躏躪 賃 +躐 儠 +躔 谗 +躜躦 钻 +躞 燮 +身 珅 +躬 弓 +躯軀 嶇 +躲 朵 +躺 倘 +軎 猬 +軏 鉞 +輓 绾 +车車 硨 +轧軋 讶 +轨軌 簋 +轩軒 喧 +轫軔 韌 +转轉 啭 +轭軛 饿 +轮輪 沦 +软軟 阮 +轰轟 哄 +轱 咕 +轲軻 颏 +轳轤 瀘 +轴軸 妯 +轵軹 衹 +轶軼 熠 +轷 垀 +轸軫 畛 +轹轢 櫟 +轺軺 堯 +轻輕 軽 +轼軾 試 +载載 儎 +轾輊 桎 +轿轎 较 +辁輇 鬈 +辂輅 賂 +较較 窖 +辄輒 磔 +辅輔 甫 +辆輛 亮 +辇輦 撚 +辈輩 背 +辉輝 晖 +辊輥 衮 +辋輞 王 +辍輟 惙 +辎輜 錙 +辏輳 湊 +辐輻 匐 +辑輯 急 +输輸 淑 +辔轡 配 +辕轅 塬 +辖轄 暇 +辗輾 搌 +辘轆 漉 +辙轍 谪 +辚轔 璘 +辛 昕 +辜 孤 +辞辭 雌 +辟闢 僻 +辣 镴 +辨 卞 +辩辯 汴 +辫辮 辯 +辰 晨 +辱 儒 +辶 龊 +边邊 鞭 +辽遼 寥 +达達 靼 +迁遷 芊 +迂 纡 +迄 讫 +迅 汛 +迆 以 +过過 濄 +迈邁 麦 +迎 萤 +运運 韵 +近 禁 +迓 砑 +返 贩 +迕 仵 +还還 孩 +这這 浙 +进進 晋 +远遠 沅 +违違 围 +连連 怜 +迟遲 匙 +迢 髫 +迤 蟻 +迥 炯 +迦 痂 +迨 绐 +迩邇 儿 +迪 笛 +迫 粕 +迭 諜 +迮 笮 +述 术 +迳逕 痙 +迴 洄 +迷 谜 +迸 泵 +迹跡 冀 +迺 鼐 +追 锥 +退 蜕 +送 宋 +适 噬 +逃 桃 +逄 龐 +逅 吼 +逆 腻 +选選 烜 +逊遜 巽 +逋 餔 +逍 綃 +透 投 +逐 竺 +逑 賕 +递遞 弟 +途 图 +逖 悌 +逗 豆 +通 嗵 +逛 光 +逝 视 +逞 骋 +速 粟 +造 灶 +逡 群 +逢 缝 +逦邐 鯉 +逭 瘓 +逮 带 +逯 琭 +週 啁 +逵 蝰 +逶 隈 +逸 裔 +逻邏 罗 +逼 鼻 +逾 榆 +遁 钝 +遂 燧 +遄 圌 +遇 寓 +遊 蝣 +遍 变 +遏 厄 +遐 辖 +遑 鳇 +遒 蝤 +道 焘 +遗遺 怡 +遘 搆 +遛 霤 +遝 闼 +遢 祂 +遣 谴 +遥遙 瑶 +遨 獒 +適 是 +遭 糟 +遮 折 +遴 轔 +遵 樽 +遽 颶 +避 臂 +邀 吆 +邂 獬 +邃 碎 +邈 妙 +邋 垃 +邑 浥 +邓鄧 凳 +邕 痈 +邗 顸 +邙 忙 +邛 蛩 +邝鄺 曠 +邡 鈁 +邢 刑 +那 衲 +邦 梆 +邪 挟 +邬鄔 鎢 +邮郵 由 +邯 韩 +邰 胎 +邱 楸 +邳 伾 +邴 稟 +邵 韶 +邶 琲 +邸 柢 +邹鄒 驺 +邺鄴 谒 +邻鄰 鳞 +邾 跦 +郁 昱 +郃 盍 +郄 箧 +郅 轾 +郇 潯 +郊 胶 +郎 廊 +郏郟 铗 +郐鄶 獪 +郑鄭 诤 +郓鄆 恽 +郗 琋 +郛 榑 +郜 告 +郝 耗 +郡 浚 +郢 瘿 +郦酈 例 +郧鄖 耘 +部 埔 +郫 啤 +郭 蝈 +郯 曇 +郴 嗔 +郸鄲 丹 +都 兜 +郾 鼴 +鄂 鳄 +鄄 卷 +鄗 皜 +鄘 墉 +鄙 比 +鄞 夤 +鄢 菸 +鄣 傽 +鄯 鳝 +鄱 皤 +鄹 鄒 +酃 棂 +酆 諷 +酉 友 +酊 鼎 +酋 遒 +酌 浊 +配 佩 +酎 纣 +酏 迆 +酐 尷 +酒 韭 +酗 婿 +酚 分 +酝醞 孕 +酞 钛 +酡 沲 +酢 作 +酣 邯 +酤 轂 +酥 稣 +酩 姳 +酪 络 +酬 疇 +酮 童 +酯 祉 +酰 祆 +酱醬 匠 +酲 埕 +酴 塗 +酵 峤 +酶 媒 +酷 裤 +酸 狻 +酹 泪 +酽釅 唁 +酾釃 曬 +酿釀 孃 +醅 珮 +醇 莼 +醉 晬 +醋 蹙 +醌 锟 +醍 媞 +醐 鹕 +醑 詡 +醒 擤 +醚 麋 +醛 詮 +醜 雠 +醢 胲 +醣 镗 +醪 癆 +醭 不 +醮 叫 +醯 蠵 +醱 潑 +醴 锂 +醵 據 +醺 勋 +釆 緶 +采採 踩 +釉 右 +释釋 饰 +里 狸 +重 堹 +野 埜 +量 辆 +金 津 +釜 斧 +釦 筘 +釭 岗 +鈇 呋 +鉋 菢 +鉴 槛 +鉼 屏 +銎 惸 +銮鑾 孿 +銲 扞 +鋈 騖 +錡 埼 +錶 俵 +錾鏨 讚 +鍊 鏈 +鍚 暘 +鍪 某 +鍾 衳 +鎏 镏 +鎔 瑢 +鎗 蹌 +鎚 搥 +鏊 骜 +鏖 凹 +鐘 盅 +鐾 钡 +鑑 鑒 +鑒 谏 +鑤 儤 +鑪 鸬 +鑫 馨 +钅 矜 +钆釓 尬 +钇釔 已 +针針 侦 +钉釘 盯 +钊釗 赵 +钋釙 頗 +钌釕 蓼 +钍釷 吐 +钎 谦 +钏釧 喘 +钐釤 潸 +钒釩 凡 +钓釣 刁 +钔鍆 门 +钕釹 女 +钗釵 差 +钙鈣 盖 +钚 布 +钛鈦 忲 +钜鉅 秬 +钝鈍 沌 +钞鈔 超 +钟 锺 +钠鈉 吶 +钡鋇 贝 +钢鋼 纲 +钣鈑 版 +钤鈐 前 +钥鑰 药 +钦欽 侵 +钧鈞 皲 +钨鎢 嗚 +钩鉤 勾 +钪鈧 囥 +钫鈁 放 +钬鈥 漷 +钭鈄 枓 +钮鈕 扭 +钯鈀 把 +钰鈺 籲 +钱錢 黔 +钲鉦 征 +钳鉗 乾 +钴鈷 詁 +钵缽 拨 +钶鈳 痾 +钷 珀 +钸鈽 咘 +钹鈸 铂 +钺鉞 悅 +钻鑽 攥 +钼鉬 霂 +钽鉭 忐 +钾鉀 岬 +钿鈿 癜 +铀鈾 油 +铁鐵 餮 +铂鉑 駁 +铃鈴 龄 +铄鑠 硕 +铅鉛 牵 +铆鉚 昴 +铈鈰 貰 +铉鉉 衒 +铊鉈 它 +铋鉍 苾 +铌鈮 昵 +铍鈹 罴 +铎鐸 夺 +铐銬 考 +铑銠 荖 +铒鉺 爾 +铕銪 牖 +铖鋮 宬 +铗鋏 蛺 +铘 揶 +铙鐃 蛲 +铛鐺 噹 +铜銅 彤 +铝鋁 侶 +铞 掉 +铟銦 絪 +铠鎧 恺 +铡鍘 闸 +铢銖 誅 +铣銑 徙 +铤鋌 梃 +铥銩 丢 +铧鏵 嘩 +铨銓 踡 +铩鎩 剎 +铪鉿 哈 +铫銚 吊 +铬鉻 硌 +铭銘 冥 +铮錚 箏 +铯銫 嗇 +铰鉸 饺 +铱銥 衣 +铲鏟 阐 +铳銃 宠 +铴鐋 汤 +铵銨 俺 +银銀 垠 +铷銣 如 +铸鑄 註 +铹鐒 痨 +铺鋪 瀑 +铼錸 徠 +铽鋱 特 +链鏈 潋 +铿鏗 吭 +销銷 宵 +锁鎖 瑣 +锂鋰 裏 +锃 增 +锄鋤 躇 +锅鍋 埚 +锆鋯 誥 +锇鋨 额 +锈鏽 嗅 +锉銼 厝 +锊鋝 掠 +锋鋒 蜂 +锌鋅 新 +锍 綹 +锎 开 +锏 硷 +锐銳 芮 +锑銻 提 +锒鋃 稂 +锓鋟 寢 +锔鋦 駒 +锕錒 啊 +锖錆 戕 +锗鍺 褶 +锘 逽 +错錯 措 +锚錨 髦 +锛錛 賁 +锝 德 +锞錁 騍 +锟錕 琨 +锡錫 悉 +锢錮 故 +锣鑼 蘿 +锤錘 棰 +锥錐 椎 +锦錦 卺 +锨 纤 +锩錈 捲 +锪 耠 +锫 赔 +锬錟 郯 +锭錠 腚 +键鍵 毽 +锯鋸 倨 +锰錳 懵 +锱錙 緇 +锲鍥 愜 +锴鍇 剴 +锵鏘 腔 +锶鍶 罳 +锷鍔 諤 +锸鍤 插 +锹鍬 敲 +锺 终 +锻鍛 段 +锼鎪 颼 +锾鍰 洹 +锿 噯 +镀鍍 肚 +镁鎂 美 +镂鏤 陋 +镄鐨 曊 +镅 莓 +镆鏌 歿 +镇鎮 朕 +镉鎘 革 +镊鑷 嗫 +镌鐫 捐 +镍鎳 涅 +镎 拿 +镏鎦 餾 +镐鎬 缟 +镑鎊 谤 +镒鎰 鷁 +镓鎵 家 +镔鑌 繽 +镖鏢 飚 +镗鏜 瑭 +镘鏝 熳 +镙鏍 儸 +镛鏞 傭 +镜鏡 竟 +镝鏑 敵 +镞鏃 崒 +镟鏇 楦 +镡鐔 罈 +镢钁 鱖 +镣鐐 料 +镤鏷 濮 +镥 滷 +镦鐓 燉 +镧鑭 襴 +镨鐠 譜 +镩 躥 +镪鏹 蜣 +镫鐙 磴 +镬鑊 獲 +镭鐳 羸 +镯鐲 茁 +镰鐮 鲢 +镱鐿 弋 +镲 馇 +镳鑣 鏢 +镶鑲 骧 +长長 偿 +閑 絃 +閒 涎 +閤 曷 +闆 舨 +门門 扪 +闩閂 拴 +闪閃 陕 +闫閆 巖 +闭閉 毕 +问問 汶 +闯闖 剏 +闰閏 润 +闱闈 濰 +闲 娴 +闳閎 吰 +间間 兼 +闵閔 泯 +闶閌 鈧 +闷悶 焖 +闸閘 札 +闹鬧 淖 +闺閨 皈 +闻聞 雯 +闼闥 撻 +闽閩 皿 +闾閭 驴 +阀閥 琺 +阁閣 格 +阂閡 劾 +阃閫 悃 +阄鬮 纠 +阅閱 粤 +阆閬 崀 +阈閾 蜮 +阉閹 胭 +阊閶 悵 +阋鬩 係 +阌閿 玟 +阍閽 惛 +阎閻 盐 +阏閼 噩 +阐闡 谄 +阑闌 谰 +阒闃 趣 +阔闊 括 +阕闋 却 +阖闔 颌 +阗闐 填 +阙闕 鵲 +阚闞 崁 +阜 驸 +阝 蝜 +队隊 対 +阡 签 +阢 鶩 +阪 钣 +阬 铿 +阮 朊 +阱 井 +防 肪 +阳陽 扬 +阴陰 殷 +阵陣 震 +阶階 接 +阻 诅 +阼 怍 +阽 坫 +阿 錒 +陀 鸵 +陂 杯 +附 駙 +际際 季 +陆陸 鹿 +陇隴 垄 +陈陳 臣 +陉陘 行 +陋 漏 +陌 默 +降 绛 +限 霰 +陔 荄 +陕陝 山 +陛 闭 +陞 聲 +陟 騭 +陡 抖 +院 媛 +除 滁 +陧隉 臬 +陨隕 殒 +险險 蚬 +陪 沛 +陬 掫 +陲 垂 +陴 毘 +陵 菱 +陶 濤 +陷 馅 +隄 镝 +隅 禺 +隆 窿 +隈 溦 +隋 绥 +隍 湟 +随隨 隋 +隐隱 尹 +隔 膈 +隗 猥 +隘 碍 +隙 系 +障 嶂 +隧 岁 +隰 襲 +隳 诙 +隶隸 力 +隹 追 +隻 枝 +隼 筍 +隽雋 絹 +难難 南 +雀 阙 +雁 砚 +雄 芎 +雅 琊 +集 嫉 +雇僱 顾 +雉 痣 +雊 夠 +雌 词 +雍 镛 +雎 疽 +雏雛 除 +雒 荦 +雕 凋 +雠讎 儔 +雨 宇 +雩 萸 +雪 鳕 +雯 文 +雲 昀 +雳靂 壢 +零 铃 +雷 蕾 +雹 包 +雾霧 晤 +需 虚 +霁霽 鲚 +霄 潇 +霆 婷 +震 振 +霈 轡 +霉黴 嵋 +霍 嚯 +霎 煞 +霏 緋 +霑 旃 +霓 猊 +霖 林 +霜 鹴 +霞 瑕 +霤 蹓 +霪 淫 +霭靄 矮 +霰 县 +露 潞 +霸 壩 +霹 噼 +霾 卖 +青 郬 +靓靚 俩 +靖 静 +静靜 徑 +靛 垫 +非 绯 +靠 铐 +靡 弭 +面 缅 +靥靨 曄 +革 蛤 +靳 燼 +靴 削 +靶 爸 +靼 妲 +鞅 鴦 +鞋 携 +鞍 氨 +鞑韃 噠 +鞒 翹 +鞔 蠻 +鞘 誚 +鞠 掬 +鞣 媃 +鞦 湫 +鞫 娵 +鞭 砭 +鞯韉 艰 +鞲韝 溝 +鞴 被 +韆 櫏 +韦韋 违 +韧韌 饪 +韩韓 晗 +韪韙 痿 +韫韞 蘊 +韬韜 绦 +韭 糾 +音 姻 +韵韻 熨 +韶 勺 +韹 鍠 +須 盱 +頫 拊 +页頁 业 +顶頂 酊 +顷頃 庼 +顸頇 犴 +项項 珦 +顺順 蕣 +须 墟 +顼頊 徐 +顽頑 玩 +顾顧 崮 +顿頓 炖 +颀頎 蕲 +颁頒 搬 +颂頌 讼 +颃頏 夯 +预預 豫 +颅顱 炉 +领領 岭 +颇頗 泼 +颈頸 阱 +颉頡 诘 +颊頰 戛 +颌頜 閤 +颍潁 影 +颏頦 轲 +颐頤 貽 +频頻 嫔 +颓頹 推 +颔頷 銲 +颖穎 颍 +颗顆 柯 +题題 蹄 +颚顎 萼 +颛顓 甎 +颜顏 延 +额額 峨 +颞顳 捏 +颟顢 瞞 +颠顛 滇 +颡顙 磉 +颢顥 灏 +颤顫 忏 +颥 銣 +颦顰 频 +颧顴 全 +颱 炱 +颳 鴰 +颺 煬 +风風 楓 +飑颮 鑣 +飒颯 萨 +飓颶 句 +飕颼 蒐 +飘飄 剽 +飙飆 镳 +飚 标 +飞飛 扉 +食 蝕 +飧 孙 +飨饗 响 +飮 癮 +餍饜 焱 +餐 灿 +餘 畬 +餮 贴 +餵 磑 +餽 憒 +饑 笄 +饔 壅 +饕 韜 +饣 时 +饥飢 叽 +饧餳 硎 +饨飩 臀 +饩餼 阋 +饪飪 衽 +饫飫 鹬 +饬飭 啻 +饭飯 氾 +饮飲 隐 +饯餞 践 +饰飾 恃 +饱飽 褓 +饲飼 似 +饴飴 彝 +饵餌 尔 +饶饒 桡 +饷餉 鲞 +饺餃 绞 +饼餅 秉 +饽餑 缽 +饿餓 遏 +馀 於 +馁餒 娞 +馄餛 魂 +馅餡 苋 +馆館 管 +馇 蹅 +馈饋 匮 +馊餿 飕 +馋饞 婵 +馍饃 嬤 +馏餾 鎏 +馐饈 脩 +馑饉 謹 +馒饅 鳗 +馓 散 +馔饌 賺 +馕 囔 +首 垨 +馗 騤 +馘 虢 +香 镶 +馥 复 +馨 歆 +騵 鼋 +马馬 犸 +驭馭 域 +驮馱 坨 +驯馴 殉 +驰馳 墀 +驱驅 岖 +驳駁 礴 +驴驢 榈 +驵駔 奘 +驶駛 史 +驷駟 姒 +驸駙 鲋 +驹駒 狙 +驺騶 诹 +驻駐 蛀 +驼駝 沱 +驽駑 孥 +驾駕 架 +驿驛 译 +骀駘 抬 +骁驍 囂 +骂罵 祃 +骄驕 椒 +骅驊 譁 +骆駱 雒 +骇駭 嗐 +骈駢 蹁 +骊驪 鲡 +骋騁 逞 +验驗 宴 +骏駿 郡 +骐騏 鯕 +骑騎 琦 +骒騍 緙 +骓騅 錐 +骖驂 餐 +骗騙 片 +骘騭 陟 +骚騷 搔 +骛騖 婺 +骜驁 岙 +骝騮 鎦 +骞騫 愆 +骟騸 訕 +骠驃 嘌 +骡騾 鏍 +骢驄 璁 +骣驏 冁 +骤驟 皱 +骥驥 鲫 +骧驤 缃 +骨 鼓 +骰 透 +骱 蚧 +骶 底 +骷 苦 +骸 駭 +骺 糇 +骼 葛 +髀 睥 +髁 锞 +髂 恰 +髅髏 楼 +髋髖 款 +髌髕 殯 +髑 黷 +髒 贓 +髓 祟 +高 皋 +髟 飑 +髡 錕 +髦 旄 +髫 苕 +髭 齜 +髮 珐 +髯 蚺 +髹 庥 +髻 荠 +鬃 综 +鬆 忪 +鬈 圈 +鬍 楜 +鬏 赳 +鬓鬢 膑 +鬚 嬃 +鬟 鍰 +鬣 躐 +鬥 竇 +鬨 讧 +鬯 倀 +鬱 聿 +鬲 蒞 +鬻 嫗 +鬼 诡 +魁 葵 +魂 浑 +魃 拔 +魄 迫 +魅 妹 +魇魘 演 +魈 瀟 +魉魎 裲 +魍 輞 +魏 謂 +魑 黐 +魔 谟 +鯈 條 +鱼魚 渔 +鱿魷 猷 +鲁魯 橹 +鲂魴 紡 +鲅 罢 +鲆 憑 +鲇 鲶 +鲈鱸 泸 +鲋鮒 苻 +鲍鮑 报 +鲎鱟 候 +鲐鮐 颱 +鲑鮭 珪 +鲒鮚 頡 +鲔鮪 诿 +鲕鮞 鴯 +鲚鱭 薊 +鲛鮫 跤 +鲜鮮 掀 +鲞鯗 想 +鲟鱘 荨 +鲠鯁 梗 +鲡鱺 鹂 +鲢鰱 漣 +鲣鰹 緘 +鲤鯉 哩 +鲥鰣 蒔 +鲦鰷 蜩 +鲧鯀 绲 +鲨鯊 唦 +鲩鯇 喚 +鲫鯽 寂 +鲭鯖 倾 +鲮鯪 淩 +鲰鯫 鄹 +鲱鯡 妃 +鲲鯤 坤 +鲳鯧 伥 +鲴 堌 +鲵鯢 輗 +鲶鯰 卄 +鲷鯛 琱 +鲸鯨 晶 +鲺 鰤 +鲻鯔 缁 +鲼 粉 +鲽鰈 疊 +鳃鰓 塞 +鳄鱷 腭 +鳅鰍 蚯 +鳆鰒 複 +鳇鰉 喤 +鳊 萹 +鳋 騷 +鳌鰲 螯 +鳍鰭 耆 +鳎鰨 塔 +鳏鰥 綸 +鳐鰩 窯 +鳓鰳 泐 +鳔鰾 摽 +鳕鱈 膤 +鳖鱉 莂 +鳗鰻 蛮 +鳘 閩 +鳙 鏞 +鳜鱖 桧 +鳝鱔 繕 +鳞鱗 粼 +鳟鱒 尊 +鳢鱧 逦 +鴃 決 +鴒 櫺 +鶸 篛 +鸟鳥 袅 +鸠鳩 究 +鸡雞 积 +鸢鳶 鸳 +鸣鳴 溟 +鸥鷗 瓯 +鸦鴉 压 +鸨鴇 饱 +鸩鴆 圳 +鸪鴣 鈷 +鸫鶇 崠 +鸬鸕 臚 +鸭鴨 桠 +鸯鴦 央 +鸱鴟 蚩 +鸲鴝 鼩 +鸳鴛 冤 +鸵鴕 砣 +鸶鷥 咝 +鸷鷙 櫛 +鸸鴯 而 +鸹鴰 苽 +鸺鵂 朽 +鸽鴿 疙 +鸾鸞 栾 +鸿鴻 泓 +鹁鵓 浡 +鹂鸝 驪 +鹃鵑 涓 +鹄鵠 壺 +鹅鵝 娥 +鹆鵒 馭 +鹇鷳 嫻 +鹈鵜 稊 +鹉鵡 午 +鹊鵲 阕 +鹋 媌 +鹌鵪 谙 +鹎鵯 北 +鹏鵬 朋 +鹑鶉 纯 +鹕鶘 猢 +鹗鶚 齶 +鹘鶻 囫 +鹚 辭 +鹛 郿 +鹜鶩 戊 +鹞鷂 靿 +鹣鶼 菅 +鹤鶴 褐 +鹦鸚 嘤 +鹧鷓 謫 +鹨鷚 六 +鹩鷯 聊 +鹪鷦 鮫 +鹫鷲 厩 +鹬鷸 諭 +鹭鷺 戮 +鹰鷹 莺 +鹱 頀 +鹳鸛 灌 +鹵 氇 +鹾鹺 銼 +鹿 麓 +麂 畿 +麇 鈞 +麈 主 +麋 迷 +麒 綦 +麓 辘 +麝 舍 +麟 燐 +麦麥 脉 +麪 眄 +麴 驅 +麵 免 +麸麩 夫 +麻 蟆 +麼 嬷 +麽 魔 +麾 暉 +黄黃 簧 +黉黌 鴻 +黍 属 +黎 离 +黏 鲇 +黑 嘿 +黔 潜 +默 墨 +黛 埭 +黜 初 +黝 莠 +黟 猗 +黠 狹 +黢 焌 +黥 情 +黧 罹 +黩黷 犢 +黪黲 穇 +黯 暗 +黹 扺 +黻 祓 +黼 輔 +黾黽 憫 +鼇 驁 +鼋黿 轅 +鼍鼉 馱 +鼎 顶 +鼐 氖 +鼓 股 +鼕 岽 +鼗 讨 +鼙 铍 +鼠 蜀 +鼢 雰 +鼬 蚴 +鼯 牾 +鼷 蹊 +鼹鼴 偃 +鼻 荸 +鼽 虯 +鼾 憨 +齄 挓 +齐齊 脐 +齑齏 躋 +齣 樗 +齿齒 褫 +龀齔 讖 +龃齟 莒 +龄齡 伶 +龅齙 鉋 +龆齠 鲦 +龇齜 貲 +龈齦 银 +龉齬 庾 +龊齪 戳 +龋齲 取 +龌齷 斡 +龙龍 珑 +龚龔 供 +龛龕 戡 +龟龜 规 +龠 鑰 diff --git a/internal/aistudio/model_turns.go b/internal/aistudio/model_turns.go index 98b5be72..a10c7dd4 100644 --- a/internal/aistudio/model_turns.go +++ b/internal/aistudio/model_turns.go @@ -2,6 +2,7 @@ package aistudio import ( "bytes" + "container/list" "crypto/sha256" "encoding/binary" "encoding/hex" @@ -26,18 +27,24 @@ type modelTurnKey struct { digest string } -// modelTurnHistory 按 API key 与对话摘要保存本进程生成的模型轮,客户端回传同一回复时与官网一样带回思考 Part、签名 Part 与轮次令牌 +// modelTurnEntry 是模型回复历史中的一条记录 +type modelTurnEntry struct { + key modelTurnKey + turn modelTurn +} + +// modelTurnHistory 按 API key 与对话摘要保存本进程生成的模型轮,order 从最近使用到最久未用排列,客户端回传同一回复时与官网一样带回思考 Part、签名 Part 与轮次令牌 type modelTurnHistory struct { mu sync.Mutex - entries map[modelTurnKey]modelTurn - order []modelTurnKey + entries map[modelTurnKey]*list.Element + order list.List } func newModelTurnHistory() *modelTurnHistory { - return &modelTurnHistory{entries: make(map[modelTurnKey]modelTurn)} + return &modelTurnHistory{entries: make(map[modelTurnKey]*list.Element)} } -// store 保存接在 tip 所在对话之后生成的模型轮;tip 为模型轮、回复带内联媒体或没有思考、签名与轮次令牌时不保存,超过上限时丢弃最早的一条 +// store 保存接在 tip 所在对话之后生成的模型轮;tip 为模型轮、回复带内联媒体或没有思考、签名与轮次令牌时不保存,达到上限时淘汰最久未用的一条 func (turns *modelTurnHistory) store(apiKey string, tip turnLink, turn modelTurn) { if tip.model || slices.ContainsFunc(turn.parts, func(part Part) bool { return part.InlineData != nil }) || turn.turnToken == "" && !slices.ContainsFunc(turn.parts, func(part Part) bool { return part.Thought || part.ThoughtSignature != "" }) { @@ -46,34 +53,40 @@ func (turns *modelTurnHistory) store(apiKey string, tip turnLink, turn modelTurn key := modelTurnKey{apiKey: apiKey, digest: turnLinkDigest(tip.digest, true, turn.parts)} turns.mu.Lock() defer turns.mu.Unlock() - if _, exists := turns.entries[key]; !exists { - turns.order = append(turns.order, key) + if element, exists := turns.entries[key]; exists { + element.Value = modelTurnEntry{key: key, turn: turn} + turns.order.MoveToFront(element) + return } - turns.entries[key] = turn - if len(turns.order) > modelTurnLimit { - delete(turns.entries, turns.order[0]) - turns.order = turns.order[1:] + if turns.order.Len() >= modelTurnLimit { + oldest := turns.order.Back() + delete(turns.entries, oldest.Value.(modelTurnEntry).key) + turns.order.Remove(oldest) } + turns.entries[key] = turns.order.PushFront(modelTurnEntry{key: key, turn: turn}) } -// restore 把对话中本进程生成过的模型轮换成生成时的 Part,函数调用沿用客户端回传的 ID,返回改写后的对话、最后一个模型轮的轮次令牌与对话最后一组轮次的累积摘要 +// restore 把对话中本进程生成过的模型轮换成生成时的 Part 并刷新其最近使用顺序,函数调用沿用客户端回传的 ID,返回改写后的对话、最后一个模型轮的轮次令牌与对话最后一组轮次的累积摘要 func (turns *modelTurnHistory) restore(apiKey string, contents []Content) ([]Content, string, turnLink) { + links := turnLinks(contents) turns.mu.Lock() defer turns.mu.Unlock() restored := make([]Content, 0, len(contents)) token := "" start := 0 var tip turnLink - for _, link := range turnLinks(contents) { - turn, found := turns.entries[modelTurnKey{apiKey: apiKey, digest: link.digest}] - switch { - case link.model && found: - restored = append(restored, Content{Role: RoleAssistant, Parts: withCallIDs(turn.parts, contents[start:link.end])}) - token = turn.turnToken - case link.model: - restored = append(restored, contents[start:link.end]...) - token = "" - default: + for _, link := range links { + if link.model { + if element, found := turns.entries[modelTurnKey{apiKey: apiKey, digest: link.digest}]; found { + turns.order.MoveToFront(element) + turn := element.Value.(modelTurnEntry).turn + restored = append(restored, Content{Role: RoleAssistant, Parts: withCallIDs(turn.parts, contents[start:link.end])}) + token = turn.turnToken + } else { + restored = append(restored, contents[start:link.end]...) + token = "" + } + } else { restored = append(restored, contents[start:link.end]...) } start, tip = link.end, link diff --git a/internal/aistudio/page_analytics.go b/internal/aistudio/page_analytics.go index 57942668..59fdb501 100644 --- a/internal/aistudio/page_analytics.go +++ b/internal/aistudio/page_analytics.go @@ -22,10 +22,16 @@ const ( tagManagerOrigin = "https://www.googletagmanager.com" // analyticsCollectURL 是 gtag 发出 GA4 命中的地址 analyticsCollectURL = "https://www.google-analytics.com/g/collect" + // analyticsGoogleCollectURL 是同意广告存储且开启 Google Signals 的 gtag 目标发出 GA4 命中的地址 + analyticsGoogleCollectURL = "https://analytics.google.com/g/collect" // analyticsFlushDelay 是 gtag 从攒下第一个非转化事件到把这一批发出的延迟 analyticsFlushDelay = 5 * time.Second - // analyticsConsent 是 Cookie 提示条拒绝后 gtag 命中的同意状态参数 - analyticsConsent = "gcs=G100&gcd=13q3q3l3q5l1&npa=1&dma=0" + // analyticsJoinInterval 是 gtag 经 analytics.google.com 发送命中时再次附带 _gaz=1 的最小间隔 + analyticsJoinInterval = 60 * time.Second + // analyticsConsentDenied 是 Cookie 提示条拒绝后 gtag 命中的同意状态参数 + analyticsConsentDenied = "gcs=G100&gcd=13q3q3l3q5l1&npa=1&dma=0" + // analyticsConsentGranted 是不需要 Cookie 提示条且无本地选择记录时 gtag 命中的同意状态参数 + analyticsConsentGranted = "gcs=G111&gcd=13r3r3l3r5l1&npa=0&dma=0" ) var ( @@ -241,6 +247,8 @@ type analyticsTarget struct { sid int64 seq int last time.Time + // gazAt 是上次经 analytics.google.com 发送命中时附带 _gaz=1 的时刻 + gazAt time.Time queue []analyticsEvent timer *time.Timer // script 是目标的 gtag 脚本地址,cached 表示它取自页面缓存 @@ -263,10 +271,12 @@ type pageAnalytics struct { screen string language string - mu sync.Mutex - start time.Time - closed bool - eea bool + mu sync.Mutex + start time.Time + closed bool + eea bool + // granted 表示 2a.json 返回不需要提示条且账户无本地选择记录,广告与统计存储均为 granted + granted bool // rewritten 是 GTM 改写主机名后的页面地址 rewritten string cid string @@ -299,11 +309,14 @@ func (analytics *pageAnalytics) load(ctx context.Context) { if analytics.container == "" { return } + runtime := analytics.runtime + _, decided := runtime.profile.LocalStorage[cookieBarStorageKey] + granted := !decided && runtime.pageCache.notes(cookieBarConfigURL(runtime.cookieBarLanguage)).ConsentOptional analytics.mu.Lock() analytics.start = time.Now() + analytics.granted = granted analytics.mu.Unlock() pauseContext(ctx, 100*time.Millisecond+rand.N(100*time.Millisecond)) - runtime := analytics.runtime containerCached := runtime.pageCache.notes(analytics.container).Tags != nil if runtime.fetchCached(ctx, analytics.container, subresourceHeaders(analytics.container, "*/*", "script", "")) != nil { return @@ -411,11 +424,12 @@ func (analytics *pageAnalytics) experiments(script *tagScript) string { // eventParams 返回 GTM 为事件附加的页面参数,后接 extra;调用方持有 mu func (analytics *pageAnalytics) eventParams(tag analyticsTag, extra ...string) []string { eea := strconv.FormatBool(analytics.eea) + storage := strconv.FormatBool(analytics.granted) params := []string{"ep.page_locale=default", "ep.is_eea=" + eea} if tag.iseea { params = append(params, "ep.iseea="+eea) } - params = append(params, "ep.ads_storage=false", "ep.analytics_storage=false", "ep.signed_in=true") + params = append(params, "ep.ads_storage="+storage, "ep.analytics_storage="+storage, "ep.signed_in=true") return append(params, extra...) } @@ -561,7 +575,20 @@ func (analytics *pageAnalytics) send(target *analyticsTarget, events []analytics target.hits++ tag := target.tag fired := slices.ContainsFunc(events, func(event analyticsEvent) bool { return event.gtm }) - query := []string{"v=2", "tid=" + tag.id, "gtm=" + target.gtmParam(fired), "_p=" + strconv.FormatInt(analytics.start.UnixMilli(), 10), analyticsConsent} + collectURL, consent, pscdl := analyticsCollectURL, analyticsConsentDenied, "pscdl=denied" + googleEndpoint := analytics.granted && tag.google && !tag.signals + if analytics.granted { + consent, pscdl = analyticsConsentGranted, "pscdl=noapi" + if googleEndpoint { + collectURL = analyticsGoogleCollectURL + } + } + query := []string{"v=2", "tid=" + tag.id, "gtm=" + target.gtmParam(fired), "_p=" + strconv.FormatInt(analytics.start.UnixMilli(), 10)} + if googleEndpoint && (target.gazAt.IsZero() || now.Sub(target.gazAt) >= analyticsJoinInterval) { + query = append(query, "_gaz=1") + target.gazAt = now + } + query = append(query, consent) if tag.euid { query = append(query, "ecid="+strconv.FormatUint(uint64(target.ecid), 10)) } @@ -571,14 +598,17 @@ func (analytics *pageAnalytics) send(target *analyticsTarget, events []analytics if tag.google { query = append(query, "_ng=1") } - query = append(query, "cid="+analytics.cid, "frm=0", "gtm_up=1") + query = append(query, "cid="+analytics.cid, "frm=0") + if !analytics.granted { + query = append(query, "gtm_up=1") + } if tag.redact { query = append(query, "ir=1") } if tag.signals { query = append(query, "ngs=1") } - query = append(query, "pscdl=denied", "rcb="+strconv.Itoa(target.rcb), "sr="+analytics.screen, "ul="+analytics.language) + query = append(query, pscdl, "rcb="+strconv.Itoa(target.rcb), "sr="+analytics.screen, "ul="+analytics.language) if tag.flags > 0 { query = append(query, "gaf="+strconv.Itoa(tag.flags)) } @@ -638,11 +668,11 @@ func (analytics *pageAnalytics) send(target *analyticsTarget, events []analytics headers.Set("Origin", aiStudioOrigin) headers.Set("Sec-Fetch-Dest", "empty") headers.Set("Sec-Fetch-Mode", "no-cors") - headers.Set("Sec-Fetch-Site", fetchSite(analyticsCollectURL)) + headers.Set("Sec-Fetch-Site", fetchSite(collectURL)) headers.Set("Priority", "u=4") headers.Set("Pragma", "no-cache") headers.Set("Cache-Control", "no-cache") - address := analyticsCollectURL + "?" + strings.Join(query, "&") + address := collectURL + "?" + strings.Join(query, "&") fallback := analyticsFallbackURL + "?" + strings.Join(fallbackQuery(query, tag.flags), "&") runtime := analytics.runtime go func() { diff --git a/internal/aistudio/page_auxiliary.go b/internal/aistudio/page_auxiliary.go index ca9a5cf8..e4dd60c9 100644 --- a/internal/aistudio/page_auxiliary.go +++ b/internal/aistudio/page_auxiliary.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "log/slog" "math/rand/v2" "net/http" "os" @@ -149,8 +148,21 @@ func cookieBarConfigURL(language string) string { return cookieBarConfig + "?hl=" + language } +// cookieBarReady 返回本次页面启动的 2a.json 请求结束时关闭的通道 +func (runtime *goWAARuntime) cookieBarReady() chan struct{} { + runtime.cookieBarOnce.Do(func() { runtime.cookieBarDone = make(chan struct{}) }) + return runtime.cookieBarDone +} + // loadPageScripts 在文档子资源载入后按官网页面的时序请求前端主程序随后载入的脚本与配置:预取 api.js、反馈服务脚本与 Cookie 提示条文案(载入后提示条回调载入 GTM),再载入 gapi client 模块,最后经 gapi 读取账户资料并载入头像;失败不影响页面 func (runtime *goWAARuntime) loadPageScripts(ctx context.Context) { + ready := runtime.cookieBarReady() + configStarted := false + defer func() { + if !configStarted { + close(ready) + } + }() start := time.Now() wait := func(offset time.Duration) bool { timer := time.NewTimer(time.Until(start.Add(offset + time.Duration(rand.IntN(40))*time.Millisecond))) @@ -190,9 +202,12 @@ func (runtime *goWAARuntime) loadPageScripts(ctx context.Context) { go func() { _ = runtime.fetchCached(ctx, feedbackScript, subresourceHeaders(feedbackScript, "*/*", "script", "")) }() + configStarted = true go func() { target := cookieBarConfigURL(runtime.cookieBarLanguage) - if runtime.fetchCached(ctx, target, corsHeaders(target)) == nil { + err := runtime.fetchCached(ctx, target, corsHeaders(target)) + close(ready) + if err == nil { runtime.analytics.load(ctx) } }() @@ -381,7 +396,7 @@ type cookieBarRecord struct { UUID string `json:"uuid"` } -// dismissOverlays 在页面启动完成后与 Camoufox 后端一样关闭启动弹层:Google AI 方案账户尚未看过欢迎对话框时点击 Continue,Cookie 提示条尚未记录选择时点击 No thanks;失败不影响页面 +// dismissOverlays 在页面启动完成后与 Camoufox 后端一样关闭启动弹层:Google AI 方案账户尚未看过欢迎对话框时点击 Continue,等本次启动的 2a.json 结束后若需要显示 Cookie 提示条且尚未记录选择则点击 No thanks;失败不影响页面也不写入用户日志 func (runtime *goWAARuntime) dismissOverlays(ctx context.Context) { <-runtime.startupDone tier, _ := decodeBenefitTier(runtime.pageCatalog.Tier) @@ -389,9 +404,10 @@ func (runtime *goWAARuntime) dismissOverlays(ctx context.Context) { body := `[[null,null,null,null,null,null,null,null,null,null,null,1],[["has_seen_g1_welcome_dialog"]]]` runtime.sendPageRPCs(ctx, runtime.headers.Get("x-goog-api-key"), runtime.headers.Get("x-aistudio-visit-id"), runtime.headers.Get("x-goog-ext-519733851-bin"), []pageRPC{{"UpdateUserPreferences", body}}) } - if err := runtime.rejectCookieBar(ctx); err != nil { - slog.Warn("关闭 Cookie 提示条失败", "error", err) + if !closedBefore(ctx, runtime.cookieBarReady()) { + return } + _ = runtime.rejectCookieBar(ctx) } // requestGDPProfile 在权益 benefitTier 满足导航栏条件时读取 Google Developer Program 权益并处理额度入口 @@ -684,12 +700,16 @@ func welcomeSeen(preferences []byte) bool { return value == "1" || value == "true" } -// rejectCookieBar 在账户页面尚未记录 Cookie 提示条选择时发出 CreateAuditRecord 并把拒绝记录写入账户目录,下次载入的页面读到该记录,每个账户一次 +// rejectCookieBar 在账户页面尚未记录 Cookie 提示条选择且当前地区需要显示提示条时发出 CreateAuditRecord 并把拒绝记录写入账户目录,下次载入的页面读到该记录,每个账户一次 func (runtime *goWAARuntime) rejectCookieBar(ctx context.Context) error { if _, ok := runtime.profile.LocalStorage[cookieBarStorageKey]; ok { return nil } - text := runtime.pageCache.notes(cookieBarConfigURL(runtime.cookieBarLanguage)).Consent + notes := runtime.pageCache.notes(cookieBarConfigURL(runtime.cookieBarLanguage)) + if notes.ConsentOptional { + return nil + } + text := notes.Consent key := runtime.pageCache.notes(cookieBarScript).AuditKey if text == "" || key == "" { return errors.New("Cookie 提示条文案或 API key 未载入") @@ -735,6 +755,21 @@ func auditRecordBody(text string, record cookieBarRecord) string { return base64.StdEncoding.EncodeToString(message) } +// cookieBarConfigNotes 解析 2a.json 为缓存条目:required 为 false 时标记当前地区不需要提示条,否则推出提示条正文 +func cookieBarConfigNotes(config []byte) (pageCacheNotes, error) { + var parsed struct { + Required *bool `json:"required"` + } + if err := json.Unmarshal(config, &parsed); err != nil { + return pageCacheNotes{}, errors.New("Cookie 提示条文案无效") + } + if parsed.Required != nil && !*parsed.Required { + return pageCacheNotes{ConsentOptional: true}, nil + } + text, err := cookieBarText(config) + return pageCacheNotes{Consent: text}, err +} + // cookieBarText 按 2a.json 的文案推出提示条正文:站点名替换 [This site],末尾接“了解详情”链接 func cookieBarText(config []byte) (string, error) { var parsed struct { diff --git a/internal/aistudio/page_resources.go b/internal/aistudio/page_resources.go index 9b8297d9..b0e6754d 100644 --- a/internal/aistudio/page_resources.go +++ b/internal/aistudio/page_resources.go @@ -231,7 +231,12 @@ func (document pageDocument) frontendBundle() string { return "" } -// loadDocumentResources 像 Firefox 解析官网文档一样按文档顺序并发请求样式表与脚本,全部完成后返回 +// optionalDocumentResource 判断官网文档子资源在真实 Firefox 中失败时页面是否照常运行:全部样式表与 Cookie 提示条脚本为可选 +func optionalDocumentResource(resource pageResource) bool { + return resource.kind == pageStylesheet || resource.url == cookieBarScript +} + +// loadDocumentResources 像 Firefox 解析官网文档一样按文档顺序并发请求样式表与脚本,全部完成后返回;样式表与 Cookie 提示条脚本失败时不中止页面载入,ctx 取消时照常返回取消 func (runtime *goWAARuntime) loadDocumentResources(ctx context.Context, document pageDocument) error { errs := make([]error, len(document.resources)) var group sync.WaitGroup @@ -246,6 +251,9 @@ func (runtime *goWAARuntime) loadDocumentResources(ctx context.Context, document headers := subresourceHeaders(resource.url, accept, destination, priority) group.Go(func() { if err := runtime.fetchCached(ctx, resource.url, headers); err != nil { + if optionalDocumentResource(resource) && ctx.Err() == nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) { + return + } errs[index] = fmt.Errorf("载入官网页面资源 %s: %w", resource.url, err) } }) @@ -315,7 +323,7 @@ func (runtime *goWAARuntime) fetchCached(ctx context.Context, target string, hea // empty 判断缓存条目没有记下任何正文内容 func (notes pageCacheNotes) empty() bool { - return notes.Loader == nil && notes.Starters == nil && notes.Fonts == nil && notes.AuditKey == "" && notes.Consent == "" && notes.Gapi == "" && notes.GapiProxy == "" && notes.Tags == nil + return notes.Loader == nil && notes.Starters == nil && notes.Fonts == nil && notes.AuditKey == "" && notes.Consent == "" && !notes.ConsentOptional && notes.Gapi == "" && notes.GapiProxy == "" && notes.Tags == nil } // noteReader 返回从该资源正文读出缓存内容的函数,不需要读正文的资源返回 nil @@ -344,10 +352,7 @@ func noteReader(address *url.URL) func([]byte) (pageCacheNotes, error) { return pageCacheNotes{AuditKey: string(match[1])}, nil } case strings.HasPrefix(address.String(), cookieBarConfig): - return func(body []byte) (pageCacheNotes, error) { - text, err := cookieBarText(body) - return pageCacheNotes{Consent: text}, err - } + return cookieBarConfigNotes case address.String() == gapiLoaderScript: return func(body []byte) (pageCacheNotes, error) { loader, err := gapiClientURL(body) @@ -461,6 +466,8 @@ type pageCacheNotes struct { AuditKey string `json:"auditKey,omitempty"` // Consent 是 Cookie 提示条按页面语言显示的正文 Consent string `json:"consent,omitempty"` + // ConsentOptional 表示 2a.json 声明当前地区不需要显示 Cookie 提示条(required 为 false) + ConsentOptional bool `json:"consentOptional,omitempty"` // Gapi 是 api.js 加载 gapi client 模块的地址 Gapi string `json:"gapi,omitempty"` // GapiProxy 是 googleapis.proxy.js 载入代理模块时附加的 le 列表 diff --git a/internal/aistudio/quota.go b/internal/aistudio/quota.go index 20b962f7..aa8453e3 100644 --- a/internal/aistudio/quota.go +++ b/internal/aistudio/quota.go @@ -41,8 +41,11 @@ 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 (?:(\d+) hours?)?(?:, )?(?:(\d+) minutes?)?`) +// 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?`) // CooldownState 表示账户或模型暂时不可调度的状态 type CooldownState struct { @@ -165,12 +168,30 @@ func zeroQuotaLimit(message string) bool { // usageLimitReset 返回套餐限额错误写明的恢复等待时长 func usageLimitReset(message string) (time.Duration, bool) { match := usageLimitResetPattern.FindStringSubmatch(message) - if match == nil || match[1] == "" && match[2] == "" { + 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 { return 0, false } - hours, _ := strconv.Atoi(match[1]) - minutes, _ := strconv.Atoi(match[2]) - return time.Duration(hours)*time.Hour + time.Duration(minutes)*time.Minute, true + return total, true } // planLimitCooldown 按同一范围上一次套餐限额冷却计算本次冷却;上一次仍未结束时沿用它 diff --git a/internal/aistudio/reply_tool.go b/internal/aistudio/reply_tool.go new file mode 100644 index 00000000..b7b8dc0e --- /dev/null +++ b/internal/aistudio/reply_tool.go @@ -0,0 +1,106 @@ +package aistudio + +import ( + "context" + "encoding/json" + "slices" + "strings" +) + +// 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`." + +// replyToolParameters 是 final 函数的参数 JSON Schema +var replyToolParameters = json.RawMessage(`{"type":"object","properties":{"content":{"type":"string","description":"The complete reply to the user."}},"required":["content"]}`) + +type replyToolBypassContextKey struct{} + +// ContextWithReplyToolBypassObserver 在开启回复工具但模型直接输出正文时调用 observer +func ContextWithReplyToolBypassObserver(ctx context.Context, observer func()) context.Context { + return context.WithValue(ctx, replyToolBypassContextKey{}, observer) +} + +func reportReplyToolBypassed(ctx context.Context) { + if observer, ok := ctx.Value(replyToolBypassContextKey{}).(func()); ok && observer != nil { + observer() + } +} + +// replyToolEligible 判断本次生成是否启用回复工具:仅限 Playground 通道的文本生成,排除结构化输出、强制或禁止工具调用、非文本模型与同名函数 +func replyToolEligible(request GenerateRequest, entry modelEntry, build bool, assistant bool) bool { + if !request.ReplyTool || build || assistant || entry.defaults.InteractionStream || entry.defaults.InteractionTask { + return false + } + if !entry.model.Capabilities["function_declarations"] { + return false + } + if nonTextGeneration(request, entry) { + return false + } + if len(request.Config.ResponseSchema) > 0 || len(request.Config.ResponseJSONSchema) > 0 { + return false + } + if mime := strings.TrimSpace(request.Config.ResponseMIMEType); mime != "" && !strings.EqualFold(mime, "text/plain") { + return false + } + mode := request.Tools.ToolConfig.Mode + if mode == "required" || mode == "none" || len(request.Tools.ToolConfig.AllowedFunctionNames) > 0 { + return false + } + return !slices.ContainsFunc(request.Tools.Functions, func(declaration FunctionDeclaration) bool { + return declaration.Name == replyToolName + }) +} + +// nonTextGeneration 判断模型或请求配置要求图片、音频、视频、音乐或转录等非文本输出 +func nonTextGeneration(request GenerateRequest, entry modelEntry) bool { + if entry.defaults.ImageRoute || + entry.model.Capabilities["image_route"] || + entry.model.Capabilities["speech_route"] || + entry.model.Capabilities["video_route"] || + entry.model.Capabilities["music_route"] || + entry.model.Capabilities["transcription_output"] { + return true + } + if request.Config.ImageConfig != nil || request.Config.SpeechConfig != nil || request.Config.VideoConfig != nil || request.Config.TranscriptionConfig != nil { + return true + } + return slices.Contains(request.Config.ResponseModalities, ResponseModalityImage) || + slices.Contains(request.Config.ResponseModalities, ResponseModalityAudio) +} + +// applyReplyTool 返回追加了 final 函数声明与固定系统指令的请求副本 +func applyReplyTool(request GenerateRequest) GenerateRequest { + request.Tools.Functions = append(slices.Clip(request.Tools.Functions), FunctionDeclaration{ + Name: replyToolName, + Description: "Deliver the complete reply to the user.", + Parameters: replyToolParameters, + }) + instruction := replyToolInstruction + if len(request.System) > 0 { + instruction = "\n" + instruction + } + request.System = appendSystem(request.System, instruction) + return request +} + +// replyToolText 从 final 函数调用参数中提取正文内容 +func replyToolText(arguments json.RawMessage) (string, bool) { + var payload struct { + Content *string `json:"content"` + } + if err := json.Unmarshal(arguments, &payload); err != nil || payload.Content == nil { + return "", false + } + return *payload.Content, 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 + }) +} diff --git a/internal/aistudio/request_phase.go b/internal/aistudio/request_phase.go index b60b379e..b361cc16 100644 --- a/internal/aistudio/request_phase.go +++ b/internal/aistudio/request_phase.go @@ -18,10 +18,10 @@ type requestPhaseContextKey struct{} type upstreamModeContextKey struct{} -type continuationContextKey struct{} - type serviceRunContextKey struct{} +type regenerationContextKey struct{} + // ContextWithServiceRun 记下生成服务本次运行的上下文,服务停止时它被取消 func ContextWithServiceRun(ctx context.Context, run context.Context) context.Context { return context.WithValue(ctx, serviceRunContextKey{}, run) @@ -45,14 +45,14 @@ func afterServiceStop(ctx context.Context, stop func()) func() bool { return context.AfterFunc(run, stop) } -// ContextWithContinuationObserver 在自动续写开始新一轮时调用 observer -func ContextWithContinuationObserver(ctx context.Context, observer func()) context.Context { - return context.WithValue(ctx, continuationContextKey{}, observer) +// ContextWithRegenerationObserver 在流在完成前中断、流尾为 5xx 或上游异常结束而重新生成之前调用 observer,attempt 从 1 起,reason 为中断错误或结束原因 +func ContextWithRegenerationObserver(ctx context.Context, observer func(attempt int, reason string)) context.Context { + return context.WithValue(ctx, regenerationContextKey{}, observer) } -func reportContinuationRound(ctx context.Context) { - if observer, ok := ctx.Value(continuationContextKey{}).(func()); ok { - observer() +func reportRegeneration(ctx context.Context, attempt int, reason string) { + if observer, ok := ctx.Value(regenerationContextKey{}).(func(int, string)); ok { + observer(attempt, reason) } } diff --git a/internal/aistudio/runtime_go.go b/internal/aistudio/runtime_go.go index d470a2f6..34ff489c 100644 --- a/internal/aistudio/runtime_go.go +++ b/internal/aistudio/runtime_go.go @@ -3,6 +3,7 @@ package aistudio import ( "bytes" "context" + "crypto/sha256" "encoding/base64" "encoding/json" "errors" @@ -49,7 +50,6 @@ type workerRuntime interface { StorageCookies(context.Context) ([]byte, error) // MergeSetCookieHeaders 把账户在页面之外取得的响应 Cookie 写入页面 MergeSetCookieHeaders(context.Context, []string, string) error - State() camoufoxnative.State // Reload 按官网冷启动重新载入页面,返回新页面就绪后使用的 runtime Reload(context.Context) (workerRuntime, error) Close() error @@ -96,8 +96,8 @@ type goWAARuntime struct { previous *goWAARuntime // running 是最近一次点击 Run 或 Rerun 取 proof 的 VM,随后的 GenerateContent 响应开始与结束时在其中派发指针下元素被替换的事件 running *waa.Runtime - // chat 是本页点击后发出的上一个 GenerateContent 的对话轮次,页面还没有对话、点过 New chat 或上一次响应不是 200 时为 nil;与 running 同由 vmMu 保护 - chat []json.RawMessage + // chat 是本页点击后发出的上一个 GenerateContent 各对话轮次的 SHA-256 摘要,页面还没有对话、点过 New chat 或上一次响应不是 200 时为 nil;与 running 同由 vmMu 保护 + chat [][sha256.Size]byte // uiLocale 是官网前端主程序地址声明的界面语言 uiLocale string @@ -129,10 +129,12 @@ type goWAARuntime struct { cookieBarLanguage string // storage 是页面写入、随账户保存的 localStorage 项 storage *pageStorage - // startupDone 在页面启动请求全部返回后关闭;preferencesReady 在其中 GetUserPreferences 返回、preferences 记下响应正文后关闭;tokenReady 在第二个 GenerateAccessToken 返回、accessToken 记下 Drive access token 与取得时刻 tokenAt 后关闭 + // startupDone 在页面启动请求全部返回后关闭;preferencesReady 在其中 GetUserPreferences 返回、preferences 记下响应正文后关闭;tokenReady 在第二个 GenerateAccessToken 返回、accessToken 记下 Drive access token 与取得时刻 tokenAt 后关闭;cookieBarDone 在本次启动的 2a.json 请求结束后关闭 startupDone chan struct{} preferencesReady chan struct{} tokenReady chan struct{} + cookieBarOnce sync.Once + cookieBarDone chan struct{} preferences []byte accessToken string tokenAt time.Time @@ -1002,6 +1004,7 @@ func (runtime *goWAARuntime) createChallenge(ctx context.Context, refresh []stri return waa.Challenge{}, err } started := time.Now() + sentSession := hasSessionCookie(runtime.cookies(), waaCreateURL, started) status := -1 defer func() { runtime.serviceStreamz.record(streamzRecord{metric: "wrl", labels: []any{"c", 1, status, waaRequestKey, streamzMachineKey}, value: float64(time.Since(started).Milliseconds())}) @@ -1018,6 +1021,9 @@ func (runtime *goWAARuntime) createChallenge(ctx context.Context, refresh []stri if response.StatusCode != http.StatusOK { return waa.Challenge{}, fmt.Errorf("Waa/Create 返回 HTTP %d: %s", response.StatusCode, strings.TrimSpace(string(raw))) } + if sentSession && !responseConfirmedSession(response.Header.Values("Set-Cookie")) { + return waa.Challenge{}, fmt.Errorf("%w: Waa/Create 未确认账户会话", camoufoxnative.ErrAuthenticationRequired) + } status = 0 decoded := time.Now() challenge, err := waa.ParseChallenge(raw) @@ -1027,6 +1033,28 @@ func (runtime *goWAARuntime) createChallenge(ctx context.Context, refresh []stri return challenge, err } +// hasSessionCookie 判断状态中包含用于目标地址的 Google 登录会话 Cookie +func hasSessionCookie(state StorageState, targetURL string, now time.Time) bool { + for _, name := range []string{"SID", "__Secure-1PSID", "__Secure-3PSID"} { + if _, ok := state.CookieValue(name, targetURL, now); ok { + return true + } + } + return false +} + +// responseConfirmedSession 判断响应通过 SIDCC 系列 Set-Cookie 确认了账户会话 +func responseConfirmedSession(headers []string) bool { + for _, header := range headers { + for _, cookie := range (&http.Response{Header: http.Header{"Set-Cookie": []string{header}}}).Cookies() { + if rotatingCookieNames[cookie.Name] && cookie.Value != "" && cookie.MaxAge >= 0 { + return true + } + } + } + return false +} + // loadInterpreter 按 challenge 指定的 hash 取得解释器并校验摘要:challenge 不带解释器地址或账户页面缓存中新鲜时沿用同 hash 的已有解释器,否则像页面脚本一样请求(有本地副本时带条件头) func (runtime *goWAARuntime) loadInterpreter(ctx context.Context, challenge waa.Challenge) (string, error) { if challenge.InterpreterJavaScript != "" { @@ -1249,6 +1277,11 @@ func (runtime *goWAARuntime) refreshVM() *vmRefresh { // nextVM 以旧 VM 的无绑定 snapshot 调用 Waa/Create 并返回静置后的新 VM,没有旧 VM 时按首次载入创建 func (runtime *goWAARuntime) nextVM(ctx context.Context, previous *waa.Runtime) (*waa.Runtime, error) { + if runtime.options.RefreshCookies != nil { + if err := runtime.options.RefreshCookies(ctx); err != nil { + return nil, err + } + } var refresh []string if previous != nil { snapshot, err := previous.RefreshSnapshot(ctx) @@ -1309,6 +1342,52 @@ 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{} @@ -1375,7 +1454,7 @@ func (runtime *goWAARuntime) proof(ctx context.Context, digest string, prompt st switch { case run: var newChat func(at time.Time) - if camoufoxnative.StartsNewChat(runtime.chat, contents) { + if startsNewChat(runtime.chat, contents) { newChat = runtime.newChat } proof, err = vm.RunProofAfter(ctx, digest, prompt, newChat, settings, pickedPause) @@ -1454,7 +1533,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 = generateContents(body) + runtime.chat = chatDigests(body) } runtime.vmMu.Unlock() turn = runtime.elements.turn(body, counting) @@ -1654,16 +1733,6 @@ func (runtime *goWAARuntime) MergeSetCookieHeaders(_ context.Context, headers [] return runtime.session.state.MergeSetCookieHeaders(headers, requestURL, time.Now()) } -// State 返回 SpiderMonkey runtime 的页面与协议状态 -func (runtime *goWAARuntime) State() camoufoxnative.State { - return camoufoxnative.State{ - PID: os.Getpid(), - PageURL: runtime.pageURL, - UserAgent: runtime.userAgent, - Headers: runtime.headers.Clone(), - } -} - // Close 结束 VM 生命周期 func (runtime *goWAARuntime) Close() error { runtime.vmMu.Lock() diff --git a/internal/aistudio/runtime_native.go b/internal/aistudio/runtime_native.go index 779d43f1..4ae9374f 100644 --- a/internal/aistudio/runtime_native.go +++ b/internal/aistudio/runtime_native.go @@ -121,8 +121,11 @@ type functionContinuer interface { ContinuesFunctionCall([]byte) bool } +// skipFunctionTabKey 标记请求在函数调用标签页不可用后改走非界面取 proof 路径 +type skipFunctionTabKey struct{} + // generator 返回在页面界面运行该请求的 runtime:Camoufox 后端、未带 proof 的 GenerateContent,最后一个轮次是带文本的 user 轮次,或是回应页面最后一轮函数调用的函数结果 -func (worker *NativeWorker) generator(request ProtectedRequest) (pageGenerator, bool) { +func (worker *NativeWorker) generator(ctx context.Context, request ProtectedRequest) (pageGenerator, bool) { runtime := worker.current() generator, ok := runtime.(pageGenerator) if !ok || request.Proof != "" || !strings.HasSuffix(request.URL, "/GenerateContent") { @@ -131,11 +134,30 @@ func (worker *NativeWorker) generator(request ProtectedRequest) (pageGenerator, if _, typed := camoufoxnative.GeneratePrompt(request.Body); typed { return generator, true } + if ctx.Value(skipFunctionTabKey{}) != nil { + return nil, false + } continuer, ok := runtime.(functionContinuer) _, result := wireFunctionResult(request.Body) return generator, ok && result && continuer.ContinuesFunctionCall(request.Body) } +// missingFunctionTab 判断请求本应在 Camoufox 函数调用标签页由页面取 proof,但该标签页已不可用 +func (worker *NativeWorker) missingFunctionTab(request ProtectedRequest) bool { + if !strings.HasSuffix(request.URL, "/GenerateContent") { + return false + } + runtime := worker.current() + if _, ok := runtime.(pageGenerator); !ok { + return false + } + if _, ok := runtime.(functionContinuer); !ok { + return false + } + _, result := wireFunctionResult(request.Body) + return result +} + // resultSubmitter 是像官网用户一样在函数调用块中粘贴函数结果并点击提交后取 proof 的 workerRuntime type resultSubmitter interface { SubmitProof(ctx context.Context, digest, result string, rounds int) (string, error) @@ -164,7 +186,7 @@ func submitRounds(body []byte) int { // Prepare 生成 fresh proof,请求带 Proof 时沿用该 proof,正文原样返回,发送时在 ProofAt 处写入;在页面界面运行的 GenerateContent 由页面应用取 proof,只返回公共协议头 func (worker *NativeWorker) Prepare(ctx context.Context, request ProtectedRequest) (PreparedProtectedRequest, error) { - if _, ok := worker.generator(request); ok { + if _, ok := worker.generator(ctx, request); ok { headers, err := worker.current().ProtocolHeaders(ctx) if err != nil { return PreparedProtectedRequest{}, err @@ -328,9 +350,12 @@ const pageSubmitCountDelay = 250 * time.Millisecond // Camoufox 后端未带 proof 的 GenerateContent 在页面界面运行,请求头、proof 与随后的 CountTokens 由页面应用产生 // 其余 GenerateContent 发出 pageCountTokensDelay 后由 runtime 以相同请求头统计页面提示词的 token func (worker *NativeWorker) SendProtected(ctx context.Context, request ProtectedRequest) (*RPCResponse, error) { - if generator, ok := worker.generator(request); ok { + if generator, ok := worker.generator(ctx, request); ok { return worker.generate(ctx, generator, request) } + if request.Proof == "" && worker.missingFunctionTab(request) { + return nil, camoufoxnative.ErrFunctionTabUnavailable + } if body, delay, ok := countTokensBody(request); ok { ctx = withFollowUp(ctx, followUp{URL: makerSuiteRPCURL + "CountTokens", Body: body, Delay: delay}) } @@ -378,7 +403,7 @@ func (worker *NativeWorker) generate(ctx context.Context, generator pageGenerato }, }) if err != nil { - if ctx.Err() != nil { + if ctx.Err() != nil || errors.Is(err, camoufoxnative.ErrFunctionTabUnavailable) { worker.setPhase(WorkerReady) } else { worker.setPhase(WorkerFailed) diff --git a/internal/aistudio/runtime_settings.go b/internal/aistudio/runtime_settings.go index 4908c2a5..fbc1ec6e 100644 --- a/internal/aistudio/runtime_settings.go +++ b/internal/aistudio/runtime_settings.go @@ -74,7 +74,7 @@ func (runtime *goWAARuntime) settingSteps(body []byte) [][]waa.SettingStep { groups = append(groups, []waa.SettingStep{ {Wait: wait(), To: "system", Clicked: elements.openSystem}, {Wait: systemPause, To: "instructions", Text: text, Clicked: elements.editSystem}, - {Wait: closePause, To: "close", Clicked: func(time.Time) { runtime.settings.system = system }}, + {Wait: closePause, To: "close", Clicked: func(time.Time) { runtime.settings.system = bytes.Clone(system) }}, }) } } @@ -98,7 +98,7 @@ func (runtime *goWAARuntime) settingSteps(body []byte) [][]waa.SettingStep { groups = append(groups, append(group, waa.SettingStep{Wait: pause, To: "edit", Clicked: func(at time.Time) { elements.toggle(at, veFunctionsEdit) }}, waa.SettingStep{Wait: dialogPause, To: "declarations", Text: string(tools)}, - waa.SettingStep{Wait: closePause, To: "save", Clicked: func(time.Time) { runtime.settings.tools = tools }}, + waa.SettingStep{Wait: closePause, To: "save", Clicked: func(time.Time) { runtime.settings.tools = bytes.Clone(tools) }}, )) } return groups diff --git a/internal/aistudio/service.go b/internal/aistudio/service.go index a61cd2df..62395f00 100644 --- a/internal/aistudio/service.go +++ b/internal/aistudio/service.go @@ -147,33 +147,53 @@ func (t *WorkerProtectedTransport) doPrepared( selection AccountSelection, rpc RPCRequest, ) (*RPCResponse, error) { - lease, worker, rpc, prepared, err := t.prepareProtectedRequest(ctx, prompt, page, proof, selection, rpc) - if err != nil { - return nil, err - } - headers := rpc.Header - if prepared.Proof != "" { - browserState, err := worker.BrowserStorageState(ctx) - if err != nil { - return nil, fmt.Errorf("读取浏览器 Cookie: %w", err) + var ( + lease *AccountLease + worker ProtectedPreparer + response *RPCResponse + ) + for retried := false; ; retried = true { + attemptCtx := ctx + if retried { + attemptCtx = context.WithValue(ctx, skipFunctionTabKey{}, true) } - authorization, err := t.transport.signer.Authorization(browserState) + var ( + preparedRPC RPCRequest + prepared PreparedProtectedRequest + err error + ) + lease, worker, preparedRPC, prepared, err = t.prepareProtectedRequest(attemptCtx, prompt, page, proof, selection, rpc) if err != nil { return nil, err } - headers = rpc.Header.Clone() - headers.Set("Authorization", authorization) - } - if lease.CoolingDown(selectionAccessScope(selection)) { - return nil, ErrAccountCoolingDown - } - if prepared.Proof != "" { - reportRequestPhase(ctx, RequestPhaseSendingUpstream) - } - response, err := worker.SendProtected(ctx, ProtectedRequest{ - URL: rpc.URL, Headers: headers, Body: rpc.Body, ProofAt: rpc.ProofAt, Prompt: prompt, PagePrompt: prepared.PagePrompt, Proof: prepared.Proof, - }) - if err != nil { + headers := preparedRPC.Header + if prepared.Proof != "" { + browserState, err := worker.BrowserStorageState(ctx) + if err != nil { + return nil, fmt.Errorf("读取浏览器 Cookie: %w", err) + } + authorization, err := t.transport.signer.Authorization(browserState) + if err != nil { + return nil, err + } + headers = preparedRPC.Header.Clone() + headers.Set("Authorization", authorization) + } + if lease.CoolingDown(selectionAccessScope(selection)) { + return nil, ErrAccountCoolingDown + } + if prepared.Proof != "" { + reportRequestPhase(ctx, RequestPhaseSendingUpstream) + } + response, err = worker.SendProtected(attemptCtx, ProtectedRequest{ + URL: preparedRPC.URL, Headers: headers, Body: preparedRPC.Body, ProofAt: preparedRPC.ProofAt, Prompt: prompt, PagePrompt: prepared.PagePrompt, Proof: prepared.Proof, + }) + if err == nil { + break + } + if !retried && prepared.Proof == "" && errors.Is(err, camoufoxnative.ErrFunctionTabUnavailable) { + continue + } return nil, err } saving := &cookieSavingBody{ReadCloser: response.Body, done: make(chan struct{})} @@ -440,6 +460,44 @@ func (s *PooledService) refreshSteps(ctx context.Context, accountID string, wait return enter } +// VerifyAccount 占用指定账户的一个普通槽位同步目录并发一次最小生成请求核对验证状态,正常时解除受限、上游要求验证时标为需要验证 +func (s *PooledService) VerifyAccount(ctx context.Context, accountID string) error { + accountID = strings.TrimSpace(accountID) + enter := s.verifySteps(ctx, accountID) + lease, err := s.pool.AcquireFor(ctx, AccountSelection{AccountID: accountID, anyState: true}) + if err != nil { + return err + } + enter(AccountStepCatalog) + _, err = s.modelsForLease(ContextWithAccountLease(ContextWithResidentCatalog(ctx), lease), lease, true) + if err == nil { + enter(AccountStepVerifying) + err = s.checkAccountVerification(ctx, lease) + } + return errors.Join(err, lease.Release()) +} + +// verifySteps 返回验证核对流程的步骤报告函数,总步数包含目录读取、生成核对以及等待在途请求 +func (s *PooledService) verifySteps(ctx context.Context, accountID string) func(AccountStep) { + report, _ := ctx.Value(refreshStepsContextKey{}).(func(AccountStep, int, int)) + if report == nil { + return func(AccountStep) {} + } + waiting := s.pool.SlotBusy(accountID) + steps, done := 2, 0 + if waiting { + steps++ + } + enter := func(step AccountStep) { + done++ + report(step, done, max(steps, done)) + } + if waiting { + enter(AccountStepWaiting) + } + return enter +} + // checkAccountVerification 以账户的页面初始化模型在租约内发一次最小生成请求,第一次被上游 403、协议错误码 7 拒绝时与普通请求一样在同一账户重试一次:生成成功时解除受限,上游仍拒绝账户时按其原因保持服务受限,其他失败保持受限并返回该失败 func (s *PooledService) checkAccountVerification(ctx context.Context, lease *AccountLease) error { accountID := lease.Account().ID @@ -562,6 +620,40 @@ func (s *PooledService) cachedModels(accountID string) []Model { return cloneModels(account.Models) } +// Model 返回租约账户实时目录中的模型 +func (l *AccountLease) Model(modelID string) (Model, bool) { + modelID = strings.TrimPrefix(strings.TrimSpace(modelID), "models/") + if modelID == "" { + return Model{}, false + } + l.pool.mu.Lock() + defer l.pool.mu.Unlock() + for _, model := range l.account.Models { + if modelMatchesID(model, modelID) { + return cloneModels([]Model{model})[0], true + } + } + return Model{}, false +} + +// InteractionRoute 返回模型在租约账户与当前通道上是否走 CreateInteractionStream 或 CreateInteraction 后台任务 +func (l *AccountLease) InteractionRoute(modelID string) (stream bool, task bool) { + model, ok := l.Model(modelID) + if !ok { + return false, 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 +} + // DefinitiveAuthenticationFailure 判断上游是否明确要求重新认证 func DefinitiveAuthenticationFailure(err error) bool { if errors.Is(err, camoufoxnative.ErrAuthenticationRequired) { @@ -879,6 +971,10 @@ func retryableAccountError(err error) bool { if errors.Is(err, ErrAccountCoolingDown) { return true } + var readError *ResponseReadError + if errors.As(err, &readError) { + return !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) + } var rpcError *RPCError if !errors.As(err, &rpcError) { return false diff --git a/internal/aistudio/stream_activity.go b/internal/aistudio/stream_activity.go index 0322da53..1c68388b 100644 --- a/internal/aistudio/stream_activity.go +++ b/internal/aistudio/stream_activity.go @@ -12,8 +12,15 @@ type streamActivityReader struct { notify func(int) } -// ContextWithStreamActivityObserver 记录上游响应体实际到达的字节 +// ContextWithStreamActivityObserver 记录上游响应体实际到达的字节,ctx 已有的观察函数照常收到同样的字节 func ContextWithStreamActivityObserver(ctx context.Context, observer func(int)) context.Context { + if parent, _ := ctx.Value(streamActivityContextKey{}).(func(int)); parent != nil { + own := observer + observer = func(count int) { + parent(count) + own(count) + } + } return context.WithValue(ctx, streamActivityContextKey{}, observer) } diff --git a/internal/aistudio/thinking_guard.go b/internal/aistudio/thinking_guard.go new file mode 100644 index 00000000..7f5ebcc9 --- /dev/null +++ b/internal/aistudio/thinking_guard.go @@ -0,0 +1,49 @@ +package aistudio + +// thinkingGuardInstruction 是思考防拦截开启时追加到系统指令的简洁抽象思考引导,防止模型在思考阶段复述敏感明文触发上游过滤截断 +const thinkingGuardInstruction = "Keep internal reasoning brief and abstract using neutral English high-level beats only. Never transcribe, decode, quote, or spell out sensitive, graphic, violent, or explicit terms in internal reasoning." + +// thinkingGuardMaxBudget 是只支持思考预算的旧模型开启思考防拦截时的预算上限 +const thinkingGuardMaxBudget int64 = 1024 + +// thinkingGuardEligible 判断本次生成是否启用思考防拦截:仅限支持思考的文本生成模型 +func thinkingGuardEligible(request GenerateRequest, entry modelEntry) bool { + if !request.ThinkingGuard || nonTextGeneration(request, entry) { + return false + } + return entry.defaults.Thinking || entry.defaults.ThinkingLevel || entry.defaults.ThinkingBudget +} + +// applyThinkingGuard 追加简洁抽象思考引导并将高于 low 的思考强度上限收敛到 low,不抬高更低设置也不遮蔽非法参数 +func applyThinkingGuard(request GenerateRequest, entry modelEntry) GenerateRequest { + effort := normalizedReasoningEffort(request.Config.ReasoningEffort) + switch { + case entry.defaults.ThinkingLevel: + switch effort { + case "medium", "high", "xhigh", "extra_high", "max": + request.Config.ReasoningEffort = "low" + request.Config.ThinkingBudget = nil + case "": + switch { + case request.Config.ThinkingBudget != nil: + if *request.Config.ThinkingBudget > thinkingGuardMaxBudget { + request.Config.ReasoningEffort = "low" + request.Config.ThinkingBudget = nil + } + case entry.defaults.DefaultThinkingLevel != 4 && entry.defaults.DefaultThinkingLevel != 1: + request.Config.ReasoningEffort = "low" + } + } + case entry.defaults.ThinkingBudget: + if effort != "none" && (request.Config.ThinkingBudget == nil || *request.Config.ThinkingBudget > thinkingGuardMaxBudget) { + budget := thinkingGuardMaxBudget + request.Config.ThinkingBudget = &budget + } + } + instruction := thinkingGuardInstruction + if len(request.System) > 0 { + instruction = "\n" + instruction + } + request.System = appendSystem(request.System, instruction) + return request +} diff --git a/internal/aistudio/tool_contract.go b/internal/aistudio/tool_contract.go index 7275ff4d..2f7d8388 100644 --- a/internal/aistudio/tool_contract.go +++ b/internal/aistudio/tool_contract.go @@ -3,6 +3,7 @@ package aistudio import ( "bytes" "context" + "errors" "fmt" "slices" "strings" @@ -14,11 +15,13 @@ import ( // toolContract 保存客户端显式要求的调用模式与参数约束 type toolContract struct { - required bool - parallel *bool - names map[string]bool - schemas map[string]*jsonschema.Schema - serverSide bool + required bool + parallel *bool + names map[string]bool + schemas map[string]*jsonschema.Schema + serverSide bool + replyTool bool + stopSequences []string } // prepareToolRequest 将工具选择与约束转换为共同生成请求,compile 为 true 时编译严格函数的参数 Schema 供校验函数调用参数 @@ -202,7 +205,7 @@ func validationSchema(value any) any { return schema } -// forward 在完整工具事件发送给客户端前核对显式约束 +// forward 在完整工具事件发送给客户端前核对显式约束并转换回复工具输出 func (contract *toolContract) forward(ctx context.Context, source <-chan Event) <-chan Event { if contract == nil { return source @@ -213,10 +216,137 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) calls := 0 serverSideUsed := false failed := false + usedReplyTool := false + sawPlainText := false + bypassReported := false + matchedStop := "" + var pendingCalls []Event + var lastTextEvent Event + var matcher *stopSequenceMatcher + if contract.replyTool && len(contract.stopSequences) > 0 { + matcher = newStopSequenceMatcher(contract.stopSequences) + } + send := func(event Event) bool { + select { + case destination <- event: + return true + case <-ctx.Done(): + return false + } + } + flushTextTail := func() bool { + if matcher == nil || matchedStop != "" { + return true + } + pending := matcher.flush() + if pending == "" { + return true + } + textEvent := Event{ + Kind: EventText, + Part: Part{Text: pending}, + ProviderModel: lastTextEvent.ProviderModel, + TurnToken: lastTextEvent.TurnToken, + DebugInfo: lastTextEvent.DebugInfo, + ResponseID: lastTextEvent.ResponseID, + FrameUsage: lastTextEvent.FrameUsage, + FinishFrame: lastTextEvent.FinishFrame, + } + return send(textEvent) + } + flushPendingCalls := func() bool { + if !flushTextTail() { + return false + } + if matchedStop != "" { + pendingCalls = nil + return true + } + for _, pending := range pendingCalls { + if !send(pending) { + return false + } + } + pendingCalls = nil + return true + } + reportBypass := func() { + if contract.replyTool && !usedReplyTool && sawPlainText && !bypassReported { + bypassReported = true + reportReplyToolBypassed(ctx) + } + } for event := range source { if failed { continue } + if matchedStop != "" { + pendingCalls = nil + switch event.Kind { + case EventUsage: + if !send(event) { + return + } + case EventFinish: + reportBypass() + event.FinishReason = "stop_sequence" + event.StopSequence = matchedStop + if !send(event) { + return + } + } + continue + } + if contract.replyTool && event.Kind == EventToolCall && event.FunctionCall != nil && event.FunctionCall.Name == replyToolName { + text, ok := replyToolText(event.FunctionCall.Arguments) + if !ok { + failed = true + reportBypass() + if !send(Event{Kind: EventError, Err: fmt.Errorf("上游 function %q 参数违反 strict Schema: %w", replyToolName, errors.New("reply tool final arguments must include string content"))}) { + return + } + continue + } + usedReplyTool = true + lastTextEvent = event + if matcher != nil { + var sequence string + text, sequence = matcher.write(text) + if sequence != "" { + matchedStop = sequence + } + } + if text != "" { + textEvent := Event{ + Kind: EventText, + Part: Part{Text: text}, + ProviderModel: event.ProviderModel, + TurnToken: event.TurnToken, + DebugInfo: event.DebugInfo, + ResponseID: event.ResponseID, + FrameUsage: event.FrameUsage, + FinishFrame: event.FinishFrame, + } + if !send(textEvent) { + return + } + } + continue + } + if contract.replyTool && event.Kind == EventText && event.Text != "" { + sawPlainText = true + lastTextEvent = event + if matcher != nil { + text, sequence := matcher.write(event.Text) + if sequence != "" { + matchedStop = sequence + } + if text == "" { + continue + } + event.Text = text + } + } var err error if event.Kind == EventGrounding || event.Kind == EventExecutableCode || event.Kind == EventCodeExecutionResult || event.Kind == EventServerToolCall { serverSideUsed = true @@ -225,7 +355,7 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) calls++ call := event.FunctionCall switch { - case !contract.names[call.Name]: + case contract.names != nil && !contract.names[call.Name]: err = fmt.Errorf("上游返回了未选择的函数 %q", call.Name) case contract.parallel != nil && !*contract.parallel && calls > 1: err = fmt.Errorf("上游违反单次工具调用约束") @@ -250,11 +380,31 @@ func (contract *toolContract) forward(ctx context.Context, source <-chan Event) event = Event{Kind: EventError, Err: err} failed = true } - select { - case destination <- event: - case <-ctx.Done(): + if contract.replyTool && !failed && event.Kind == EventToolCall && event.FunctionCall != nil { + pendingCalls = append(pendingCalls, event) + continue + } + if contract.replyTool && (event.Kind == EventUsage || event.Kind == EventFinish) { + if !flushPendingCalls() { + return + } + } else if contract.replyTool && !failed && event.Kind != EventText && event.Kind != EventError { + if !flushTextTail() { + return + } + } + if contract.replyTool && (event.Kind == EventFinish || event.Kind == EventError) { + reportBypass() + } + if !send(event) { + return + } + } + if !failed { + if !flushPendingCalls() { return } + reportBypass() } }() return destination diff --git a/internal/aistudio/transport_browser.go b/internal/aistudio/transport_browser.go index a9b7fd84..261dc4a2 100644 --- a/internal/aistudio/transport_browser.go +++ b/internal/aistudio/transport_browser.go @@ -11,7 +11,6 @@ import ( "net/url" "slices" "sort" - "strconv" "strings" "sync" "time" @@ -32,6 +31,8 @@ const ( firefoxPingTimeout = 8 * time.Second // nssTLSGREASEECHInner 是 NSS 为 TCP ClientHello 的 GREASE ECH 估算的内层 ClientHello 基础长度 nssTLSGREASEECHInner = 217 + // firefoxConnectionTimeout 是 Firefox network.http.connection-timeout,直连 TCP 拨号在系统未先放弃时的上限 + firefoxConnectionTimeout = 90 * time.Second // firefoxTLSHandshakeTimeout 是 Firefox network.http.tls-handshake-timeout firefoxTLSHandshakeTimeout = 30 * time.Second // browserIdleConnTimeout 是 Firefox network.http.http2.timeout,空闲 HTTP/2 连接保留该时长后关闭 @@ -46,8 +47,17 @@ 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 秒上限 +var firefoxDirectDialer = &net.Dialer{Timeout: firefoxConnectionTimeout} + // firefoxHTTP2Settings 是 Firefox 158 在每条 HTTP/2 连接开头发送的 SETTINGS var firefoxHTTP2Settings = map[http2.SettingID]uint32{ http2.SettingHeaderTableSize: 65536, @@ -219,14 +229,17 @@ type browserRoundTripper struct { transport *http2.Transport pool *firefoxConnPool mu sync.Mutex - // preflights 按 preflightKey 记录 CORS 预检缓存 + // preflights 按 preflightCacheKey 记录 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 不查方法,其余方法与每个脚本设置的请求头都在有效期内 @@ -242,6 +255,21 @@ 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 @@ -251,7 +279,7 @@ type browserResponseBody struct { // newBrowserRoundTripper 创建与当前 Camoufox 网络形状一致的 HTTP/2 传输 func newBrowserRoundTripper(proxyURL string) (stdhttp.RoundTripper, error) { proxyURL = strings.TrimSpace(proxyURL) - var proxyDialer proxy.ContextDialer = &net.Dialer{} + var proxyDialer proxy.ContextDialer = firefoxDirectDialer sessions := &firefoxSessionCache{sessions: map[firefoxSessionPeer][]*tls.ClientSessionState{}} if proxyURL != "" { parsed, err := url.Parse(proxyURL) @@ -271,9 +299,9 @@ func newBrowserRoundTripper(proxyURL string) (stdhttp.RoundTripper, error) { } } pool := &firefoxConnPool{ - dial: func(address string, anonymous bool, timing *connectionTiming) (net.Conn, error) { + dial: func(ctx context.Context, address string, anonymous bool, timing *connectionTiming) (net.Conn, error) { proxyDialer := timing.dialer(proxyDialer, sessions.tunnel) - return dialBrowserTLS(proxyDialer, sessions, address, anonymous) + return dialBrowserTLS(ctx, proxyDialer, sessions, address, anonymous) }, conns: map[string][]*http2.ClientConn{}, experienced: map[*http2.ClientConn]bool{}, @@ -353,7 +381,7 @@ func (dialer tracedDialer) DialContext(ctx context.Context, network, address str // firefoxConnPool 按 Firefox 选择 HTTP/2 连接,匿名请求与携带凭据的请求分开建连 type firefoxConnPool struct { transport *http2.Transport - dial func(address string, anonymous bool, timing *connectionTiming) (net.Conn, error) + dial func(ctx context.Context, address string, anonymous bool, timing *connectionTiming) (net.Conn, error) mu sync.Mutex conns map[string][]*http2.ClientConn // experienced 记录握手完成后又分派过请求的连接,即 Firefox 的 IsExperienced @@ -420,17 +448,22 @@ func (pool *firefoxConnPool) get(ctx context.Context, address string) (*http2.Cl if timing != nil { timing.dialed = true } - return pool.connect(address, class, timing) + return pool.connect(ctx, address, class, timing) } -// connect 拨出一条 class 类别的连接并放入池中,调用方已为它计入 dialing -func (pool *firefoxConnPool) connect(address string, class requestClass, timing *connectionTiming) (*http2.ClientConn, error) { +// connect 拨出一条 class 类别的连接并放入池中,调用方已为它计入 dialing,拨号随 ctx 取消而中止 +func (pool *firefoxConnPool) connect(ctx context.Context, address string, class requestClass, timing *connectionTiming) (*http2.ClientConn, error) { var conn *http2.ClientConn - raw, err := pool.dial(address, class.anonymous, timing) + raw, err := pool.dial(ctx, address, class.anonymous, timing) if err == nil { - conn, err = pool.transport.NewClientConn(raw) - if err != nil { + if ctx.Err() != nil { _ = raw.Close() + err = ctx.Err() + } else { + conn, err = pool.transport.NewClientConn(raw) + if err != nil { + _ = raw.Close() + } } } key := poolKey(address, class) @@ -444,16 +477,22 @@ func (pool *firefoxConnPool) connect(address string, class requestClass, timing return conn, err } -// speculate 与 Firefox 为需要预检的跨域请求预先连接实际请求所属的连接类别一样,该类别没有连接也没有正在拨出的连接时在后台拨出一条 +// speculate 与 Firefox 为需要预检的跨域请求预先连接实际请求所属的连接类别一样,本类没有连接或拨号且另一类没有可复用的已复用连接时在后台拨出一条 func (pool *firefoxConnPool) speculate(address string, class requestClass) { key := poolKey(address, class) + inverted := poolKey(address, requestClass{anonymous: !class.anonymous}) pool.mu.Lock() defer pool.mu.Unlock() if len(pool.conns[key])+pool.dialing[key] > 0 { return } + if slices.ContainsFunc(pool.conns[inverted], func(conn *http2.ClientConn) bool { + return pool.experienced[conn] && conn.CanTakeNewRequest() + }) { + return + } pool.dialing[key]++ - go func() { _, _ = pool.connect(address, class, nil) }() + go func() { _, _ = pool.connect(context.Background(), address, class, nil) }() } // availableLocked 返回本类能接受新请求的最早连接并把它记为已复用,没有时返回另一类已复用过的连接 @@ -586,23 +625,33 @@ func (sessions handshakeSessions) Put(_ string, session *tls.ClientSessionState) } } -// dialBrowserTLS 以 Firefox ClientHello 建立 TLS 连接并要求协商 HTTP/2,按 Firefox 取票据的时机在建 socket 时与 CONNECT 隧道建立后取用会话票据 -func dialBrowserTLS(dialer proxy.ContextDialer, sessions *firefoxSessionCache, address string, anonymous bool) (net.Conn, error) { +// dialBrowserTLS 以 Firefox ClientHello 建立 TLS 连接并要求协商 HTTP/2,拨号与 TLS 握手随 ctx 取消而中止(握手另套 30 秒上限),按 Firefox 取票据的时机在建 socket 时与 CONNECT 隧道建立后取用会话票据 +func dialBrowserTLS(ctx context.Context, dialer proxy.ContextDialer, sessions *firefoxSessionCache, address string, anonymous bool) (net.Conn, error) { host, _, _ := net.SplitHostPort(address) peer := firefoxSessionPeer{host: host, anonymous: anonymous} session, psk := sessions.take(peer) - raw, err := dialer.DialContext(context.Background(), "tcp", address) + raw, err := dialer.DialContext(ctx, "tcp", address) if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, err + } + if err := ctx.Err(); err != nil { + _ = raw.Close() return nil, err } if sessions.tunnel { session, psk = sessions.take(peer) } connection := tls.UClient(raw, &tls.Config{ServerName: host, OmitEmptyPsk: true, ClientSessionCache: handshakeSessions{sessions, peer, session}}, firefox158ClientHello(psk), false, false, false) - ctx, cancel := context.WithTimeout(context.Background(), firefoxTLSHandshakeTimeout) + handshakeCtx, cancel := context.WithTimeout(ctx, firefoxTLSHandshakeTimeout) defer cancel() - if err := connection.HandshakeContext(ctx); err != nil { + if err := connection.HandshakeContext(handshakeCtx); err != nil { _ = connection.Close() + if ctx.Err() != nil { + return nil, ctx.Err() + } return nil, err } if protocol := connection.ConnectionState().NegotiatedProtocol; protocol != http2.NextProtoTLS { @@ -636,8 +685,10 @@ 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, preflightKey(request)) + delete(transport.preflights, preflightCacheKey(target, false)) + delete(transport.preflights, preflightCacheKey(target, true)) transport.mu.Unlock() return nil, err } @@ -662,7 +713,7 @@ func (transport *browserRoundTripper) RoundTrip(request *stdhttp.Request) (*stdh }, nil } -// roundTrip 经 HTTP/2 以 Firefox 的 HEADERS 帧优先级执行上游请求,anonymous 表示不携带凭据的请求(CORS 预检与 CSP 报告),请求 context 结束时立即返回,未完成的拨号在后台结束 +// roundTrip 经 HTTP/2 以 Firefox 的 HEADERS 帧优先级执行上游请求,anonymous 表示不携带凭据的请求(CORS 预检与 CSP 报告),请求 context 结束时中止拨号并立即返回 func (transport *browserRoundTripper) roundTrip(request *fhttp.Request, anonymous bool) (*fhttp.Response, error) { ctx := withRequestClass(request.Context(), requestClass{anonymous: anonymous}) request = request.WithContext(http2.WithHeaderPriority(ctx, firefoxStreamPriority(request.Header))) @@ -677,6 +728,9 @@ func (transport *browserRoundTripper) roundTrip(request *fhttp.Request, anonymou }() select { case value := <-done: + if value.err != nil && request.Context().Err() != nil { + return nil, request.Context().Err() + } return value.response, value.err case <-request.Context().Done(): go func() { @@ -721,15 +775,34 @@ func standardHeader(source fhttp.Header) stdhttp.Header { return result } -// preflightKey 返回请求的 CORS 预检缓存键:与 Firefox nsPreflightCache 一样按 URL 与是否携带凭据区分 -func preflightKey(request *stdhttp.Request) string { - if requestClassOf(request.Context()).anonymous { - return "anonymous " + request.URL.String() +// preflightCacheKey 返回 URL 与是否匿名的 CORS 预检缓存键,与 Firefox nsPreflightCache 一样区分是否携带凭据 +func preflightCacheKey(target string, anonymous bool) string { + if anonymous { + return "anonymous " + target } - return request.URL.String() + return target } -// ensurePreflight 为带 Origin 的跨域 cors 请求按 Firefox 的流程先发 CORS 预检:先在后台为实际请求的类别预先拨出连接,预检走匿名连接,预检响应允许的方法与请求头按 Access-Control-Max-Age(上限 24 小时)逐个缓存;no-cors 请求与只带安全头的 GET、HEAD、POST 不预检 +// 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 + } + return time.Duration(seconds) * time.Second, true +} + +// ensurePreflight 为带 Origin 的跨域 cors 请求按 Firefox 的流程先发 CORS 预检:携带凭据的请求先在后台预先拨出带凭据的连接,预检走匿名连接,预检响应允许的方法与请求头按 Access-Control-Max-Age(上限 24 小时、缓存上限 100 条)逐个缓存;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 { @@ -740,18 +813,28 @@ func (transport *browserRoundTripper) ensurePreflight(request *stdhttp.Request) return nil } target := request.URL.String() - key := preflightKey(request) + class := requestClassOf(request.Context()) + key := preflightCacheKey(target, class.anonymous) + now := time.Now() transport.mu.Lock() - cached := transport.preflights[key].allows(request.Method, unsafe, time.Now()) + 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) transport.mu.Unlock() if cached { return nil } - port := request.URL.Port() - if port == "" { - port = "443" + if !class.anonymous { + port := request.URL.Port() + if port == "" { + port = "443" + } + transport.pool.speculate(net.JoinHostPort(request.URL.Hostname(), port), class) } - transport.pool.speculate(net.JoinHostPort(request.URL.Hostname(), port), requestClassOf(request.Context())) preflight, err := fhttp.NewRequestWithContext(request.Context(), stdhttp.MethodOptions, target, nil) if err != nil { return err @@ -777,23 +860,47 @@ func (transport *browserRoundTripper) ensurePreflight(request *stdhttp.Request) if response.StatusCode < 200 || response.StatusCode > 299 { return fmt.Errorf("CORS 预检返回 HTTP %d", response.StatusCode) } - 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) + maxAge, ok := parsePreflightMaxAge(response.Header.Get("Access-Control-Max-Age")) + if !ok { + return nil } - expiry := time.Now().Add(maxAge) + storedAt := time.Now() + expiry := storedAt.Add(maxAge) transport.mu.Lock() - grant := transport.preflights[key] - if grant.headers == nil { + 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 = 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"), ",") { - grant.methods[strings.TrimSpace(method)] = expiry + if method = strings.TrimSpace(method); method != "" { + grant.methods[method] = expiry + } } for _, name := range strings.Split(response.Header.Get("Access-Control-Allow-Headers"), ",") { - grant.headers[strings.ToLower(strings.TrimSpace(name))] = expiry + if name = strings.ToLower(strings.TrimSpace(name)); name != "" { + grant.headers[name] = expiry + } } + transport.preflights[key] = grant transport.mu.Unlock() return nil } diff --git a/internal/aistudio/transport_http.go b/internal/aistudio/transport_http.go index 656c32ba..61bc06d9 100644 --- a/internal/aistudio/transport_http.go +++ b/internal/aistudio/transport_http.go @@ -45,15 +45,22 @@ type HTTPTransportOptions struct { GlobalProxy string } +// accountHTTPClient 保存单个账户当前出口代理对应的 HTTP 客户端 +type accountHTTPClient struct { + proxyURL string + client *http.Client +} + // MakerSuiteHTTPTransport 使用账户固定出口发送普通 RPC type MakerSuiteHTTPTransport struct { - pool *AccountPool - signer *Signer - headers ProtocolHeaderProvider - globalProxy string - now func() time.Time - clientsMu sync.Mutex - clients map[string]*http.Client + pool *AccountPool + signer *Signer + headers ProtocolHeaderProvider + globalProxy string + now func() time.Time + clientsMu sync.Mutex + clients map[string]*http.Client + accountClients map[string]accountHTTPClient // driveMu 保护 driveDiscovered driveMu sync.Mutex // driveDiscovered 记录已按官网页面读取 Drive discovery 文档的账户 @@ -114,6 +121,7 @@ func NewMakerSuiteHTTPTransport(options HTTPTransportOptions) (*MakerSuiteHTTPTr 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 { @@ -205,7 +213,7 @@ func (t *MakerSuiteHTTPTransport) UploadAssistantFile(ctx context.Context, accou if err != nil { return "", fmt.Errorf("读取账户动态公共头: %w", err) } - client, err := t.clientForProxy(account.EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(account) if err != nil { return "", err } @@ -324,7 +332,7 @@ func (t *MakerSuiteHTTPTransport) Do(ctx context.Context, rpc RPCRequest) (*RPCR return nil, releaseOnError(fmt.Errorf("创建 MakerSuite %s 请求: %w", rpc.Method, err)) } request.Header = headers - client, err := t.clientForProxy(account.EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(account) if err != nil { return nil, releaseOnError(err) } @@ -378,8 +386,34 @@ func (t *MakerSuiteHTTPTransport) CloseIdleConnections() { for _, client := range t.clients { client.CloseIdleConnections() } + for _, entry := range t.accountClients { + entry.client.CloseIdleConnections() + } +} + +// clientForAccount 返回账户专用的固定出口客户端,与每账户一个浏览器的 Firefox 一致,按账户隔离连接池、预检缓存与 TLS 票据缓存 +func (t *MakerSuiteHTTPTransport) clientForAccount(account *Account) (*http.Client, error) { + proxyURL := account.EffectiveProxy(t.globalProxy) + t.clientsMu.Lock() + if entry, ok := t.accountClients[account.ID]; ok && entry.proxyURL == proxyURL { + t.clientsMu.Unlock() + return entry.client, nil + } + client, err := NewProxyHTTPClient(proxyURL) + if err != nil { + t.clientsMu.Unlock() + return nil, err + } + previous := t.accountClients[account.ID].client + t.accountClients[account.ID] = accountHTTPClient{proxyURL: proxyURL, client: client} + t.clientsMu.Unlock() + if previous != nil { + previous.CloseIdleConnections() + } + return client, nil } +// clientForProxy 返回按代理共用的无凭据客户端,供不带账户 Cookie 与授权头的公开静态资源请求使用 func (t *MakerSuiteHTTPTransport) clientForProxy(proxyURL string) (*http.Client, error) { t.clientsMu.Lock() defer t.clientsMu.Unlock() diff --git a/internal/aistudio/types.go b/internal/aistudio/types.go index 4d1235f4..d9bcc879 100644 --- a/internal/aistudio/types.go +++ b/internal/aistudio/types.go @@ -450,6 +450,12 @@ type GenerateRequest struct { Truncate bool `json:"-"` // KeepAbnormalFinish 表示异常结束重新生成耗尽且没有输出时仍以该结束原因结束,供按官方形状输出的 Gemini 入口使用 KeepAbnormalFinish bool `json:"-"` + // ReplyTool 表示经内部 final 函数交付正文以减轻角色扮演场景的流式截断 + ReplyTool bool `json:"-"` + // UserMessageRewrite 表示发往上游前改写用户消息的模式(off、traditional、martian),开启时要求模型默认以简体中文回复 + UserMessageRewrite string `json:"-"` + // ThinkingGuard 表示引导思考阶段保持简洁抽象不复述敏感词并将思考上限收敛到低档,以减轻思考阶段触发上游过滤截断 + ThinkingGuard bool `json:"-"` // continuationRound 为自动续写的轮次,首轮为 0 continuationRound int // continuationToken 为上一轮响应给出的续写 token diff --git a/internal/aistudio/upload.go b/internal/aistudio/upload.go index 4e44517a..902c1d4c 100644 --- a/internal/aistudio/upload.go +++ b/internal/aistudio/upload.go @@ -844,7 +844,7 @@ func inlineMediaKeyOf(part Part) inlineMediaKey { return inlineMediaKey{mime: part.InlineData.MIME, sha256: base64.StdEncoding.EncodeToString(digest[:]), name: part.DisplayName} } -// InlineMediaAccount 返回已上传 contents 中最多内联附件的账户,没有账户上传过时返回空串 +// InlineMediaAccount 返回已上传 contents 中最多未过期内联附件的可用账户,没有符合条件的账户时返回空串 func (p *AccountPool) InlineMediaAccount(contents []Content) string { keys := make(map[inlineMediaKey]bool) for _, content := range contents { @@ -859,11 +859,15 @@ func (p *AccountPool) InlineMediaAccount(contents []Content) string { } p.mu.Lock() defer p.mu.Unlock() + now := time.Now().UTC() best, bestHits := "", 0 for _, account := range p.accounts { + if !account.Config.Enabled || account.State != AccountReady { + continue + } hits := 0 for _, binding := range account.runtime.Resources { - if binding.Kind == "inline-media" && keys[inlineMediaKey{mime: binding.MIME, sha256: binding.SHA256, name: binding.DisplayName}] { + if binding.Kind == "inline-media" && binding.expiresAt().After(now) && keys[inlineMediaKey{mime: binding.MIME, sha256: binding.SHA256, name: binding.DisplayName}] { hits++ } } @@ -1178,6 +1182,10 @@ func (s *PooledService) UploadInlineMediaToLease( } return nil, nil, errors.Join(err, temporary.Cleanup()) } + if driveAuthorizationMissing(folderErr) { + temporary.release = s.useInlineMedia(used) + return rewritten, temporary, nil + } } for _, id := range expired { temporary.copies = append(temporary.copies, temporaryDriveCopy{id: id, token: token, bound: true}) @@ -1323,7 +1331,7 @@ func (t *MakerSuiteHTTPTransport) UploadDrive(ctx context.Context, accountID str if owned { defer func() { err = errors.Join(err, lease.Release()) }() } - client, err := t.clientForProxy(lease.Account().EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(lease.Account()) if err != nil { return FileRef{}, err } @@ -1467,7 +1475,7 @@ func (t *MakerSuiteHTTPTransport) getDriveFile(ctx context.Context, accountID, t if err != nil { return err } - client, err := t.clientForProxy(account.EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(account) if err != nil { return err } @@ -1729,7 +1737,7 @@ func (t *MakerSuiteHTTPTransport) DownloadDrive(ctx context.Context, accountID s return MediaStream{}, release(err) } httpRequest.Header.Set("Authorization", "Bearer "+token) - client, err := t.clientForProxy(lease.Account().EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(lease.Account()) if err != nil { return MediaStream{}, release(err) } @@ -1769,7 +1777,7 @@ func (t *MakerSuiteHTTPTransport) DeleteDrive(ctx context.Context, accountID str return err } request.Header.Set("Authorization", "Bearer "+token) - client, err := t.clientForProxy(lease.Account().EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(lease.Account()) if err != nil { return err } @@ -1802,7 +1810,7 @@ func (t *MakerSuiteHTTPTransport) DriveFileExists(ctx context.Context, accountID return false, err } request.Header.Set("Authorization", "Bearer "+token) - client, err := t.clientForProxy(lease.Account().EffectiveProxy(t.globalProxy)) + client, err := t.clientForAccount(lease.Account()) if err != nil { return false, err } diff --git a/internal/aistudio/webchannel.go b/internal/aistudio/webchannel.go index 1e76939a..0f68e592 100644 --- a/internal/aistudio/webchannel.go +++ b/internal/aistudio/webchannel.go @@ -405,7 +405,7 @@ func (t *WorkerProtectedTransport) OpenBidiProtected( if err != nil { return nil, err } - client, err := t.transport.clientForProxy(lease.Account().EffectiveProxy(t.transport.globalProxy)) + client, err := t.transport.clientForAccount(lease.Account()) if err != nil { return nil, err } diff --git a/internal/api/account_tasks.go b/internal/api/account_tasks.go index 7a843b2e..a8fff73d 100644 --- a/internal/api/account_tasks.go +++ b/internal/api/account_tasks.go @@ -13,7 +13,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" ) -// AccountTask 是在服务端运行的添加或重新登录账户任务,管理页关闭或刷新后继续运行,结束后保留到用户关闭 +// AccountTask 是在服务端运行的添加、重新登录或刷新账户任务,管理页关闭或刷新后继续运行,结束后保留到用户关闭 type AccountTask struct { ID string `json:"id"` Kind string `json:"kind"` @@ -32,12 +32,14 @@ type AccountTaskItem struct { Error string `json:"error,omitempty"` } -// 账户任务中一个账户的步骤:等待在浏览器中登录、读取浏览器里的登录状态、检查 AI Studio 访问、保存账户 +// 账户任务中一个账户的步骤:等待在浏览器中登录、读取浏览器里的登录状态、检查 AI Studio 访问、保存账户、核对验证状态、等待在验证页完成验证 const ( - TaskStepLogin = "login" - TaskStepReading = "reading" - TaskStepChecking = "checking" - TaskStepSaving = "saving" + TaskStepLogin = "login" + TaskStepReading = "reading" + TaskStepChecking = "checking" + TaskStepSaving = "saving" + TaskStepVerifying = "verifying" + TaskStepVerify = "verify" ) // taskStepContextKey 是 context 中账户任务步骤回调的键 @@ -46,6 +48,9 @@ type taskStepContextKey struct{} // taskLabelContextKey 是 context 中账户任务正在处理的账户标签的键 type taskLabelContextKey struct{} +// taskLabelReportContextKey 是 context 中账户任务更新账户标签回调的键 +type taskLabelReportContextKey struct{} + // TaskLabel 返回 ctx 所属账户任务正在处理的账户标签,ctx 不属于账户任务时为空串 func TaskLabel(ctx context.Context) string { label, _ := ctx.Value(taskLabelContextKey{}).(string) @@ -59,6 +64,13 @@ func ReportTaskStep(ctx context.Context, step string) { } } +// ReportTaskLabel 把已知的账户邮箱写入进行中的账户任务,ctx 不属于账户任务时不做任何事 +func ReportTaskLabel(ctx context.Context, label string) { + if report, ok := ctx.Value(taskLabelReportContextKey{}).(func(string)); ok { + report(label) + } +} + // chromeImportRequest 是从本机 Chrome 导入的账号与共用的账户环境 type chromeImportRequest struct { Accounts []struct { @@ -215,6 +227,12 @@ func runAccountTaskItems(ctx context.Context, update accountTaskUpdate, count in label = task.Items[index].Label }) itemCtx := context.WithValue(ctx, taskLabelContextKey{}, label) + itemCtx = context.WithValue(itemCtx, taskLabelReportContextKey{}, func(nextLabel string) { + if nextLabel == "" { + return + } + update(func(task *AccountTask) { task.Items[index].Label = nextLabel }) + }) account, err := run(context.WithValue(itemCtx, taskStepContextKey{}, func(step string) { update(func(task *AccountTask) { task.Items[index].Step = step }) }), index) @@ -299,6 +317,75 @@ func (s *server) handleLoginAccount(w http.ResponseWriter, r *http.Request) { }) } +// handleVerifyAccount 在账户任务中打开浏览器停在验证页供用户完成验证,验证后自动核对 +func (s *server) handleVerifyAccount(w http.ResponseWriter, r *http.Request) { + var input struct { + View string `json:"view"` + } + if r.ContentLength != 0 { + if err := decodeJSON(r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + } + id := r.PathValue("id") + view, release := s.loginView(r, input.View) + task := AccountTask{Kind: "verify", Items: []AccountTaskItem{{Label: id, State: "pending"}}} + if view != nil { + task.View = input.View + } + s.startAccountTask(w, r, task, func(ctx context.Context, update accountTaskUpdate) { + defer release() + runAccountTaskItems(ctx, update, 1, func(ctx context.Context, _ int) (AdminAccount, error) { + return s.config.Admin.VerifyAccount(ctx, id, view) + }) + }) +} + +// refreshTaskConcurrency 是刷新任务同时刷新的账户数 +const refreshTaskConcurrency = 4 + +// handleRefreshAccounts 在账户任务中按 refreshTaskConcurrency 的并发依次刷新所列账户,账户标签为账户 ID,任务被关闭后不再开始刷新 +func (s *server) handleRefreshAccounts(w http.ResponseWriter, r *http.Request) { + var input struct { + IDs []string `json:"ids"` + } + if err := decodeJSON(r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + task := AccountTask{Kind: "refresh", Items: make([]AccountTaskItem, len(input.IDs))} + next := make(chan int, len(input.IDs)) + for index, id := range input.IDs { + task.Items[index] = AccountTaskItem{Label: id, State: "pending"} + next <- index + } + close(next) + s.startAccountTask(w, r, task, func(ctx context.Context, update accountTaskUpdate) { + var group sync.WaitGroup + for range min(refreshTaskConcurrency, len(input.IDs)) { + group.Go(func() { + for index := range next { + if ctx.Err() != nil { + return + } + update(func(task *AccountTask) { task.Items[index].State = "running" }) + _, err := s.config.Admin.RefreshAccount(ctx, input.IDs[index]) + update(func(task *AccountTask) { + item := &task.Items[index] + if err != nil { + item.State, item.Code, item.Error = "failed", codeFromError(err, ""), err.Error() + return + } + item.State = "done" + }) + } + }) + } + group.Wait() + }) +} + // handleImportChromeAccounts 在账户任务中同时导入选中的本机 Chrome 账号,各账号独立保存 func (s *server) handleImportChromeAccounts(w http.ResponseWriter, r *http.Request) { var input chromeImportRequest diff --git a/internal/api/admin.go b/internal/api/admin.go index 066c0fda..12506b29 100644 --- a/internal/api/admin.go +++ b/internal/api/admin.go @@ -2,6 +2,7 @@ package api import ( "context" + "encoding/json" "errors" "net/http" "time" @@ -18,6 +19,7 @@ type AdminService interface { AccountExits(context.Context) ([]AccountExit, error) CreateAccount(context.Context, AccountCreateInput, *camoufoxnative.LiveView) (AdminAccount, error) ChromeImportProfiles(context.Context) ([]ChromeImportProfile, error) + CheckChromeImportTiers(context.Context, ChromeTierCheckInput, func(ChromeProfileTier)) error CookieBrowsers(ctx context.Context, proxy string) ([]CookieBrowser, error) DiscoverCookieAccounts(context.Context, CookieImportInput) ([]CookieBrowser, error) ImportChromeAccounts(context.Context, ChromeImportInput) ([]AdminAccount, error) @@ -27,6 +29,7 @@ type AdminService interface { SetAccountState(ctx context.Context, accountID string, state string) (AdminAccount, error) DeleteAccount(context.Context, string) error LoginAccount(context.Context, string, *camoufoxnative.LiveView) (AdminAccount, error) + VerifyAccount(context.Context, string, *camoufoxnative.LiveView) (AdminAccount, error) RefreshAccount(context.Context, string) (AdminAccountRefresh, error) StartService(context.Context) (AdminStatus, error) StopService(context.Context) (AdminStatus, error) @@ -190,6 +193,7 @@ type AdminAccountCounts struct { type AdminAccount struct { ID string `json:"id"` Label string `json:"label"` + Note string `json:"note,omitempty"` Enabled bool `json:"enabled"` State string `json:"state"` Proxy string `json:"proxy"` @@ -218,6 +222,10 @@ type AdminAccount struct { ActiveRequests int `json:"active_requests"` // CatalogError 是已有模型目录的账户最近一次目录同步失败的原因,下一次同步成功后省略 CatalogError string `json:"catalog_error,omitempty"` + // VerificationRequired 表示账户因上游要求验证而受限,可在验证页完成验证后恢复 + VerificationRequired bool `json:"verification_required,omitempty"` + // DeviceBoundSession 表示账户会话带 __Secure-1PSIDRTS 且缺少本地与远程续签材料,约 2 小时内失效 + DeviceBoundSession bool `json:"device_bound_session,omitempty"` } // AccountExit 表示一个账户出口代理的公网 IP 与按 IP 定位的国家、时区和语言,Proxy 为空时是直连,查询失败时 Error 为原因 @@ -251,6 +259,7 @@ type AdminAccountRefresh struct { // AccountInput 表示已有账户配置 type AccountInput struct { Label string `json:"label"` + Note string `json:"note"` Enabled bool `json:"enabled"` Proxy string `json:"proxy"` Locale string `json:"locale"` @@ -276,10 +285,28 @@ type ChromeImportProfile struct { Profile string `json:"profile"` DisplayName string `json:"display_name"` Email string `json:"email"` + // Imported 表示该邮箱已存在于账户列表中(需要重新登录或受限) + Imported bool `json:"imported,omitempty"` + // BenefitTier 是该账户已知或检测出的 AI Studio 权益等级,未检测时省略 + BenefitTier string `json:"benefit_tier,omitempty"` // Restricted 是该账户服务受限的原因,受限的账户不能导入 Restricted string `json:"restricted"` } +// ChromeTierCheckInput 是按需检测本机 Chrome 账号权益的请求参数 +type ChromeTierCheckInput struct { + AccountIDs []string `json:"account_ids"` + Proxy string `json:"proxy"` +} + +// ChromeProfileTier 是按需检测单个本机 Chrome 账号权益的流式结果 +type ChromeProfileTier struct { + ID string `json:"id"` + BenefitTier string `json:"benefit_tier,omitempty"` + Restricted string `json:"restricted,omitempty"` + Error string `json:"error,omitempty"` +} + // CookieBrowser 表示本机开启远程调试的浏览器与其中登录 AI Studio 的账户 type CookieBrowser struct { Address string `json:"address"` @@ -296,6 +323,8 @@ type CookieBrowser struct { DeviceBound bool `json:"device_bound"` // SignInRequired 表示该账户已导入且需要重新登录,导入时原地更新它的认证状态 SignInRequired bool `json:"sign_in_required"` + // BenefitTier 是识别阶段读取到的 AI Studio 权益等级,未读取到时省略 + BenefitTier string `json:"benefit_tier,omitempty"` } // ChromeImportInput 表示批量导入的 Chrome 账号与账户环境 @@ -326,8 +355,12 @@ type RuntimeConfig struct { GoogleSearch bool `json:"google_search"` FirstEventHedge string `json:"first_event_hedge"` FirstEventHedgeModels string `json:"first_event_hedge_models"` + FirstEventTimeout string `json:"first_event_timeout"` ContinuationRewrite bool `json:"continuation_rewrite"` ContinuationPrompt string `json:"continuation_prompt"` + ReplyTool bool `json:"reply_tool"` + UserMessageRewrite string `json:"user_message_rewrite"` + ThinkingGuard bool `json:"thinking_guard"` LogFile bool `json:"log_file"` LogMaxTotalMB int `json:"log_max_total_mb"` AuthStates string `json:"auth_states"` @@ -401,6 +434,7 @@ func (s *server) registerAdmin(mux *http.ServeMux) { mux.HandleFunc("GET /api/accounts/exits", s.handleAccountExits) mux.HandleFunc("POST /api/accounts", s.handleCreateAccount) mux.HandleFunc("GET /api/accounts/import/chrome", s.handleChromeImportProfiles) + mux.HandleFunc("POST /api/accounts/import/chrome/tiers", s.handleCheckChromeImportTiers) mux.HandleFunc("POST /api/accounts/import/chrome", s.handleImportChromeAccounts) mux.HandleFunc("GET /api/accounts/import/browsers", s.handleCookieBrowsers) mux.HandleFunc("POST /api/accounts/import/cookies/discover", s.handleDiscoverCookieAccounts) @@ -415,8 +449,10 @@ func (s *server) registerAdmin(mux *http.ServeMux) { mux.HandleFunc("PUT /api/accounts/{id}/state", s.handleSetAccountState) mux.HandleFunc("DELETE /api/accounts/{id}", s.handleDeleteAccount) mux.HandleFunc("POST /api/accounts/{id}/login", s.handleLoginAccount) + mux.HandleFunc("POST /api/accounts/{id}/verify", s.handleVerifyAccount) mux.HandleFunc("GET /api/login-view/{view}", s.handleLoginView) mux.HandleFunc("POST /api/accounts/{id}/refresh", s.handleRefreshAccount) + 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/camoufox/download", s.handleDownloadCamoufox) @@ -481,6 +517,43 @@ func (s *server) handleChromeImportProfiles(w http.ResponseWriter, r *http.Reque writeJSON(w, http.StatusOK, map[string][]ChromeImportProfile{"profiles": profiles}) } +// handleCheckChromeImportTiers 流式按行输出所选 Chrome 账号的权益检测结果(NDJSON),每完成一个账号即刷新到客户端 +func (s *server) handleCheckChromeImportTiers(w http.ResponseWriter, r *http.Request) { + var input ChromeTierCheckInput + if err := decodeJSON(r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + if len(input.AccountIDs) == 0 { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "未选择 Chrome 账号") + return + } + flusher, _ := w.(http.Flusher) + started := false + err := s.config.Admin.CheckChromeImportTiers(r.Context(), input, func(item ChromeProfileTier) { + if !started { + started = true + w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.WriteHeader(http.StatusOK) + } + if line, marshalErr := json.Marshal(item); marshalErr == nil { + _, _ = w.Write(append(line, '\n')) + if flusher != nil { + flusher.Flush() + } + } + }) + if err != nil && !started { + writeAdminUpstreamError(w, err) + return + } + if !started { + w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8") + w.WriteHeader(http.StatusOK) + } +} + func (s *server) handleCookieBrowsers(w http.ResponseWriter, r *http.Request) { browsers, err := s.config.Admin.CookieBrowsers(r.Context(), r.URL.Query().Get("proxy")) if err != nil { diff --git a/internal/api/anthropic.go b/internal/api/anthropic.go index 612d0fa0..92ec62fc 100644 --- a/internal/api/anthropic.go +++ b/internal/api/anthropic.go @@ -1,6 +1,7 @@ package api import ( + "bytes" "encoding/json" "fmt" "net/http" @@ -63,6 +64,10 @@ func (request anthropicRequest) thinkingOmitted() bool { type anthropicMessage struct { Role string `json:"role"` Content json.RawMessage `json:"content"` + // OutputConfig 是对话中途 system 消息改变的输出设置,effort 作用于之后的轮次 + OutputConfig *struct { + Effort string `json:"effort"` + } `json:"output_config"` } type anthropicTool struct { @@ -123,6 +128,7 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request) return } generateRequest, err := request.toGenerateRequest(messageID) + request.Messages, request.System = nil, nil if err == nil { generateRequest, err = s.resolveMCPTools(r.Context(), generateRequest) } @@ -301,6 +307,7 @@ func (s *server) countAnthropicTokens(w http.ResponseWriter, r *http.Request, re var generateRequest aistudio.GenerateRequest if err == nil { generateRequest, err = request.toGenerateRequest(newID("count")) + request.Messages, request.System = nil, nil } if err == nil { generateRequest, err = s.resolveMCPTools(r.Context(), generateRequest) @@ -350,10 +357,18 @@ func (request anthropicRequest) toGenerateRequest(id string) (aistudio.GenerateR for _, tool := range request.Tools { known[tool.Name] = tool } + messageEffort := "" for _, message := range request.Messages { + message.Content, declared, err = anthropicToolChanges(message.Content, declared, known) + if err != nil { + return aistudio.GenerateRequest{}, fmt.Errorf("%s message: %w", message.Role, err) + } if message.Role == "system" { + if message.OutputConfig != nil && message.OutputConfig.Effort != "" { + messageEffort = message.OutputConfig.Effort + } var text string - text, declared, err = anthropicSystemMessage(message.Content, declared, known) + text, err = anthropicSystemText(message.Content) if err != nil { return aistudio.GenerateRequest{}, fmt.Errorf("system message: %w", err) } @@ -404,11 +419,16 @@ func (request anthropicRequest) toGenerateRequest(id string) (aistudio.GenerateR } format := request.OutputFormat if request.OutputConfig != nil { - config.ReasoningEffort = request.OutputConfig.Effort + if request.OutputConfig.Effort != "" && config.ReasoningEffort != "none" { + config.ReasoningEffort = request.OutputConfig.Effort + } if request.OutputConfig.Format != nil { format = request.OutputConfig.Format } } + if messageEffort != "" && config.ReasoningEffort != "none" { + config.ReasoningEffort = messageEffort + } if format != nil { if format.Type != "json_schema" { return aistudio.GenerateRequest{}, fmt.Errorf("unsupported output format type %q", format.Type) @@ -447,48 +467,61 @@ func anthropicSystemText(raw json.RawMessage) (string, error) { return strings.Join(texts, "\n"), nil } -// anthropicSystemMessage 读取对话中途 system 消息的文本,并按其中的 tool_addition 与 tool_removal 更新声明的工具:按定义加入的工具记入 known,按名称引用的工具从 known 恢复,已声明的工具不重复声明 -func anthropicSystemMessage(raw json.RawMessage, tools []anthropicTool, known map[string]anthropicTool) (string, []anthropicTool, error) { - var text string - if err := json.Unmarshal(raw, &text); err == nil { - return text, tools, nil - } - var blocks []struct { - Type string `json:"type"` - Text string `json:"text"` - Tool struct { - Type string `json:"type"` - Name string `json:"name"` - Definition anthropicTool `json:"definition"` - } `json:"tool"` +// anthropicToolChange 是 tool_addition 与 tool_removal 块中的一个工具:tool_definition 带定义,tool_reference 与移除只带名称 +type anthropicToolChange struct { + Type string `json:"type"` + Name string `json:"name"` + Definition anthropicTool `json:"definition"` +} + +// anthropicToolChanges 按消息内容中的 tool_addition 与 tool_removal 块更新声明的工具并返回其余内容块,块以 tool 给出一个工具或以 tools 给出多个;按定义加入的工具记入 known,按名称引用的工具从 known 恢复,已声明的工具不重复声明 +func anthropicToolChanges(raw json.RawMessage, tools []anthropicTool, known map[string]anthropicTool) (json.RawMessage, []anthropicTool, error) { + if !bytes.Contains(raw, []byte("tool_addition")) && !bytes.Contains(raw, []byte("tool_removal")) && !bytes.Contains(raw, []byte(`\u`)) { + return raw, tools, nil } + var blocks []json.RawMessage if err := json.Unmarshal(raw, &blocks); err != nil { - return "", nil, fmt.Errorf("content must be a string or block array") + return raw, tools, nil } - texts := make([]string, 0, len(blocks)) - for _, block := range blocks { - switch block.Type { - case "text": - if block.Text != "" { - texts = append(texts, block.Text) + kept := make([]json.RawMessage, 0, len(blocks)) + for _, rawBlock := range blocks { + var block struct { + Type string `json:"type"` + Tool *anthropicToolChange `json:"tool"` + Tools []anthropicToolChange `json:"tools"` + } + if err := json.Unmarshal(rawBlock, &block); err != nil { + return nil, nil, err + } + if block.Type != "tool_addition" && block.Type != "tool_removal" { + kept = append(kept, rawBlock) + continue + } + changes := block.Tools + if block.Tool != nil { + changes = append(changes, *block.Tool) + } + for _, change := range changes { + if block.Type == "tool_removal" { + tools = slices.DeleteFunc(slices.Clone(tools), func(tool anthropicTool) bool { return tool.Name == change.Name }) + continue } - case "tool_addition": - tool, ok := block.Tool.Definition, block.Tool.Type == "tool_definition" + tool, ok := change.Definition, change.Type == "tool_definition" if ok { known[tool.Name] = tool - } else if block.Tool.Type == "tool_reference" { - tool, ok = known[block.Tool.Name] + } else if change.Type == "tool_reference" { + tool, ok = known[change.Name] } if ok && !slices.ContainsFunc(tools, func(declared anthropicTool) bool { return declared.Name == tool.Name }) { tools = append(slices.Clip(tools), tool) } - case "tool_removal": - tools = slices.DeleteFunc(slices.Clone(tools), func(tool anthropicTool) bool { return tool.Name == block.Tool.Name }) - default: - return "", nil, fmt.Errorf("unsupported system block type %q", block.Type) } } - return strings.Join(texts, "\n"), tools, nil + if len(kept) == len(blocks) { + return raw, tools, nil + } + content, err := json.Marshal(kept) + return content, tools, err } func anthropicRole(role string) (aistudio.Role, error) { @@ -514,7 +547,7 @@ type anthropicPartBlock struct { Content json.RawMessage `json:"content"` IsError bool `json:"is_error"` Signature string `json:"signature"` - Source json.RawMessage `json:"source"` + Source jsonSlice `json:"source"` Title string `json:"title"` Context string `json:"context"` FileID string `json:"file_id"` @@ -556,7 +589,9 @@ func anthropicParts(raw json.RawMessage) ([]aistudio.Part, error) { parts = append(parts, aistudio.Part{ThoughtSignature: pendingSignature}) pendingSignature = "" } - for _, block := range blocks { + for index := range blocks { + block := blocks[index] + blocks[index] = anthropicPartBlock{} switch block.Type { case "text": if block.Text == "" { @@ -575,13 +610,13 @@ func anthropicParts(raw json.RawMessage) ([]aistudio.Part, error) { pendingSignature = block.Data case "image", "document": flushPendingSignature() - if !rawJSONConfigured(block.Source) { + if !rawJSONConfigured(json.RawMessage(block.Source)) { return nil, fmt.Errorf("%s source is required", block.Type) } var source struct { Type string `json:"type"` MediaType string `json:"media_type"` - Data string `json:"data"` + Data jsonSlice `json:"data"` URL string `json:"url"` FileID string `json:"file_id"` Content json.RawMessage `json:"content"` @@ -589,12 +624,18 @@ func anthropicParts(raw json.RawMessage) ([]aistudio.Part, error) { if err := json.Unmarshal(block.Source, &source); err != nil { return nil, fmt.Errorf("%s source: %w", block.Type, err) } + block.Source = nil if block.Context != "" { parts = append(parts, aistudio.Part{Text: block.Context}) } switch source.Type { case "base64": - data, err := decodeBase64Flexible(source.Data) + rawData, err := source.Data.stringBytes() + source.Data = nil + if err != nil { + return nil, fmt.Errorf("%s source data: %w", block.Type, err) + } + data, err := decodeBase64Bytes(rawData) if err != nil { return nil, fmt.Errorf("%s source data: %w", block.Type, err) } @@ -610,8 +651,14 @@ func anthropicParts(raw json.RawMessage) ([]aistudio.Part, error) { parts = append(parts, aistudio.Part{File: &aistudio.FileRef{ID: strings.TrimSpace(source.URL), MIME: source.MediaType}}) } case "text": - if source.Data != "" { - parts = append(parts, aistudio.Part{Text: source.Data}) + if source.Data.hasString() { + var text string + if err := json.Unmarshal(source.Data, &text); err != nil { + return nil, fmt.Errorf("%s source: %w", block.Type, err) + } + if text != "" { + parts = append(parts, aistudio.Part{Text: text}) + } } case "content": nested, err := anthropicParts(source.Content) @@ -1697,9 +1744,14 @@ func (writer *anthropicStreamWriter) finish(result generationResult) error { return writer.send("message_stop", map[string]string{"type": "message_stop"}) } +// error 写出流内错误事件,5xx 原因的错误类型为 Claude Code 流内会重试的 overloaded_error func (writer *anthropicStreamWriter) error(err error) error { + kind, status := anthropicErrorType(err), statusFromError(err) + if status >= http.StatusInternalServerError { + kind = "overloaded_error" + } return writer.send("error", map[string]any{ "type": "error", - "error": map[string]string{"type": anthropicErrorType(err), "message": retryMessage(publicErrorMessage(statusFromError(err), anthropicErrorMessage(err)), retryAfterSeconds(err))}, + "error": map[string]string{"type": kind, "message": retryMessage(publicErrorMessage(status, anthropicErrorMessage(err)), retryAfterSeconds(err))}, }) } diff --git a/internal/api/anthropic_context.go b/internal/api/anthropic_context.go index 4c4dbc7e..bf60829e 100644 --- a/internal/api/anthropic_context.go +++ b/internal/api/anthropic_context.go @@ -333,27 +333,15 @@ func (s *server) compactAnthropic(ctx context.Context, request anthropicRequest, if instructions == "" { instructions = anthropicCompactionPrompt } - summarize := *generate - summarize.Contents = append(slices.Clone(generate.Contents), aistudio.Content{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: instructions}}}) - summarize.Tools.ToolConfig.Mode = "none" - summarize.Unary = true - events, err := s.service.Generate(ctx, summarize) + summary, usage, err := s.generateCompactionSummary(ctx, *generate, instructions) if err != nil { return nil, err } - result, err := consumeEvents(ctx, events) - if err != nil { - return nil, err - } - if result.finishReason != "stop" { - return nil, fmt.Errorf("compaction summary finished with %s", result.finishReason) - } - summary := strings.TrimSpace(result.text.String()) if start, end := strings.Index(summary, ""), strings.LastIndex(summary, ""); start >= 0 && end > start { summary = strings.TrimSpace(summary[start+len("") : end]) } generate.Contents = []aistudio.Content{{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: fmt.Sprintf(compactionSummaryContext, summary)}}}} - return &anthropicCompaction{summary: summary, usage: result.usage, pause: edit.PauseAfterCompaction}, nil + return &anthropicCompaction{summary: summary, usage: usage, pause: edit.PauseAfterCompaction}, nil } // block 返回压缩摘要的 compaction 内容块 diff --git a/internal/api/anthropic_search.go b/internal/api/anthropic_search.go index 6da15108..a5f7e653 100644 --- a/internal/api/anthropic_search.go +++ b/internal/api/anthropic_search.go @@ -104,11 +104,10 @@ func (s *server) decodeAnthropicSearchHistory(request *anthropicRequest) error { continue } var heads []anthropicSearchHead - searched := bytes.Contains(message.Content, []byte(`"server_tool_use"`)) || bytes.Contains(message.Content, []byte(`"web_search_tool_result"`)) + searched := bytes.Contains(message.Content, []byte(`"server_tool_use"`)) || bytes.Contains(message.Content, []byte(`"web_search_tool_result"`)) || bytes.Contains(message.Content, []byte(`\u`)) if !searched || json.Unmarshal(message.Content, &heads) == nil && !slices.ContainsFunc(heads, func(head anthropicSearchHead) bool { return head.Type == "server_tool_use" || head.Type == "web_search_tool_result" }) { - message.Content, _ = json.Marshal(message.Content) continue } var blocks []json.RawMessage diff --git a/internal/api/client_tools.go b/internal/api/client_tools.go index 664d11ca..63e13953 100644 --- a/internal/api/client_tools.go +++ b/internal/api/client_tools.go @@ -133,6 +133,10 @@ func responsesToolKind(tools []responsesTool, name string) string { if name == "computer" { return tool.Type } + case "tool_search": + if tool.Execution == "client" && name == clientToolSearch { + return "tool_search" + } case "namespace": for _, inner := range tool.Tools { if inner.Type == "custom" && namespacedName(tool.Name, inner.Name) == name { diff --git a/internal/api/errors.go b/internal/api/errors.go index dd2f549e..2911cf5e 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -27,7 +27,7 @@ type errorCodeProvider interface { ErrorCode() string } -// readRequestBody 读取请求正文,已知 ContentLength 时在上限内预分配缓冲 +// readRequestBody 读取请求正文,已知 ContentLength 时先在 maxPrealloc 内预分配,读满后再按实际长度一次性扩容,避免大请求体倍增拷贝 func readRequestBody(r *http.Request, maxPrealloc int64) ([]byte, error) { if r.ContentLength <= 0 || maxPrealloc <= 0 { return io.ReadAll(r.Body) @@ -35,7 +35,13 @@ func readRequestBody(r *http.Request, maxPrealloc int64) ([]byte, error) { buf := make([]byte, 0, min(r.ContentLength, maxPrealloc)+1) for { if len(buf) == cap(buf) { - buf = append(buf, 0)[:len(buf)] + if target := r.ContentLength + 1; int64(cap(buf)) < target && r.ContentLength <= maxPublicBodyBytes { + grown := make([]byte, len(buf), target) + copy(grown, buf) + buf = grown + } else { + buf = append(buf, 0)[:len(buf)] + } } n, err := r.Body.Read(buf[len(buf):cap(buf)]) buf = buf[:len(buf)+n] @@ -239,6 +245,18 @@ func writeRouteNotFound(w http.ResponseWriter, r *http.Request) { } } +// writeRequestBodyError 以请求所属协议的错误体返回请求体无法读取的错误 +func writeRequestBodyError(w http.ResponseWriter, r *http.Request, status int, message string) { + switch requestProtocol(r) { + case "gemini": + writeGeminiError(w, status, "INVALID_ARGUMENT", message) + case "anthropic": + writeAnthropicError(w, status, "invalid_request_error", message) + default: + writeOpenAIError(w, status, "invalid_request", message) + } +} + // geminiInvalidKeyMessage 是 Gemini API 对无效 API key 的错误信息 const geminiInvalidKeyMessage = "API key not valid. Please pass a valid API key." @@ -415,7 +433,7 @@ type openAIErrorBody struct { } func openAIErrorType(status int, code string) string { - if status == http.StatusBadRequest || status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusNotFound { + if status == http.StatusBadRequest || status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusNotFound || status == http.StatusUnsupportedMediaType { return "invalid_request_error" } if code == "rate_limit_exceeded" { diff --git a/internal/api/gemini.go b/internal/api/gemini.go index b403c273..53240e34 100644 --- a/internal/api/gemini.go +++ b/internal/api/gemini.go @@ -702,6 +702,27 @@ func geminiJSONName(name string) string { return builder.String() } +// geminiSystemParts 把系统指令中的 part 分为指令文本与移到首个 user 轮开头的媒体,函数调用与结果转录为文本 +func geminiSystemParts(parts []aistudio.Part) ([]string, []aistudio.Part, error) { + var texts []string + var media []aistudio.Part + for _, part := range parts { + switch { + case part.FunctionCall != nil || part.FunctionResult != nil: + transcript, err := aistudio.ToolPartTranscript(part) + if err != nil { + return nil, nil, err + } + texts = append(texts, transcript) + case part.Text != "": + texts = append(texts, part.Text) + case part.InlineData != nil || part.File != nil || part.ExternalMedia != nil: + media = append(media, part) + } + } + return texts, media, nil +} + func (request geminiRequest) toGenerateRequest(id string, model string) (aistudio.GenerateRequest, error) { if err := request.GenerationConfig.validate(); err != nil { return aistudio.GenerateRequest{}, err @@ -713,24 +734,14 @@ func (request geminiRequest) toGenerateRequest(id string, model string) (aistudi if err != nil { return aistudio.GenerateRequest{}, fmt.Errorf("systemInstruction: %w", err) } - for _, part := range parts { - if part.FunctionCall != nil || part.FunctionResult != nil { - transcript, err := aistudio.ToolPartTranscript(part) - if err != nil { - return aistudio.GenerateRequest{}, fmt.Errorf("systemInstruction: %w", err) - } - system = append(system, transcript) - continue - } - if part.Text == "" && (part.InlineData != nil || part.File != nil || part.ExternalMedia != nil) { - systemMedia = append(systemMedia, part) - } - if part.Text != "" { - system = append(system, part.Text) - } + texts, media, err := geminiSystemParts(parts) + if err != nil { + return aistudio.GenerateRequest{}, fmt.Errorf("systemInstruction: %w", err) } + system, systemMedia = texts, media } contents := make([]aistudio.Content, 0, len(request.Contents)) + var reminders []aistudio.Part for _, content := range request.Contents { parts, hasResult, err := mapGeminiParts(content.Parts) if err != nil { @@ -739,6 +750,19 @@ func (request geminiRequest) toGenerateRequest(id string, model string) (aistudi if len(parts) == 0 { continue } + if content.Role == "system" || content.Role == "developer" { + texts, media, err := geminiSystemParts(parts) + if err != nil { + return aistudio.GenerateRequest{}, fmt.Errorf("%s content: %w", content.Role, err) + } + systemMedia = append(systemMedia, media...) + if len(contents) == 0 { + system = append(system, texts...) + } else if len(texts) > 0 { + reminders = addSystemReminder(contents, reminders, strings.Join(texts, "\n")) + } + continue + } role, err := geminiRole(content.Role) if err != nil { return aistudio.GenerateRequest{}, err @@ -746,7 +770,10 @@ func (request geminiRequest) toGenerateRequest(id string, model string) (aistudi if hasResult { role = aistudio.RoleTool } - contents = append(contents, aistudio.Content{Role: role, Parts: parts}) + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: role, Parts: parts}, reminders) + } + if len(reminders) > 0 { + contents = append(contents, aistudio.Content{Role: aistudio.RoleUser, Parts: reminders}) } contents = prependSystemMedia(contents, systemMedia) tools, err := mapGeminiTools(request.Tools, request.ToolConfig) @@ -1781,6 +1808,7 @@ func geminiUsage(usage *aistudio.Usage) geminiUsageMetadata { type geminiStream struct { w http.ResponseWriter keepalive *streamKeepalive + bareError bool mu sync.Mutex written bool } @@ -1789,7 +1817,7 @@ type geminiStream struct { func openGeminiStream(w http.ResponseWriter, r *http.Request) (*geminiStream, error) { if r.URL.Query().Get("alt") == "sse" { keepalive, err := openStream(w, geminiHeartbeat) - return &geminiStream{w: keepalive, keepalive: keepalive}, err + return &geminiStream{w: keepalive, keepalive: keepalive, bareError: geminiBareStreamError(r)}, err } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.Header().Set("Cache-Control", "no-cache") @@ -1798,6 +1826,32 @@ func openGeminiStream(w http.ResponseWriter, r *http.Request) (*geminiStream, er return &geminiStream{w: w}, http.NewResponseController(w).Flush() } +// geminiBareStreamError 判断客户端是否为只识别裸 JSON 流内错误的旧版 JS @google/genai(< 3.2) +func geminiBareStreamError(r *http.Request) bool { + if r == nil { + return false + } + client := strings.Join(r.Header.Values("X-Goog-Api-Client"), " ") + if !strings.Contains(client, "google-genai-sdk/") { + client = r.Header.Get("User-Agent") + } + if !strings.Contains(client, "gl-node/") { + return false + } + _, rest, ok := strings.Cut(client, "google-genai-sdk/") + if !ok { + return false + } + version, _, _ := strings.Cut(rest, " ") + parts := strings.SplitN(version, ".", 3) + if len(parts) < 2 { + return false + } + major, err1 := strconv.Atoi(parts[0]) + minor, err2 := strconv.Atoi(parts[1]) + return err1 == nil && err2 == nil && (major < 3 || (major == 3 && minor < 2)) +} + // write 写出一个响应块 func (stream *geminiStream) write(value map[string]any) error { data, err := json.Marshal(officialOrder("gemini", value)) @@ -1844,9 +1898,9 @@ func (stream *geminiStream) writeJSON(data []byte) error { return http.NewResponseController(stream.w).Flush() } -// fail 写出流内错误:SSE 按官方 SDK 的解析方式写成不带 data: 前缀的整块 JSON,JSON 数组中写为一个元素 +// fail 写出流内错误:SSE 默认写为标准 data: 帧以便标准 SSE 客户端与新版 SDK 解析,旧版 JS @google/genai(< 3.2)不检查 data: 帧内的 error 字段故写为裸 JSON,JSON 数组中写为一个元素 func (stream *geminiStream) fail(value map[string]any) error { - if stream.keepalive == nil { + if stream.keepalive == nil || !stream.bareError { return stream.write(value) } data, err := json.Marshal(officialOrder("gemini", value)) diff --git a/internal/api/generate.go b/internal/api/generate.go index d6a1d1fe..dfe359e7 100644 --- a/internal/api/generate.go +++ b/internal/api/generate.go @@ -233,12 +233,19 @@ func providerFinishReason(reason string) string { // addSystemReminder 把对话中途的系统消息以 system-reminder 追加到上一个 user 轮,上一轮不是 user 时返回待并入下一个 user 轮的 reminder func addSystemReminder(contents []aistudio.Content, pending []aistudio.Part, text string) []aistudio.Part { - reminder := aistudio.Part{Text: "\n" + text + "\n"} + return addSystemReminderParts(contents, pending, []aistudio.Part{{Text: "\n" + text + "\n"}}) +} + +// addSystemReminderParts 把对话中途的系统提醒内容追加到上一个 user 轮,上一轮不是 user 时返回待并入下一个 user 轮的片段 +func addSystemReminderParts(contents []aistudio.Content, pending []aistudio.Part, parts []aistudio.Part) []aistudio.Part { + if len(parts) == 0 { + return pending + } if last := len(contents) - 1; last >= 0 && contents[last].Role == aistudio.RoleUser { - contents[last].Parts = append(contents[last].Parts, reminder) + contents[last].Parts = append(contents[last].Parts, parts...) return pending } - return append(pending, reminder) + return append(pending, parts...) } // appendWithReminders 追加一条消息,待并入的 reminder 排在下一个 user 消息的函数结果之后 @@ -275,7 +282,10 @@ var functionResultMediaTypes = map[string]bool{ "image_url": true, "input_image": true, "input_file": true, "input_audio": true, "video_url": true, "input_video": true, } -// functionResultParts 把工具结果转成函数结果内容与紧随其后的媒体 part,文本块以换行相连作为结果文本,isError 时结果写在 error 键下 +// functionResultMediaPayloads 是媒体块中承载内容的字段,单个对象带其中之一时才按媒体块处理 +var functionResultMediaPayloads = []string{"image_url", "file_id", "file_data", "file_url", "input_audio", "video_url", "source", "data", "uri"} + +// functionResultParts 把工具结果转成函数结果内容与紧随其后的媒体 part,文本块以换行相连作为结果文本,类型与内容字段都是媒体块的单个对象按只含它的块数组处理,isError 时结果写在 error 键下 func functionResultParts(raw json.RawMessage, isError bool, parse func(json.RawMessage) ([]aistudio.Part, error)) (json.RawMessage, []aistudio.Part, error) { key := "result" if isError { @@ -283,7 +293,15 @@ func functionResultParts(raw json.RawMessage, isError bool, parse func(json.RawM } trimmed := bytes.TrimSpace(raw) var blocks []json.RawMessage - if bytes.HasPrefix(trimmed, []byte("[")) && json.Unmarshal(raw, &blocks) == nil && len(blocks) > 0 { + var single struct { + Type string `json:"type"` + } + var fields map[string]json.RawMessage + if bytes.HasPrefix(trimmed, []byte("{")) && json.Unmarshal(raw, &single) == nil && functionResultMediaTypes[single.Type] && json.Unmarshal(raw, &fields) == nil && + slices.ContainsFunc(functionResultMediaPayloads, func(name string) bool { return fields[name] != nil }) { + blocks = []json.RawMessage{raw} + } + if len(blocks) > 0 || bytes.HasPrefix(trimmed, []byte("[")) && json.Unmarshal(raw, &blocks) == nil && len(blocks) > 0 { var texts []string var media []aistudio.Part contentBlocks := true diff --git a/internal/api/interaction_input.go b/internal/api/interaction_input.go index 5420b0b3..e9b1bceb 100644 --- a/internal/api/interaction_input.go +++ b/internal/api/interaction_input.go @@ -62,6 +62,8 @@ type interactionRequest struct { stream *streamLog // cache 是 cached_content 引用的显式缓存 cache *geminiCache + // inputSteps 是提前整理好的输入步骤,避免生成期间整份持有原始 Input JSON + inputSteps []json.RawMessage } // interactionAgentConfig 是公开请求的 agent_config,max_total_tokens 按官方 REST 为字符串,也接受数字 @@ -239,7 +241,7 @@ type interactionFormat struct { type interactionInput struct { Type string `json:"type"` Text *string `json:"text"` - Data string `json:"data"` + Data jsonSlice `json:"data"` URI string `json:"uri"` MIME string `json:"mime_type"` Processing json.RawMessage `json:"processing"` @@ -570,7 +572,9 @@ func interactionContents(raw json.RawMessage) ([]aistudio.Content, error) { pendingSignature := "" // mcpFunctions 记录按函数调用发送的 MCP 调用 ID 与函数名 mcpFunctions := map[string]string{} - for _, item := range items { + for index := range items { + item := items[index] + items[index] = interactionInput{} role := aistudio.RoleUser var parts []aistudio.Part switch item.Type { @@ -578,7 +582,9 @@ func interactionContents(raw json.RawMessage) ([]aistudio.Content, error) { if item.Type == "model_output" { role = aistudio.RoleAssistant } - for _, content := range item.Content { + for contentIndex := range item.Content { + content := item.Content[contentIndex] + item.Content[contentIndex] = interactionInput{} mapped, mapErr := content.parts() if mapErr != nil { return nil, mapErr @@ -682,25 +688,41 @@ func (content interactionInput) parts() ([]aistudio.Part, error) { } } case "image", "audio", "video", "document": - if (content.Data == "") == (content.URI == "") { + hasData := content.Data.hasString() + if hasData == (content.URI != "") { return nil, fmt.Errorf("%s content requires exactly one of data or uri", content.Type) } - if content.Data != "" { + if hasData { + rawData, err := content.Data.stringBytes() + content.Data = nil + if err != nil { + return nil, fmt.Errorf("%s data: %w", content.Type, err) + } + data, err := decodeBase64Bytes(rawData) + if err != nil { + return nil, fmt.Errorf("%s data: %w", content.Type, err) + } mimeType := content.MIME if mimeType == "" { - data, err := decodeBase64Flexible(content.Data) - if err != nil { - return nil, fmt.Errorf("%s data: %w", content.Type, err) - } mimeType = detectMediaType("", data) if mimeType == "application/octet-stream" { return nil, fmt.Errorf("%s content requires mime_type", content.Type) } } - part.InlineData = &geminiBlobPart{MIMEType: content.audioMIME(mimeType), Data: content.Data, DisplayName: content.Name} - } else { - part.FileData = &geminiFilePart{MIMEType: content.audioMIME(content.MIME), FileURI: content.URI, DisplayName: content.Name} - } + mediaType, data := normalizeImagePayload(attachmentMIME(content.audioMIME(mimeType), content.Name, data), data) + resolution := "" + if part.MediaResolution != nil { + resolution = part.MediaResolution.Level + } + return []aistudio.Part{{ + InlineData: aistudio.NewBlob(mediaType, data), + VideoMetadata: (*aistudio.VideoMetadata)(part.VideoMetadata), + MediaProcessing: part.MediaProcessing, + DisplayName: content.Name, + MediaResolution: resolution, + }}, nil + } + part.FileData = &geminiFilePart{MIMEType: content.audioMIME(content.MIME), FileURI: content.URI, DisplayName: content.Name} default: return nil, fmt.Errorf("unsupported input type %q", content.Type) } @@ -835,8 +857,10 @@ 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/mpeg" && encoding.format == "pcm" && sameRate: + case baseType == "audio/l16" && 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 dffa5f16..d4a9c084 100644 --- a/internal/api/interaction_resources.go +++ b/internal/api/interaction_resources.go @@ -64,7 +64,11 @@ func (s *server) storeInteraction(request interactionRequest, previous responseH return } id, _ := object["id"].(string) - interaction := &interactionRecord{object: encoded, input: interactionInputSteps(request.Input), upstream: result.interactionID, account: result.accountID, agent: result.providerModel, stream: request.stream} + inputSteps := request.inputSteps + if inputSteps == nil && len(request.Input) > 0 { + inputSteps = interactionInputSteps(request.Input) + } + interaction := &interactionRecord{object: encoded, input: inputSteps, upstream: result.interactionID, account: result.accountID, agent: result.providerModel, stream: request.stream} s.responseStates.Store(id, previous, result, responseState{Contents: current, Interaction: interaction}) } @@ -157,11 +161,11 @@ 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 value, ok := s.background.Load(id); ok { - run := value.(backgroundRun) - run.cancel() - <-run.done + if _, ok := s.responseStates.Interaction(id); !ok { + writeInteractionNotFound(w, id) + return } + s.stopBackground(id) record, ok := s.responseStates.Interaction(id) if !ok { writeInteractionNotFound(w, id) diff --git a/internal/api/interactions.go b/internal/api/interactions.go index 07fb7dc7..db999b50 100644 --- a/internal/api/interactions.go +++ b/internal/api/interactions.go @@ -34,6 +34,11 @@ func (s *server) handleInteraction(w http.ResponseWriter, r *http.Request) { writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) return } + stores := request.Store == nil || *request.Store + if stores { + request.inputSteps = interactionInputSteps(request.Input) + } + request.Input = nil if err := resolveGeminiFileNames(r.Context(), s.service, generate.Contents); err != nil { if shouldWriteRequestError(r, err) { writeGeminiRequestError(w, err) @@ -54,7 +59,10 @@ func (s *server) handleInteraction(w http.ResponseWriter, r *http.Request) { w, stopKeepalive = s.nonstreamKeepalive(w, r) defer stopKeepalive() } - current := cloneResponseContents(generate.Contents) + var current []aistudio.Content + if stores { + current = cloneResponseContents(generate.Contents) + } var previous responseHistory if request.PreviousID != "" { var ok bool diff --git a/internal/api/mcp_tools.go b/internal/api/mcp_tools.go index e3a2ac10..d9443f56 100644 --- a/internal/api/mcp_tools.go +++ b/internal/api/mcp_tools.go @@ -313,13 +313,12 @@ func (s *server) mcpApprovalTools(ctx context.Context, tools []responsesTool, ch return request, err } if allowed != nil { - names, ok := restricted[server.Name] - if !ok { + var ok bool + if server, ok = restrictMCPServer(server, restricted); !ok { continue } - if names != nil { - server.AllowedTools = names - } + } else if server.AllowedTools != nil && len(server.AllowedTools) == 0 { + continue } listed, err := s.listMCPTools(ctx, server) if err != nil { diff --git a/internal/api/media.go b/internal/api/media.go index 2ed26b70..8ca592ac 100644 --- a/internal/api/media.go +++ b/internal/api/media.go @@ -6,6 +6,7 @@ import ( "context" "encoding/base64" "encoding/binary" + "encoding/json" "errors" "fmt" "image" @@ -729,20 +730,69 @@ func wavPCM(media aistudio.Blob) (aistudio.Blob, error) { return aistudio.Blob{MIME: fmt.Sprintf("audio/l16;rate=%d;channels=%d", rate, channels), Data: pcm}, nil } -// decodeBase64Flexible 根据字母表和填充形式解码 Base64 与 Data URL -func decodeBase64Flexible(s string) ([]byte, error) { - s = strings.TrimSpace(s) - if idx := strings.Index(s, ","); idx != -1 && strings.HasPrefix(s, "data:") { - s = s[idx+1:] +// jsonSlice 在局部解码时零拷贝引用父 JSON 字节片段,避免大附件被重复拷贝 +type jsonSlice []byte + +// UnmarshalJSON 直接记录输入切片,不分配新缓冲 +func (slice *jsonSlice) UnmarshalJSON(data []byte) error { + *slice = data + return nil +} + +// hasValue 返回字段是否包含非空且非 null 的 JSON 值 +func (slice jsonSlice) hasValue() bool { + trimmed := bytes.TrimSpace(slice) + return len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null")) +} + +// hasString 返回字段是否包含非空 JSON 字符串;非字符串值返回 true 交由后续解码报类型错误 +func (slice jsonSlice) hasString() bool { + trimmed := bytes.TrimSpace(slice) + return len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null")) && !bytes.Equal(trimmed, []byte(`""`)) +} + +// stringBytes 返回 JSON 字符串的内容字节,不含反斜杠转义时零拷贝切片返回,null 返回 nil +func (slice jsonSlice) stringBytes() ([]byte, error) { + trimmed := bytes.TrimSpace(slice) + if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { + return nil, nil + } + if len(trimmed) >= 2 && trimmed[0] == '"' && trimmed[len(trimmed)-1] == '"' && bytes.IndexByte(trimmed[1:len(trimmed)-1], '\\') < 0 { + return trimmed[1 : len(trimmed)-1], nil + } + var value string + if err := json.Unmarshal(trimmed, &value); err != nil { + return nil, err + } + return []byte(value), nil +} + +// decodeBase64Bytes 根据字母表和填充形式直接从字节切片解码 Base64 与 Data URL,不产生字符串副本 +func decodeBase64Bytes(raw []byte) ([]byte, error) { + raw = bytes.TrimSpace(raw) + if bytes.HasPrefix(raw, []byte("data:")) { + if idx := bytes.IndexByte(raw, ','); idx != -1 { + raw = raw[idx+1:] + } } encoding := base64.StdEncoding - if index := strings.IndexAny(s, "+/-_"); index >= 0 && (s[index] == '-' || s[index] == '_') { + if index := bytes.IndexAny(raw, "+/-_"); index >= 0 && (raw[index] == '-' || raw[index] == '_') { encoding = base64.URLEncoding } - if !strings.HasSuffix(s, "=") { + if !bytes.HasSuffix(raw, []byte("=")) { encoding = encoding.WithPadding(base64.NoPadding) } - return encoding.DecodeString(s) + dst := make([]byte, encoding.DecodedLen(len(raw))) + n, err := encoding.Decode(dst, raw) + if err != nil { + return nil, err + } + return dst[:n], nil +} + +// decodeBase64Flexible 根据字母表和填充形式解码 Base64 与 Data URL +func decodeBase64Flexible(s string) ([]byte, error) { + return decodeBase64Bytes([]byte(s)) } // normalizeImagePayload 将 GIF 首帧按逻辑画布转换为 PNG 图片 @@ -770,13 +820,16 @@ func normalizeImagePayload(mimeType string, data []byte) (string, []byte) { return mimeType, data } -// decodeGIFFrame 解码 GIF 的首帧与逻辑画布配置 +// maxGIFCanvasPixels 是 GIF 首帧转换允许的最大逻辑画布像素数 +const maxGIFCanvasPixels = 64_000_000 + +// decodeGIFFrame 解码 GIF 的首帧与逻辑画布配置,画布宽或高为 0 或像素数超过 maxGIFCanvasPixels 时返回 false func decodeGIFFrame(data []byte) (*image.Paletted, image.Config, bool) { - img, err := gif.Decode(bytes.NewReader(data)) - if err != nil { + config, err := gif.DecodeConfig(bytes.NewReader(data)) + if err != nil || config.Width <= 0 || config.Height <= 0 || int64(config.Width) > maxGIFCanvasPixels/int64(config.Height) { return nil, image.Config{}, false } - config, err := gif.DecodeConfig(bytes.NewReader(data)) + img, err := gif.Decode(bytes.NewReader(data)) if err != nil { return nil, image.Config{}, false } diff --git a/internal/api/middleware.go b/internal/api/middleware.go index 212a74b8..2bdede4c 100644 --- a/internal/api/middleware.go +++ b/internal/api/middleware.go @@ -4,6 +4,8 @@ import ( "context" "crypto/subtle" "errors" + "fmt" + "io" "net" "net/http" "net/url" @@ -15,6 +17,8 @@ import ( "unicode/utf8" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/klauspost/compress/gzip" + "github.com/klauspost/compress/zstd" ) type accessLogContextKey struct{} @@ -435,7 +439,7 @@ func corsMiddleware(next http.Handler) http.Handler { w.Header().Set("Access-Control-Expose-Headers", "*") if r.Method == http.MethodOptions { w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers")) - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") w.WriteHeader(http.StatusNoContent) return } @@ -500,6 +504,47 @@ func bodyLimitMiddleware(next http.Handler) http.Handler { }) } +// requestEncodingMiddleware 按 Content-Encoding 依次解压 gzip 与 zstd 请求体,解压后的正文同样受公开接口请求体上限约束,不支持的编码返回 415 +func requestEncodingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + header := strings.Join(r.Header.Values("Content-Encoding"), ",") + if header == "" { + next.ServeHTTP(w, r) + return + } + encodings := strings.Split(header, ",") + var body io.Reader = r.Body + for index := len(encodings) - 1; index >= 0; index-- { + switch encoding := strings.ToLower(strings.TrimSpace(encodings[index])); encoding { + case "", "identity": + case "gzip", "x-gzip": + reader, err := gzip.NewReader(body) + if err != nil { + writeRequestBodyError(w, r, http.StatusBadRequest, fmt.Sprintf("invalid gzip request body: %v", err)) + return + } + defer reader.Close() + body = reader + case "zstd": + decoder, err := zstd.NewReader(body, zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(uint64(maxPublicBodyBytes))) + if err != nil { + writeRequestBodyError(w, r, http.StatusBadRequest, fmt.Sprintf("invalid zstd request body: %v", err)) + return + } + defer decoder.Close() + body = decoder + default: + writeRequestBodyError(w, r, http.StatusUnsupportedMediaType, fmt.Sprintf("unsupported Content-Encoding %q", encoding)) + return + } + } + r.Body = http.MaxBytesReader(w, io.NopCloser(body), maxPublicBodyBytes) + r.Header.Del("Content-Encoding") + r.ContentLength = -1 + next.ServeHTTP(w, r) + }) +} + func sameOriginMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Sec-Fetch-Site") == "cross-site" { diff --git a/internal/api/openai.go b/internal/api/openai.go index 79a8734d..bc0ea7d8 100644 --- a/internal/api/openai.go +++ b/internal/api/openai.go @@ -243,6 +243,7 @@ func (s *server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { requestID := newID("chatcmpl") s.resolveChatAudio(request.Messages) generateRequest, err := request.toGenerateRequest(requestID) + request.Messages = nil if err != nil { writeOpenAIError(w, http.StatusBadRequest, "invalid_request", err.Error()) return @@ -355,6 +356,7 @@ func (request *chatRequest) mergeLegacyFunctions() error { func (request chatRequest) toGenerateRequest(id string) (aistudio.GenerateRequest, error) { var system []string contents := make([]aistudio.Content, 0, len(request.Messages)) + var reminders []aistudio.Part for _, message := range request.Messages { if message.Role == "system" || message.Role == "developer" { text, err := openAITextContent(message.Content) @@ -365,7 +367,11 @@ func (request chatRequest) toGenerateRequest(id string) (aistudio.GenerateReques text = message.Name + ": " + text } if text != "" { - system = append(system, text) + if len(contents) == 0 { + system = append(system, text) + } else { + reminders = addSystemReminder(contents, reminders, text) + } } continue } @@ -376,7 +382,10 @@ func (request chatRequest) toGenerateRequest(id string) (aistudio.GenerateReques if len(content.Parts) == 0 { continue } - contents = append(contents, content) + contents, reminders = appendWithReminders(contents, content, reminders) + } + if len(reminders) > 0 { + contents = append(contents, aistudio.Content{Role: aistudio.RoleUser, Parts: reminders}) } tools, err := mapOpenAITools(request.Tools, request.ToolChoice) if err != nil { @@ -553,8 +562,9 @@ func openAIContentParts(raw json.RawMessage) ([]aistudio.Part, error) { return nil, err } parts := make([]aistudio.Part, 0, len(blocks)) - for _, block := range blocks { - part, err := openAIContentPart(block) + for index := range blocks { + part, err := openAIContentPart(blocks[index]) + blocks[index] = openAIBlock{} if err != nil { return nil, err } @@ -571,134 +581,163 @@ var openAIDetailResolutions = map[string]string{"low": "MEDIA_RESOLUTION_LOW", " // openAIBlock 是 Chat 与 Responses 的内容块,image_url 与 video_url 为字符串或带 url 的对象 type openAIBlock struct { - Type string `json:"type"` - Text string `json:"text"` - Refusal string `json:"refusal"` - Detail string `json:"detail"` - ImageURL any `json:"image_url"` - VideoURL any `json:"video_url"` - FileID string `json:"file_id"` - Filename string `json:"filename"` - FileData string `json:"file_data"` - FileURL string `json:"file_url"` + Type string `json:"type"` + Text string `json:"text"` + Refusal string `json:"refusal"` + Detail string `json:"detail"` + ImageURL jsonSlice `json:"image_url"` + VideoURL jsonSlice `json:"video_url"` + FileID string `json:"file_id"` + Filename string `json:"filename"` + FileData jsonSlice `json:"file_data"` + FileURL string `json:"file_url"` File *struct { - FileID string `json:"file_id"` - Filename string `json:"filename"` - FileData string `json:"file_data"` + FileID string `json:"file_id"` + Filename string `json:"filename"` + FileData jsonSlice `json:"file_data"` } `json:"file"` InputAudio *struct { - Data string `json:"data"` - Format string `json:"format"` + Data jsonSlice `json:"data"` + Format string `json:"format"` } `json:"input_audio"` } // openAIContentPart 映射内容块,并把图片与文件的 detail 写为媒体分辨率 func openAIContentPart(block openAIBlock) (aistudio.Part, error) { - part, err := openAIContentBlock(block) + part, detail, err := openAIContentBlock(block) if err != nil { return part, err } - if image, ok := block.ImageURL.(map[string]any); ok && block.Detail == "" { - block.Detail, _ = image["detail"].(string) + if block.Detail == "" { + block.Detail = detail } part.MediaResolution = openAIDetailResolutions[block.Detail] return part, nil } -// openAIContentBlock 把 Chat 与 Responses 内容块映射为 Part -func openAIContentBlock(block openAIBlock) (aistudio.Part, error) { +// openAIContentBlock 把 Chat 与 Responses 内容块映射为 Part,并在 image_url 对象含 detail 时返回它 +func openAIContentBlock(block openAIBlock) (aistudio.Part, string, error) { switch block.Type { case "text", "input_text", "output_text": - return aistudio.Part{Text: block.Text}, nil + return aistudio.Part{Text: block.Text}, "", nil case "refusal": - return aistudio.Part{Text: block.Refusal}, nil + return aistudio.Part{Text: block.Refusal}, "", nil case "image_url", "input_image", "video_url", "input_video": field, rawURL := "image_url", block.ImageURL if block.Type == "video_url" || block.Type == "input_video" { field, rawURL = "video_url", block.VideoURL } - if rawURL == nil && block.FileID != "" { - return aistudio.Part{File: &aistudio.FileRef{ID: block.FileID}}, nil + if !rawURL.hasValue() && block.FileID != "" { + return aistudio.Part{File: &aistudio.FileRef{ID: block.FileID}}, "", nil } - url, err := mediaURLString(rawURL, field) + rawValue, detail, err := mediaURLBytes(rawURL, field) if err != nil { - return aistudio.Part{}, err + return aistudio.Part{}, "", err } - return fileOrInlinePart(url, "") + if field != "image_url" { + detail = "" + } + part, err := fileOrInlineBytes(rawValue, "") + return part, detail, err case "file", "input_file": if block.File != nil { block.FileID, block.Filename, block.FileData = block.File.FileID, block.File.Filename, block.File.FileData } - if block.FileData != "" { - return fileDataPart(block.FileData, block.Filename) + if block.FileData.hasString() { + raw, err := block.FileData.stringBytes() + if err != nil { + return aistudio.Part{}, "", fmt.Errorf("file_data: %w", err) + } + part, err := fileDataBytes(raw, block.Filename) + return part, "", err } if block.FileID == "" { block.FileID = block.FileURL } - return aistudio.Part{File: &aistudio.FileRef{ID: block.FileID, Name: block.Filename}}, nil + return aistudio.Part{File: &aistudio.FileRef{ID: block.FileID, Name: block.Filename}}, "", nil case "input_audio": if block.InputAudio == nil { - return aistudio.Part{}, fmt.Errorf("input_audio is required") + return aistudio.Part{}, "", fmt.Errorf("input_audio is required") + } + raw, err := block.InputAudio.Data.stringBytes() + if err != nil { + return aistudio.Part{}, "", fmt.Errorf("input_audio.data: %w", err) } - data, err := decodeBase64Flexible(block.InputAudio.Data) + data, err := decodeBase64Bytes(raw) if err != nil { - return aistudio.Part{}, fmt.Errorf("input_audio.data: %w", err) + return aistudio.Part{}, "", fmt.Errorf("input_audio.data: %w", err) } - return aistudio.Part{InlineData: aistudio.NewBlob(audioMIME(block.InputAudio.Format), data)}, nil + return aistudio.Part{InlineData: aistudio.NewBlob(audioMIME(block.InputAudio.Format), data)}, "", nil default: - return aistudio.Part{}, fmt.Errorf("unsupported content type %q", block.Type) + return aistudio.Part{}, "", fmt.Errorf("unsupported content type %q", block.Type) } } -// mediaURLString 读取 image_url 或 video_url 的字符串值或 url 字段 -func mediaURLString(value any, field string) (string, error) { - switch value := value.(type) { - case string: - return value, nil - case map[string]any: - if url, _ := value["url"].(string); url != "" { - return url, nil +// mediaURLBytes 零拷贝读取 image_url 或 video_url 的字符串值或 url 字段,并在对象含 detail 时一并返回 +func mediaURLBytes(raw jsonSlice, field string) ([]byte, string, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { + return nil, "", fmt.Errorf("%s must contain url", field) + } + if trimmed[0] == '"' { + value, err := jsonSlice(trimmed).stringBytes() + if err != nil || len(value) == 0 { + return nil, "", fmt.Errorf("%s must contain url", field) } + return value, "", nil } - return "", fmt.Errorf("%s must contain url", field) + if trimmed[0] == '{' { + var object struct { + URL jsonSlice `json:"url"` + Detail string `json:"detail"` + } + if json.Unmarshal(trimmed, &object) == nil { + if value, err := object.URL.stringBytes(); err == nil && len(value) > 0 { + return value, object.Detail, nil + } + } + } + return nil, "", fmt.Errorf("%s must contain url", field) } -func fileOrInlinePart(value string, name string) (aistudio.Part, error) { - if media, ok := aistudio.ExternalMediaForURL(value); ok { - return aistudio.Part{ExternalMedia: media, DisplayName: name}, nil - } - if !strings.HasPrefix(value, "data:") { +// fileOrInlineBytes 零拷贝解析 data URL、外部媒体链接或普通文件引用,避免为大 Base64 分配字符串副本 +func fileOrInlineBytes(raw []byte, name string) (aistudio.Part, error) { + if !bytes.HasPrefix(raw, []byte("data:")) { + value := string(raw) + if media, ok := aistudio.ExternalMediaForURL(value); ok { + return aistudio.Part{ExternalMedia: media, DisplayName: name}, nil + } return aistudio.Part{File: &aistudio.FileRef{ID: value, Name: name}}, nil } - metadata, encoded, ok := strings.Cut(strings.TrimPrefix(value, "data:"), ",") + metadata, encoded, ok := bytes.Cut(raw[len("data:"):], []byte(",")) if !ok { return aistudio.Part{}, fmt.Errorf("data URL must contain a comma") } var data []byte - if mediaType, isBase64 := strings.CutSuffix(metadata, ";base64"); isBase64 { - decoded, err := decodeBase64Flexible(encoded) + if mediaType, isBase64 := bytes.CutSuffix(metadata, []byte(";base64")); isBase64 { + decoded, err := decodeBase64Bytes(encoded) if err != nil { return aistudio.Part{}, fmt.Errorf("data URL: %w", err) } metadata, data = mediaType, decoded } else { - decoded, err := url.PathUnescape(encoded) + decoded, err := url.PathUnescape(string(encoded)) if err != nil { return aistudio.Part{}, fmt.Errorf("data URL: %w", err) } data = []byte(decoded) } - mediaType, _, _ := mime.ParseMediaType(metadata) + mediaType, _, _ := mime.ParseMediaType(string(metadata)) mimeType, data := normalizeImagePayload(attachmentMIME(mediaType, name, data), data) return aistudio.Part{InlineData: aistudio.NewBlob(mimeType, data), DisplayName: name}, nil } -// fileDataPart 解析 data URL 或 base64 文件内容 -func fileDataPart(value string, name string) (aistudio.Part, error) { - if strings.HasPrefix(value, "data:") { - return fileOrInlinePart(value, name) +// fileDataBytes 零拷贝解析 data URL 或 base64 文件内容 +func fileDataBytes(raw []byte, name string) (aistudio.Part, error) { + if bytes.HasPrefix(raw, []byte("data:")) { + return fileOrInlineBytes(raw, name) } - data, err := decodeBase64Flexible(value) + data, err := decodeBase64Bytes(raw) if err != nil { return aistudio.Part{}, fmt.Errorf("file_data: %w", err) } @@ -706,6 +745,11 @@ func fileDataPart(value string, name string) (aistudio.Part, error) { return aistudio.Part{InlineData: aistudio.NewBlob(mimeType, data), DisplayName: name}, nil } +// fileOrInlinePart 解析字符串形式的 data URL、外部媒体链接或普通文件引用 +func fileOrInlinePart(value string, name string) (aistudio.Part, error) { + return fileOrInlineBytes([]byte(value), name) +} + // detectMediaType 按内容前缀判断不带参数的 MIME,无法识别时依次按 FLAC 头、MPEG 音频帧头与扩展名判断 func detectMediaType(name string, data []byte) string { detected, _, _ := mime.ParseMediaType(http.DetectContentType(data)) @@ -871,18 +915,44 @@ func restrictAllowedTools(tools aistudio.Tools, allowed []toolReference) aistudi tools.GoogleSearch = nil } servers := allowedMCPServers(allowed) - tools.MCPServers = slices.DeleteFunc(tools.MCPServers, func(server aistudio.MCPServer) bool { - _, ok := servers[server.Name] - return !ok - }) - for index, server := range tools.MCPServers { - if names := servers[server.Name]; names != nil { - tools.MCPServers[index].AllowedTools = names + kept := make([]aistudio.MCPServer, 0, len(tools.MCPServers)) + for _, server := range tools.MCPServers { + if server, ok := restrictMCPServer(server, servers); ok { + kept = append(kept, server) } } + tools.MCPServers = kept return tools } +// restrictMCPServer 按 tool_choice 限定的 MCP 服务器与工具名裁剪 server,与 server.AllowedTools 取交集;服务器不被允许或交集为空时返回 false +func restrictMCPServer(server aistudio.MCPServer, restricted map[string][]string) (aistudio.MCPServer, bool) { + names, ok := restricted[server.Name] + if !ok { + return server, false + } + if names != nil { + if server.AllowedTools == nil { + server.AllowedTools = names + } else { + var common []string + for _, name := range server.AllowedTools { + if slices.Contains(names, name) { + common = appendUnique(common, name) + } + } + if len(common) == 0 { + return server, false + } + server.AllowedTools = common + } + } + if server.AllowedTools != nil && len(server.AllowedTools) == 0 { + return server, false + } + return server, true +} + // allowedMCPServers 返回引用中限定的 MCP 服务器标签与工具名,工具名为 nil 表示该服务器的全部工具 func allowedMCPServers(allowed []toolReference) map[string][]string { servers := make(map[string][]string) diff --git a/internal/api/pairing.go b/internal/api/pairing.go index 27525885..59dad7cb 100644 --- a/internal/api/pairing.go +++ b/internal/api/pairing.go @@ -24,6 +24,7 @@ type PairingToken struct { // AccountStateInput 是远程配对上传或管理端 Cookie 导入的账户认证状态与 Camoufox 指纹 type AccountStateInput struct { Label string `json:"label"` + Note string `json:"note,omitempty"` Proxy string `json:"-"` Locale string `json:"locale"` Timezone string `json:"timezone"` diff --git a/internal/api/remote_media.go b/internal/api/remote_media.go index fa5666e5..7f0384a9 100644 --- a/internal/api/remote_media.go +++ b/internal/api/remote_media.go @@ -30,9 +30,13 @@ var remoteMediaClient = &http.Client{Transport: remoteMediaTransport(), CheckRed return checkRemoteMediaHost(request.Context(), request.URL.Hostname()) }} -// remoteMediaTransport 返回按进程环境变量选择代理的 Transport,直连时在建立连接时拒绝实际连接的非公网地址 +// remoteMediaHeaderTimeout 是下载外部媒体等待响应头的超时 +const remoteMediaHeaderTimeout = 30 * time.Second + +// remoteMediaTransport 返回按进程环境变量选择代理并设置响应头超时的 Transport,直连时在建立连接时拒绝实际连接的非公网地址 func remoteMediaTransport() *http.Transport { transport := http.DefaultTransport.(*http.Transport).Clone() + transport.ResponseHeaderTimeout = remoteMediaHeaderTimeout dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second} direct := *dialer direct.Control = func(_, address string, _ syscall.RawConn) error { diff --git a/internal/api/responses.go b/internal/api/responses.go index 758e65df..983d6870 100644 --- a/internal/api/responses.go +++ b/internal/api/responses.go @@ -6,7 +6,9 @@ import ( "context" "encoding/base64" "encoding/json" + "encoding/json/jsontext" "fmt" + "io" "maps" "net/http" "slices" @@ -49,11 +51,15 @@ type responsesRequest struct { } `json:"context_management"` // split 是 prepareResponses 对 Input 的切分结果 split splitInput + // effectiveTools 是合并输入项配置后的工具列表,生成后不再需要保留原始 Input + effectiveTools []responsesTool + // hasHistory 表示该请求经 previous_response_id 续接已有对话轮次,输入中的 system 与 developer 消息按对话中途提醒处理 + hasHistory bool } // inputItems 返回 Input 的切分结果,prepareResponses 已切分同一输入时直接沿用 func (request responsesRequest) inputItems() splitInput { - if bytes.Equal(request.split.raw, request.Input) { + if request.split.array && request.Input == nil || bytes.Equal(request.split.raw, request.Input) { return request.split } return splitResponsesInput(request.Input) @@ -102,8 +108,17 @@ type responsesTool struct { AllowedTools json.RawMessage `json:"allowed_tools,omitempty"` RequireApproval json.RawMessage `json:"require_approval,omitempty"` ServerDescription string `json:"server_description,omitempty"` + // Execution 是 tool_search 工具的执行方,client 时由客户端检索并在 tool_search_output 中给出找到的工具 + Execution string `json:"execution,omitempty"` } +// clientToolSearch 是客户端执行的 tool_search 在上游声明的函数名、默认说明与默认参数 +const ( + clientToolSearch = "tool_search" + clientToolSearchDescription = "Search for deferred tools by query and load the matching tools." + clientToolSearchParameters = `{"type":"object","properties":{"query":{"type":"string","description":"Search query for deferred tools."},"limit":{"type":"number","description":"Maximum number of tools to return."}},"required":["query"],"additionalProperties":false}` +) + // imageGenerationTool 返回请求声明的 image_generation 工具 func imageGenerationTool(tools []responsesTool) *responsesTool { index := slices.IndexFunc(tools, func(tool responsesTool) bool { return tool.Type == "image_generation" }) @@ -117,7 +132,7 @@ type responsesInputItem struct { Type string `json:"type"` ID string `json:"id"` Role string `json:"role"` - Content json.RawMessage `json:"content"` + Content jsonSlice `json:"content"` CallID string `json:"call_id"` Name string `json:"name"` Namespace string `json:"namespace"` @@ -158,7 +173,12 @@ type storedItem struct { Raw json.RawMessage } -const responseStateCapacity = 256 +const ( + responseStateCapacity = 256 + // responseStateCacheItemLimit 与 responseStateCacheBytes 限制 persist 启用时内存中保留的已落盘节点正文体积,超过时仅留索引、按需从持久层读取 + responseStateCacheItemLimit = 256 << 10 + responseStateCacheBytes = 8 << 20 +) // responseHistory 是续接起点的响应 ID 及其按顺序展开的完整上下文 type responseHistory struct { @@ -178,7 +198,7 @@ type responseHistory struct { type StateStore interface { Index() []StateNode Read(id string) ([]byte, bool) - Save(saved []SavedState, removed []string) + Save(saved []SavedState, removed []string) error } // StateNode 是已保存续接节点的 ID 与续接起点 @@ -201,7 +221,15 @@ type responseStateStore struct { // parents 是全部节点的续接起点,正文还在 persist 中的节点也在其中 parents map[string]string order []string - persist StateStore + // streams 独立保留后台流式响应与交互的事件记录,节点正文落盘释放后仍可续传 + streams map[string]*streamLog + // sizes 与 cachedBytes 记录 persist 启用时留在 states 中的已落盘节点估算字节数 + sizes map[string]int + cachedBytes int + // versions 标记每个节点的内存版本,落盘提交后只处理版本未变的节点 + versions map[string]uint64 + nextVersion uint64 + persist StateStore // committed 在最近一次排队的写入提交完成时关闭,写入按排队顺序提交 committed chan struct{} } @@ -211,8 +239,13 @@ func newResponseStateStore(persist StateStore) *responseStateStore { committed := make(chan struct{}) close(committed) store := &responseStateStore{ - states: make(map[string]responseState, responseStateCapacity), parents: make(map[string]string, responseStateCapacity), - persist: persist, committed: committed, + states: make(map[string]responseState, responseStateCapacity), + parents: make(map[string]string, responseStateCapacity), + streams: make(map[string]*streamLog), + sizes: make(map[string]int, responseStateCapacity), + versions: make(map[string]uint64, responseStateCapacity), + persist: persist, + committed: committed, } if persist == nil { return store @@ -224,7 +257,59 @@ func newResponseStateStore(persist StateStore) *responseStateStore { return store } -// stateLocked 返回节点,正文还在 persist 中时读出并留在内存 +// recordStreamLocked 把后台流式事件记录独立保存在内存索引中,避免正文释放后丢失流状态 +func (store *responseStateStore) recordStreamLocked(id string, state responseState) { + switch { + case state.Record != nil && state.Record.Stream != nil: + store.streams[id] = state.Record.Stream + case state.Interaction != nil && state.Interaction.stream != nil: + store.streams[id] = state.Interaction.stream + } +} + +// attachStreamLocked 为从持久层读出的节点回填仍在内存中的后台事件记录 +func (store *responseStateStore) attachStreamLocked(id string, state *responseState) { + stream := store.streams[id] + if stream == nil { + return + } + if state.Record != nil && state.Record.Stream == nil { + state.Record.Stream = stream + } + if state.Interaction != nil && state.Interaction.stream == nil { + state.Interaction.stream = stream + } +} + +// cacheLocked 在预算内把已落盘节点正文保留在 states 中,超出总预算时按写入顺序释放最旧的已落盘正文 +func (store *responseStateStore) cacheLocked(id string, state responseState, size int) { + if old, exists := store.sizes[id]; exists { + store.cachedBytes -= old + delete(store.sizes, id) + } + if size > responseStateCacheItemLimit { + delete(store.states, id) + return + } + store.states[id] = state + store.sizes[id] = size + store.cachedBytes += size + for _, candidate := range store.order { + if store.cachedBytes <= responseStateCacheBytes { + break + } + if candidate == id { + continue + } + if old, exists := store.sizes[candidate]; exists { + delete(store.states, candidate) + delete(store.sizes, candidate) + store.cachedBytes -= old + } + } +} + +// stateLocked 返回节点,正文还在 persist 中时读出并在预算内保留于内存 func (store *responseStateStore) stateLocked(id string) (responseState, bool) { if state, exists := store.states[id]; exists { return state, true @@ -237,33 +322,63 @@ func (store *responseStateStore) stateLocked(id string) (responseState, bool) { if !ok || json.Unmarshal(data, &state) != nil { return responseState{}, false } - store.states[id] = state + store.attachStreamLocked(id, &state) + if len(data) <= responseStateCacheItemLimit { + store.cacheLocked(id, state, len(data)) + } return state, true } // putLocked 保存节点并记录它的续接起点 func (store *responseStateStore) putLocked(id string, state responseState) { + store.nextVersion++ + store.versions[id] = store.nextVersion + if old, exists := store.sizes[id]; exists { + store.cachedBytes -= old + delete(store.sizes, id) + } store.states[id] = state store.parents[id] = state.ParentID + store.recordStreamLocked(id, state) } -// persistLocked 编码仍存在且已结束的节点并排队删除已移除的节点,返回按排队顺序提交这次写入的函数,调用方释放 mu 后调用;进行中的后台响应与交互在服务重启后不能继续,只保存终态 +// persistLocked 编码仍存在且已结束的节点并排队删除已移除的节点,返回按排队顺序提交这次写入的函数,调用方释放 mu 后调用;进行中的后台响应与交互在服务重启后不能继续,只保存终态,落盘后超出内存预算的大节点从 states 释放 func (store *responseStateStore) persistLocked(saved, removed []string) func() { if store.persist == nil { return func() {} } + type savedVersion struct { + id string + version uint64 + size int + } states := make([]SavedState, 0, len(saved)) + tracked := make([]savedVersion, 0, len(saved)) for _, id := range saved { if state, exists := store.states[id]; exists && state.finished() { data, _ := json.Marshal(state) states = append(states, SavedState{ID: id, ParentID: state.ParentID, Data: data}) + tracked = append(tracked, savedVersion{id: id, version: store.versions[id], size: len(data)}) } } previous, done := store.committed, make(chan struct{}) store.committed = done return func() { <-previous - store.persist.Save(states, removed) + if err := store.persist.Save(states, removed); err == nil && len(tracked) > 0 { + store.mu.Lock() + for _, item := range tracked { + if store.versions[item.id] != item.version { + continue + } + state, exists := store.states[item.id] + if !exists { + continue + } + store.cacheLocked(item.id, state, item.size) + } + store.mu.Unlock() + } close(done) } } @@ -288,23 +403,24 @@ func (store *responseStateStore) Load(id string) (responseHistory, bool) { store.mu.Lock() defer store.mu.Unlock() history := responseHistory{ID: id, Contents: make([]aistudio.Content, 0), InlineInstructions: make([]string, 0)} - if state, exists := store.stateLocked(id); exists { - history.Interaction = state.Interaction != nil - if state.Interaction != nil { - history.Upstream, history.AccountID, history.Agent = state.Interaction.upstream, state.Interaction.account, state.Interaction.agent - } - if state.Record != nil { - history.Model = state.Record.Model - } - } chain := make([]responseState, 0) - for id != "" { - state, exists := store.stateLocked(id) + for cursor := id; cursor != ""; { + state, exists := store.stateLocked(cursor) if !exists { return responseHistory{}, false } chain = append(chain, state) - id = state.ParentID + cursor = state.ParentID + } + if len(chain) > 0 { + head := chain[0] + history.Interaction = head.Interaction != nil + if head.Interaction != nil { + history.Upstream, history.AccountID, history.Agent = head.Interaction.upstream, head.Interaction.account, head.Interaction.agent + } + if head.Record != nil { + history.Model = head.Record.Model + } } for index := len(chain) - 1; index >= 0; index-- { history.Contents = append(history.Contents, cloneResponseContents(chain[index].Contents)...) @@ -371,6 +487,12 @@ func (store *responseStateStore) removeLocked(id string) []string { } delete(store.states, id) delete(store.parents, id) + delete(store.streams, id) + delete(store.versions, id) + if old, exists := store.sizes[id]; exists { + store.cachedBytes -= old + delete(store.sizes, id) + } return children } @@ -509,15 +631,40 @@ type splitInput struct { heads []responsesItemHead } -// splitResponsesInput 把 Responses 输入切分为各输入项原文与类型、角色和 ID +// splitResponsesInput 零拷贝按字节偏移把 Responses 输入数组切分为各输入项原文与类型、角色和 ID func splitResponsesInput(raw json.RawMessage) splitInput { input := splitInput{raw: raw} - if json.Unmarshal(raw, &input.items) != nil { - input.items = nil + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || trimmed[0] != '[' { + return input + } + decoder := jsontext.NewDecoder(bytes.NewBuffer(raw)) + token, err := decoder.ReadToken() + if err != nil || token.Kind() != '[' { + return input + } + var items []json.RawMessage + for decoder.PeekKind() != ']' { + start := decoder.InputOffset() + if err := decoder.SkipValue(); err != nil { + return input + } + end := decoder.InputOffset() + elem := bytes.TrimSpace(raw[start:end]) + if len(elem) > 0 && elem[0] == ',' { + elem = bytes.TrimSpace(elem[1:]) + } + items = append(items, json.RawMessage(elem)) + } + if _, err := decoder.ReadToken(); err != nil { + return input + } + if _, err := decoder.ReadToken(); err != io.EOF { return input } input.array = true - input.heads = responsesItemHeads(input.items) + input.items = items + input.heads = responsesItemHeads(items) return input } @@ -583,6 +730,7 @@ func (s *server) handleResponses(w http.ResponseWriter, r *http.Request) { defer stopKeepalive() } compaction, err := s.compactOverThreshold(r.Context(), &request, &prepared, responseID) + request.Input, request.split = nil, splitInput{} if err != nil { if shouldWriteRequestError(r, err) { writeOpenAIRequestError(w, err) @@ -714,17 +862,42 @@ func (s *server) prepareResponses(ctx context.Context, request *responsesRequest request.Tools[index].Strict = &strict } } - additionalTools, _ := responsesInputConfig(input) - tools := slices.Concat(request.Tools, additionalTools) - rewritten, approved, err := s.applyMCPApprovals(ctx, request.PreviousResponseID, tools, input.raw, execute) - if err != nil { - return responsesPreparation{}, err + tools, _ := responsesInputConfig(request.Tools, input) + rewritten := input.raw + var approved []map[string]any + if input.hasType("mcp_approval_response") { + rewritten, approved, err = s.applyMCPApprovals(ctx, request.PreviousResponseID, tools, input.raw, execute) + if err != nil { + return responsesPreparation{}, err + } } request.Input, request.split = rewritten, input if !bytes.Equal(rewritten, input.raw) { request.split = splitResponsesInput(rewritten) + tools, _ = responsesInputConfig(request.Tools, request.split) + } + if tools == nil { + tools = []responsesTool{} + } + request.effectiveTools = tools + var previous responseHistory + if request.PreviousResponseID != "" { + var ok bool + previous, ok = s.responseStates.Load(request.PreviousResponseID) + if !ok || previous.Interaction { + return responsesPreparation{}, fmt.Errorf("previous response %q was not found", request.PreviousResponseID) + } + request.hasHistory = len(previous.Contents) > 0 + } + consumable := request.split.array && !request.storesResponse() && request.compactThreshold() <= 0 && !responsesCompactionTrigger(request.split) + if consumable { + request.Input = nil + request.split.raw = nil } generateRequest, inlineInstructions, err := request.toGenerateRequest(id) + if consumable { + request.split = splitInput{} + } if err == nil { generateRequest, err = s.resolveMCPTools(ctx, generateRequest) } @@ -755,10 +928,11 @@ func (s *server) prepareResponses(ctx context.Context, request *responsesRequest } } prepared := responsesPreparation{ - generate: generateRequest, contents: cloneResponseContents(generateRequest.Contents), + generate: generateRequest, inlineInstructions: append([]string(nil), inlineInstructions...), approved: approved, } if request.storesResponse() { + prepared.contents = cloneResponseContents(generateRequest.Contents) prepared.input = responsesInputItems(input, id) } if tool := imageGenerationTool(request.Tools); tool != nil && tool.InputImageMask != nil { @@ -772,10 +946,6 @@ func (s *server) prepareResponses(ctx context.Context, request *responsesRequest if request.PreviousResponseID == "" { return prepared, nil } - previous, ok := s.responseStates.Load(request.PreviousResponseID) - if !ok || previous.Interaction { - return responsesPreparation{}, fmt.Errorf("previous response %q was not found", request.PreviousResponseID) - } prepared.previous = previous prepared.generate.Contents = append(cloneResponseContents(previous.Contents), generateRequest.Contents...) inlineInstructions = append(append([]string(nil), previous.InlineInstructions...), inlineInstructions...) @@ -848,7 +1018,7 @@ func responsesInputItems(input splitInput, responseID string) []storedItem { if json.Unmarshal(head.Content, &content) == nil { part := map[string]any{"type": "input_text", "text": content} if head.Role == "assistant" { - part = map[string]any{"type": "output_text", "text": content, "annotations": []any{}} + part = map[string]any{"type": "output_text", "text": content, "annotations": []any{}, "logprobs": []any{}} } item["content"], _ = json.Marshal([]any{part}) } @@ -885,13 +1055,13 @@ func (request responsesRequest) toGenerateRequest(id string) (aistudio.GenerateR return aistudio.GenerateRequest{}, nil, fmt.Errorf("unsupported truncation %q", request.Truncation) } input := request.inputItems() - contents, inlineInstructions, err := responsesContents(input) + contents, inlineInstructions, err := responsesContentsWithHistory(input, request.hasHistory) if err != nil { return aistudio.GenerateRequest{}, nil, err } instructions := request.instructions(inlineInstructions) - additionalTools, configuredEffort := responsesInputConfig(input) - tools, err := mapResponsesTools(slices.Concat(request.Tools, additionalTools), request.ToolChoice) + declared, configuredEffort := responsesInputConfig(request.Tools, input) + tools, err := mapResponsesTools(declared, request.ToolChoice) if err != nil { return aistudio.GenerateRequest{}, nil, err } @@ -984,10 +1154,15 @@ func (request responsesRequest) toGenerateRequest(id string) (aistudio.GenerateR } func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { - if !rawJSONConfigured(input.raw) { - return nil, nil, nil - } + return responsesContentsWithHistory(input, false) +} + +// responsesContentsWithHistory 转换 Responses 输入项为规范轮次与开头系统指令,hasHistory 为真或已有对话轮次之后的 system 与 developer 消息按出现位置进入当轮提醒 +func responsesContentsWithHistory(input splitInput, hasHistory bool) ([]aistudio.Content, []string, error) { if !input.array { + if !rawJSONConfigured(input.raw) { + return nil, nil, nil + } var text string if err := json.Unmarshal(input.raw, &text); err != nil { return nil, nil, fmt.Errorf("input must be a string or item array") @@ -1006,6 +1181,7 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { contents := make([]aistudio.Content, 0, len(items)) var instructions []string var systemMedia []aistudio.Part + var reminders []aistudio.Part pendingSignature := "" for index, rawItem := range items { var item responsesInputItem @@ -1017,14 +1193,61 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { continue case "additional_tools", "configuration_update": continue + case "tool_search_call", "tool_search_output": + var search struct { + CallID string `json:"call_id"` + Execution string `json:"execution"` + Status string `json:"status"` + Arguments json.RawMessage `json:"arguments"` + Tools []responsesTool `json:"tools"` + } + if err := json.Unmarshal(rawItem, &search); err != nil { + return nil, nil, fmt.Errorf("%s: %w", kind, err) + } + if search.Execution != "client" { + pendingSignature = "" + content, err := responsesHostedItem(kind, rawItem) + if err != nil { + return nil, nil, fmt.Errorf("%s: %w", kind, err) + } + contents, reminders = appendWithReminders(contents, content, reminders) + continue + } + if kind == "tool_search_call" { + arguments := search.Arguments + var text string + if json.Unmarshal(arguments, &text) == nil { + arguments = json.RawMessage(text) + } + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleAssistant, Parts: []aistudio.Part{{FunctionCall: &aistudio.FunctionCall{ + ID: search.CallID, Name: clientToolSearch, Arguments: functionCallArguments(string(arguments)), ThoughtSignature: pendingSignature, + }}}}, reminders) + pendingSignature = "" + continue + } + pendingSignature = "" + names := make([]string, 0, len(search.Tools)) + for _, tool := range search.Tools { + if tool.Type != "namespace" { + names = append(names, tool.Name) + } + for _, member := range tool.Tools { + names = append(names, namespacedName(tool.Name, member.Name)) + } + } + output, _ := json.Marshal(map[string]any{"status": cmp.Or(search.Status, "completed"), "tools": names}) + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleTool, Parts: []aistudio.Part{{FunctionResult: &aistudio.FunctionResult{ + ID: search.CallID, Name: clientToolSearch, Content: output, + }}}}, reminders) + continue case "web_search_call", "code_interpreter_call", "image_generation_call", "file_search_call", - "mcp_call", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", "tool_search_call", "tool_search_output", "program", "program_output": + "mcp_call", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", "program", "program_output": pendingSignature = "" content, err := responsesHostedItem(kind, rawItem) if err != nil { return nil, nil, fmt.Errorf("%s: %w", kind, err) } - contents = append(contents, content) + contents, reminders = appendWithReminders(contents, content, reminders) continue default: if err := json.Unmarshal(rawItem, &item); err != nil { @@ -1037,19 +1260,30 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { case "", "message": pendingSignature = "" if item.Role == "system" || item.Role == "developer" { - parts, err := openAIContentParts(item.Content) + parts, err := openAIContentParts(json.RawMessage(item.Content)) if err != nil { return nil, nil, fmt.Errorf("%s message: %w", item.Role, err) } var text strings.Builder + var media []aistudio.Part for _, part := range parts { if part.Text == "" { - systemMedia = append(systemMedia, part) + media = append(media, part) } text.WriteString(part.Text) } - if text.Len() > 0 { - instructions = append(instructions, text.String()) + if !hasHistory && len(contents) == 0 { + systemMedia = append(systemMedia, media...) + if text.Len() > 0 { + instructions = append(instructions, text.String()) + } + } else { + var mid []aistudio.Part + if text.Len() > 0 { + mid = append(mid, aistudio.Part{Text: "\n" + text.String() + "\n"}) + } + mid = append(mid, media...) + reminders = addSystemReminderParts(contents, reminders, mid) } continue } @@ -1057,19 +1291,19 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { if err != nil { return nil, nil, err } - parts, err := openAIContentParts(item.Content) + parts, err := openAIContentParts(json.RawMessage(item.Content)) if err != nil { return nil, nil, err } - contents = append(contents, aistudio.Content{Role: role, Parts: parts}) + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: role, Parts: parts}, reminders) continue case "agent_message": pendingSignature = "" - parts, err := agentMessageParts(item.Content) + parts, err := agentMessageParts(json.RawMessage(item.Content)) if err != nil { return nil, nil, fmt.Errorf("agent_message: %w", err) } - contents = append(contents, aistudio.Content{Role: aistudio.RoleUser, Parts: parts}) + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleUser, Parts: parts}, reminders) continue case "function_call": call.Arguments = functionCallArguments(item.Arguments) @@ -1092,9 +1326,9 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { if err != nil { return nil, nil, fmt.Errorf("computer_call_output: %w", err) } - contents = append(contents, aistudio.Content{Role: aistudio.RoleTool, Parts: append([]aistudio.Part{{FunctionResult: &aistudio.FunctionResult{ + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleTool, Parts: append([]aistudio.Part{{FunctionResult: &aistudio.FunctionResult{ ID: item.CallID, Name: "computer", Content: json.RawMessage(`{"type":"computer_screenshot"}`), - }}}, screenshot...)}) + }}}, screenshot...)}, reminders) continue case "function_call_output", "custom_tool_call_output", "local_shell_call_output", "shell_call_output", "apply_patch_call_output": pendingSignature = "" @@ -1108,19 +1342,27 @@ func responsesContents(input splitInput) ([]aistudio.Content, []string, error) { if err != nil { return nil, nil, fmt.Errorf("%s: %w", item.Type, err) } - contents = append(contents, aistudio.Content{Role: aistudio.RoleTool, Parts: append([]aistudio.Part{{FunctionResult: &aistudio.FunctionResult{ + if item.Status == "incomplete" && item.Type != "apply_patch_call_output" { + output, _ = json.Marshal(map[string]any{"status": item.Status, "output": rawJSONValue(output, nil)}) + } + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleTool, Parts: append([]aistudio.Part{{FunctionResult: &aistudio.FunctionResult{ ID: item.CallID, Content: output, - }}}, media...)}) + }}}, media...)}, reminders) continue case "reasoning": - pendingSignature = item.EncryptedContent + if item.EncryptedContent != "" { + pendingSignature = item.EncryptedContent + } continue default: return nil, nil, fmt.Errorf("unsupported input item type %q", item.Type) } - contents = append(contents, aistudio.Content{Role: aistudio.RoleAssistant, Parts: []aistudio.Part{{FunctionCall: &call}}}) + contents, reminders = appendWithReminders(contents, aistudio.Content{Role: aistudio.RoleAssistant, Parts: []aistudio.Part{{FunctionCall: &call}}}, reminders) pendingSignature = "" } + if len(reminders) > 0 { + contents = append(contents, aistudio.Content{Role: aistudio.RoleUser, Parts: reminders}) + } return prependSystemMedia(contents, systemMedia), instructions, nil } @@ -1148,27 +1390,40 @@ func agentMessageParts(raw json.RawMessage) ([]aistudio.Part, error) { return parts, nil } -// responsesInputConfig 返回输入项中 additional_tools 提供的工具与最后一个 configuration_update 的推理强度 -func responsesInputConfig(input splitInput) ([]responsesTool, string) { - if !input.hasType("additional_tools", "configuration_update") { - return nil, "" - } - var items []struct { - Type string `json:"type"` - Tools []responsesTool `json:"tools"` - Reasoning *struct { - Effort string `json:"effort"` - } `json:"reasoning"` +// responsesInputConfig 返回 declared 加上输入项中 additional_tools 提供的工具与客户端 tool_search_output 找到的工具,以及最后一个 configuration_update 的推理强度 +func responsesInputConfig(declared []responsesTool, input splitInput) ([]responsesTool, string) { + tools := slices.Clone(declared) + if !input.hasType("additional_tools", "configuration_update", "tool_search_output") { + return tools, "" } - if json.Unmarshal(input.raw, &items) != nil { - return nil, "" - } - var tools []responsesTool effort := "" - for _, item := range items { + for index, head := range input.heads { + switch head.Type { + case "additional_tools", "configuration_update", "tool_search_output": + default: + continue + } + var item struct { + Type string `json:"type"` + Execution string `json:"execution"` + Tools []responsesTool `json:"tools"` + Reasoning *struct { + Effort string `json:"effort"` + } `json:"reasoning"` + } + if json.Unmarshal(input.items[index], &item) != nil { + continue + } switch item.Type { case "additional_tools": tools = append(tools, item.Tools...) + case "tool_search_output": + if item.Execution != "client" { + continue + } + for _, tool := range item.Tools { + tools = addFoundTool(tools, tool) + } case "configuration_update": if item.Reasoning != nil && item.Reasoning.Effort != "" { effort = item.Reasoning.Effort @@ -1178,6 +1433,26 @@ func responsesInputConfig(input splitInput) ([]responsesTool, string) { return tools, effort } +// addFoundTool 把 tool_search 找到的工具加入 tools:已有同类同名的工具时跳过,已有同名命名空间时加入其中没有的成员 +func addFoundTool(tools []responsesTool, tool responsesTool) []responsesTool { + index := slices.IndexFunc(tools, func(found responsesTool) bool { return found.Type == tool.Type && found.Name == tool.Name }) + if index < 0 { + return append(tools, tool) + } + if tool.Type != "namespace" { + return tools + } + namespace := tools[index] + namespace.Tools = slices.Clone(namespace.Tools) + for _, member := range tool.Tools { + if !slices.ContainsFunc(namespace.Tools, func(found responsesTool) bool { return found.Name == member.Name }) { + namespace.Tools = append(namespace.Tools, member) + } + } + tools[index] = namespace + return tools +} + // responsesItemType 读取输入项的 type 字段 func responsesItemType(raw json.RawMessage) string { var head struct { @@ -1342,6 +1617,7 @@ func mapResponsesTools(tools []responsesTool, choice json.RawMessage) (aistudio. Name: tool.Name, Description: tool.Description, Parameters: parameters, Strict: tool.strict(), }) } + clientSearch := false for _, tool := range tools { switch tool.Type { case "function", "custom": @@ -1399,10 +1675,22 @@ func mapResponsesTools(tools []responsesTool, choice json.RawMessage) (aistudio. if err != nil { return aistudio.Tools{}, err } - if approval.never { + if approval.never && (server.AllowedTools == nil || len(server.AllowedTools) > 0) { mapped.MCPServers = append(mapped.MCPServers, server) } - case "image_generation", "file_search", "tool_search", "programmatic_tool_calling": + case "tool_search": + if tool.Execution != "client" { + continue + } + declaration := aistudio.FunctionDeclaration{Name: clientToolSearch, Description: cmp.Or(tool.Description, clientToolSearchDescription), Parameters: tool.Parameters} + if len(declaration.Parameters) == 0 { + declaration.Parameters = json.RawMessage(clientToolSearchParameters) + } + if err := addDeclaration(declaration); err != nil { + return aistudio.Tools{}, err + } + clientSearch = true + case "image_generation", "file_search", "programmatic_tool_calling": default: return aistudio.Tools{}, fmt.Errorf("unsupported tool type %q", tool.Type) } @@ -1411,6 +1699,18 @@ func mapResponsesTools(tools []responsesTool, choice json.RawMessage) (aistudio. if err != nil { return aistudio.Tools{}, err } + if clientSearch { + if allowed != nil { + for index, reference := range allowed { + if reference.Type == "tool_search" { + allowed[index] = toolReference{Type: "function", Name: clientToolSearch} + config.AllowedFunctionNames = appendUnique(config.AllowedFunctionNames, clientToolSearch) + } + } + } else if responsesItemType(choice) == "tool_search" { + config = aistudio.ToolConfig{Mode: "required", AllowedFunctionNames: []string{clientToolSearch}} + } + } if allowed != nil { mapped = restrictAllowedTools(mapped, allowed) } @@ -1541,6 +1841,9 @@ func responseFunctionCall(call aistudio.FunctionCall, tools []responsesTool) map } item := map[string]any{"id": "fc_" + call.ID, "status": "completed", "call_id": call.ID} switch responsesToolKind(tools, call.Name) { + case "tool_search": + item["id"], item["type"], item["execution"], item["arguments"] = "tsc_"+call.ID, "tool_search_call", "client", rawJSONValue(call.Arguments, map[string]any{}) + return item case "local_shell": item["type"], item["action"] = "local_shell_call", localShellAction(call.Arguments) return item @@ -1561,17 +1864,23 @@ func responseFunctionCall(call aistudio.FunctionCall, tools []responsesTool) map item["type"], item["actions"], item["pending_safety_checks"] = "computer_call", arguments.Actions, []any{} return item case "custom": - item["type"], item["name"], item["input"] = "custom_tool_call", call.Name, customToolInput(call.Arguments) + item["id"], item["type"], item["name"], item["input"] = "ctc_"+call.ID, "custom_tool_call", call.Name, customToolInput(call.Arguments) default: item["type"], item["name"], item["arguments"] = "function_call", call.Name, string(call.Arguments) } if namespace := responsesNamespace(tools, call.Name); namespace != "" { item["namespace"] = namespace item["name"] = strings.TrimPrefix(call.Name, namespace+".") + if namespace == "collaboration" && item["type"] == "function_call" && slices.Contains(collaborationPlaintextCalls, item["name"].(string)) { + item["encrypted_function_args"] = []string{} + } } return item } +// collaborationPlaintextCalls 是 Codex multi_agent_v2 collaboration 命名空间中以空 encrypted_function_args 标明参数为明文的函数 +var collaborationPlaintextCalls = []string{"spawn_agent", "send_message", "followup_task"} + // namespacedName 返回命名空间中函数的声明名:默认命名空间 functions 中的函数与顶层函数相同,用原名,其余为 <命名空间>.<名> func namespacedName(namespace, name string) string { if namespace == "" || namespace == "functions" { @@ -1682,7 +1991,7 @@ func (o *responsesOutput) add(event aistudio.Event) ([]map[string]any, error) { write(o.reasoning, o.reasoning["summary"].([]any)[0].(map[string]any), event.Text) case aistudio.EventText: if !isLast(o.message) { - o.message = map[string]any{"id": o.itemID("msg_"), "type": "message", "status": "completed", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "", "annotations": []any{}}}} + o.message = map[string]any{"id": o.itemID("msg_"), "type": "message", "status": "completed", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "", "annotations": []any{}, "logprobs": []any{}}}} o.texts[o.message["id"].(string)] = &strings.Builder{} o.starts[o.message["id"].(string)] = o.text push(o.message) @@ -1879,11 +2188,14 @@ func outputPrefix(compaction map[string]any, prepared responsesPreparation) []ma // newResponsesWriter 返回 Responses 输出写出器 func newResponsesWriter(w http.ResponseWriter, id string, created int64, request responsesRequest) *responsesStreamWriter { - additional, _ := responsesInputConfig(request.inputItems()) + tools := request.effectiveTools + if tools == nil { + tools, _ = responsesInputConfig(request.Tools, request.inputItems()) + } return &responsesStreamWriter{ w: w, id: id, created: created, request: request, output: &responsesOutput{ - id: id, request: request, tools: slices.Concat(request.Tools, additional), texts: make(map[string]*strings.Builder), + id: id, request: request, tools: tools, texts: make(map[string]*strings.Builder), starts: make(map[string]int), queries: make(map[string]struct{}), pages: make(map[string]struct{}), mcpCalls: make(map[string]aistudio.ServerToolStep), }, } @@ -2062,7 +2374,7 @@ func (writer *responsesStreamWriter) added(item map[string]any) error { writer.open = append(writer.open, item) return writer.emit("response.content_part.added", map[string]any{ "item_id": item["id"], "output_index": index, "content_index": 0, - "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}}, + "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}, "logprobs": []any{}}, }) case item["type"] == "reasoning": pending := maps.Clone(item) @@ -2326,8 +2638,11 @@ func responsesError(err error) map[string]any { return map[string]any{"code": responsesErrorCode(err), "message": retryMessage(publicErrorMessage(statusFromError(err), publicReason(err)), retryAfterSeconds(err))} } -// responsesErrorCode 返回 Responses 错误对象的官方枚举 code +// responsesErrorCode 返回 Responses 错误对象的官方枚举 code,输入 token 超限时为 Codex 识别的 context_length_exceeded func responsesErrorCode(err error) string { + if contextOverflow(err) { + return "context_length_exceeded" + } switch statusFromError(err) { case http.StatusTooManyRequests: return "rate_limit_exceeded" diff --git a/internal/api/responses_background.go b/internal/api/responses_background.go index 3dc9a279..6098178b 100644 --- a/internal/api/responses_background.go +++ b/internal/api/responses_background.go @@ -68,6 +68,7 @@ func (s *server) respondBackground(w http.ResponseWriter, r *http.Request, reque _ = http.NewResponseController(w).Flush() compaction, err := s.compactOverThreshold(ctx, &request, &prepared, id) + request.Input, request.split = nil, splitInput{} var events <-chan aistudio.Event if err == nil { generate := prepared.generate @@ -118,6 +119,7 @@ func (s *server) streamBackground(w http.ResponseWriter, r *http.Request, reques _ = writer.emit("response.queued", map[string]any{"response": queued}) compaction, err := s.compactOverThreshold(ctx, &request, &prepared, id) + request.Input, request.split = nil, splitInput{} prepared.stream = stream prepared.generate.Background = true var events <-chan aistudio.Event diff --git a/internal/api/responses_compaction.go b/internal/api/responses_compaction.go index c81eba64..38b07c48 100644 --- a/internal/api/responses_compaction.go +++ b/internal/api/responses_compaction.go @@ -358,6 +358,31 @@ func conversationItems(items []json.RawMessage) []json.RawMessage { return slices.DeleteFunc(slices.Clone(items), instructionItem) } +// generateCompactionSummary 在不沿用调用方输出格式、输出上限与停止词的前提下,以非流式、禁用工具的方式生成压缩摘要 +func (s *server) generateCompactionSummary(ctx context.Context, base aistudio.GenerateRequest, instructions string) (string, *aistudio.Usage, error) { + summarize := base + summarize.Contents = append(slices.Clone(base.Contents), aistudio.Content{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: instructions}}}) + summarize.Tools.ToolConfig.Mode = "none" + summarize.Unary = true + summarize.Config.ResponseMIMEType = "" + summarize.Config.ResponseSchema = nil + summarize.Config.ResponseJSONSchema = nil + summarize.Config.MaxOutputTokens = nil + summarize.Config.StopSequences = nil + events, err := s.service.Generate(ctx, summarize) + if err != nil { + return "", nil, err + } + result, err := consumeEvents(ctx, events) + if err != nil { + return "", nil, err + } + if result.finishReason != "stop" { + return "", nil, fmt.Errorf("compaction summary finished with %s", result.finishReason) + } + return strings.TrimSpace(result.text.String()), result.usage, nil +} + // compactionSummary 以请求的模型、指令与工具非流式生成摘要,工具调用关闭,旧摘要作为首个 user 轮,摘要提示词作为末尾 user 轮 func (s *server) compactionSummary(ctx context.Context, request responsesRequest, items []json.RawMessage, previous, id string) (string, *aistudio.Usage, error) { prompt := compactionSummaryPrompt @@ -377,21 +402,7 @@ func (s *server) compactionSummary(ctx context.Context, request responsesRequest if err := inlineRemoteMedia(ctx, generate.Contents); err != nil { return "", nil, err } - generate.Contents = append(generate.Contents, aistudio.Content{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: fmt.Sprintf(compactionInstructions, prompt)}}}) - generate.Tools.ToolConfig.Mode = "none" - generate.Unary = true - events, err := s.service.Generate(ctx, generate) - if err != nil { - return "", nil, err - } - result, err := consumeEvents(ctx, events) - if err != nil { - return "", nil, err - } - if result.finishReason != "stop" { - return "", nil, fmt.Errorf("compaction summary finished with %s", result.finishReason) - } - return strings.TrimSpace(result.text.String()), result.usage, nil + return s.generateCompactionSummary(ctx, generate, fmt.Sprintf(compactionInstructions, prompt)) } // handleResponsesCompact 返回保留的 user 消息与一个 compaction 项 diff --git a/internal/api/responses_retrieval.go b/internal/api/responses_retrieval.go index 62d4857c..96ba63fc 100644 --- a/internal/api/responses_retrieval.go +++ b/internal/api/responses_retrieval.go @@ -18,6 +18,7 @@ func (s *server) handleResponsesInputTokens(w http.ResponseWriter, r *http.Reque return } prepared, err := s.prepareResponses(r.Context(), &request, newID("count"), false) + request.Input, request.split = nil, splitInput{} if err != nil { if shouldWriteRequestError(r, err) { writeOpenAIError(w, http.StatusBadRequest, "invalid_request", err.Error()) @@ -90,6 +91,10 @@ 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) @@ -100,16 +105,22 @@ func (s *server) handleResponseDelete(w http.ResponseWriter, r *http.Request) { // handleResponseCancel 终止进行中的后台响应并返回保存的 cancelled 对象,已结束的后台响应返回最终对象,其他响应不可取消 func (s *server) handleResponseCancel(w http.ResponseWriter, r *http.Request) { - s.stopBackground(r.PathValue("response")) - response, background, ok := s.responseStates.Response(r.PathValue("response"), nil) + id := r.PathValue("response") + response, background, ok := s.responseStates.Response(id, nil) if !ok { - writeResponseNotFound(w, r.PathValue("response")) + writeResponseNotFound(w, id) 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 cb9a38ee..c6afba75 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -157,7 +157,7 @@ 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(requestBodyMiddleware(config.Ledger, waitLaunchMiddleware(config.WaitLaunch, s.catalogRead, public))))))) + publicHandler := bodyLimitMiddleware(browserOriginMiddleware(config.APIKey, authMiddleware(config.APIKey, apiKeyContextMiddleware(config.APIKey, 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) diff --git a/internal/app/admin.go b/internal/app/admin.go index 30fcf369..60805b49 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -215,41 +215,84 @@ func (admin *runtimeAdmin) CreateAccount(ctx context.Context, input api.AccountC admin.requests.logStage("auth", "ERROR", api.LogStage{Name: "账户添加", State: "failed"}, "账户添加失败", "duration", time.Since(startedAt), "error", err) } }() - admin.requests.logStage("auth", "INFO", api.LogStage{Name: "账户添加", Step: 1, Steps: 2}, "等待隔离登录") + admin.requests.logStage("auth", "INFO", api.LogStage{Name: "账户添加", Step: 1, Steps: 3}, "等待隔离登录") api.ReportTaskStep(ctx, api.TaskStepLogin) + var savedID string + var savedLabel string + saveAccount := func(saveCtx context.Context, logged aistudio.IsolatedLoginResult) (*runtimeAdmin, *aistudio.Account, error) { + if logged.DriveError != "" { + admin.requests.logStage("auth", "WARN", api.LogStage{Name: "账户添加"}, "Drive 授权失败", "error", logged.DriveError) + } + admin.requests.logStage("auth", "INFO", api.LogStage{Name: "账户添加", Step: 2, Steps: 3}, "保存认证状态") + api.ReportTaskStep(ctx, api.TaskStepSaving) + if _, authErr := aistudio.NewSigner().Authorization(logged.StorageState); authErr != nil { + return nil, nil, fmt.Errorf("认证状态无法用于 AI Studio: %w", authErr) + } + accountConfig.Label = logged.Email + if valErr := accountConfig.Validate(); valErr != nil { + return nil, nil, invalidAccount(valErr) + } + target, done := admin.accountCommit() + account, upsertErr := target.upsertAccount(saveCtx, accountConfig.Label, accountConfig, logged.StorageState, directory) + done() + if upsertErr != nil { + return nil, nil, upsertErr + } + return target, account, nil + } result, err := admin.login.Login(ctx, aistudio.IsolatedLoginRequest{ - Directory: directory, Proxy: admin.effectiveProxy(accountConfig.Proxy), - Locale: accountConfig.Locale, Timezone: accountConfig.Timezone, View: view, + Directory: directory, + Proxy: admin.effectiveProxy(accountConfig.Proxy), + Locale: accountConfig.Locale, + Timezone: accountConfig.Timezone, + View: view, + OnLoggedIn: func(saveCtx context.Context, logged aistudio.IsolatedLoginResult) error { + target, account, saveErr := saveAccount(saveCtx, logged) + if saveErr != nil { + return saveErr + } + savedID, savedLabel = account.ID, account.Config.Label + api.ReportTaskLabel(ctx, savedLabel) + target.publishRuntimeSnapshot(target.lifecycle) + return nil + }, + CheckVerification: func(checkCtx context.Context, updated aistudio.StorageState) (bool, error) { + if savedID == "" { + return false, nil + } + admin.requests.logStage(savedLabel, "INFO", api.LogStage{Name: "账户添加", Step: 3, Steps: 3}, "核对账户验证状态") + target, done := admin.accountCommit() + defer done() + return target.verifyAccountNow(checkCtx, savedID, updated) + }, + OnVerifyStep: func(step string) { reportAccountVerifyStep(ctx, step) }, }) if err != nil { return api.AdminAccount{}, err } - if result.DriveError != "" { - admin.requests.logStage("auth", "WARN", api.LogStage{Name: "账户添加"}, "Drive 授权失败", "error", result.DriveError) - } if result.CloseError != "" { - admin.requests.logStage("auth", "WARN", api.LogStage{Name: "账户添加"}, "关闭 Camoufox 失败", "error", result.CloseError) + admin.requests.logStage(cmp.Or(savedLabel, "auth"), "WARN", api.LogStage{Name: "账户添加"}, "关闭 Camoufox 失败", "error", result.CloseError) } - admin.requests.logStage("auth", "INFO", api.LogStage{Name: "账户添加", Step: 2, Steps: 2}, "保存认证状态") - api.ReportTaskStep(ctx, api.TaskStepSaving) - if _, err := aistudio.NewSigner().Authorization(result.StorageState); err != nil { - return api.AdminAccount{}, fmt.Errorf("认证状态无法用于 AI Studio: %w", err) - } - accountConfig.Label = result.Email - if err := accountConfig.Validate(); err != nil { - return api.AdminAccount{}, invalidAccount(err) - } - target, done := admin.accountCommit() - account, err := target.upsertAccount(ctx, accountConfig.Label, accountConfig, result.StorageState, directory) - done() - if err != nil { - return api.AdminAccount{}, err + var created api.AdminAccount + if result.Saved { + if result.VerificationError != "" { + admin.requests.logStage(savedLabel, "WARN", api.LogStage{Name: "账户添加"}, "账户验证核对失败", "error", result.VerificationError) + } + target, done := admin.accountCommit() + created, err = target.account(savedID) + done() + } else { + var target *runtimeAdmin + var account *aistudio.Account + target, account, err = saveAccount(ctx, result) + if err == nil { + created, err = target.verifiedAccount(account) + } } - created, err := target.syncedAccount(account) if err != nil { return api.AdminAccount{}, err } - admin.requests.logStage("auth", "INFO", api.LogStage{Name: "账户添加", State: "completed"}, "账户添加完成", "account", created.Label, "duration", time.Since(startedAt)) + admin.requests.logStage(cmp.Or(savedLabel, "auth"), "INFO", api.LogStage{Name: "账户添加", State: "completed"}, "账户添加完成", "account", created.Label, "duration", time.Since(startedAt)) return created, nil } @@ -266,7 +309,51 @@ func (admin *runtimeAdmin) ChromeImportProfiles(context.Context) ([]api.ChromeIm if err != nil { return nil, err } - return chromeImportProfiles(accounts, admin.accountIDs(), recorded), nil + profiles := chromeImportProfiles(accounts, admin.accountIDs(), recorded) + return enrichChromeImportProfiles(profiles, admin.pool.Status()), nil +} + +// enrichChromeImportProfiles 为已存在于账户池的 Chrome 候选补上已导入标记与已知权益 +func enrichChromeImportProfiles(profiles []api.ChromeImportProfile, statuses []aistudio.AccountStatus) []api.ChromeImportProfile { + existing := make(map[string]aistudio.AccountStatus, len(statuses)) + for _, status := range statuses { + existing[strings.ToLower(strings.TrimSpace(status.ID))] = status + } + for index := range profiles { + status, ok := existing[strings.ToLower(strings.TrimSpace(profiles[index].Email))] + if !ok { + continue + } + profiles[index].Imported = true + if status.BenefitTier != "" && status.BenefitTier != "Unknown" { + profiles[index].BenefitTier = status.BenefitTier + } + } + return profiles +} + +// 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 + } + proxyURL := admin.effectiveProxy(input.Proxy) + return chromeauth.CheckProfileTiers(ctx, chromeauth.ImportOptions{ + ChromeRoot: root, Proxy: proxyURL, AccountIDs: input.AccountIDs, + }, func(result chromeauth.ProfileTierResult) { + if emit != nil { + emit(api.ChromeProfileTier{ + ID: result.ID, + BenefitTier: result.BenefitTier, + Restricted: result.Restricted, + Error: result.Error, + }) + } + }) } // chromeImportProfiles 返回可导入的 Chrome 账户,已导入且未受限的账户不列出,服务受限的已导入账户与导入时被拒绝的账户带受限原因 @@ -370,7 +457,7 @@ func (admin *runtimeAdmin) DiscoverCookieAccounts(ctx context.Context, input api // deviceBoundSession 表示 Cookie 带 __Secure-1PSIDRTS,会话绑定签发它的设备 func deviceBoundSession(state aistudio.StorageState) bool { - return slices.ContainsFunc(state.Cookies, func(cookie aistudio.StateCookie) bool { return cookie.Name == "__Secure-1PSIDRTS" }) + return state.HasBoundCookie() } // cookieAccountEntries 以 template 为模板为每个会话账户生成一项,按账户池状态 statuses 标记已导入、需要重新登录与服务受限的账户,没有账户时只返回 template @@ -385,9 +472,12 @@ func cookieAccountEntries(template api.CookieBrowser, accounts []chromeauth.Cook entries := make([]api.CookieBrowser, len(accounts)) for index, account := range accounts { entry := template - entry.Email, entry.AuthUser, entry.Restricted = account.Email, account.AuthUser, account.Restricted + entry.Email, entry.AuthUser, entry.Restricted, entry.BenefitTier = account.Email, account.AuthUser, account.Restricted, account.BenefitTier if status, imported := existing[account.Email]; imported { entry.Imported, entry.SignInRequired = true, status.State == aistudio.AccountAuthRequired + if entry.BenefitTier == "" && status.BenefitTier != "" && status.BenefitTier != "Unknown" { + entry.BenefitTier = status.BenefitTier + } if status.State == aistudio.AccountRestricted && status.Message != "" { entry.Restricted = status.Message } @@ -490,6 +580,7 @@ func (admin *runtimeAdmin) ImportChromeAccounts(ctx context.Context, input api.C } seen[email] = struct{}{} accountConfig := aistudio.DefaultAccountConfig(email) + accountConfig.Note = aistudio.TruncateAccountNote(result.DisplayName) accountConfig.Proxy = accountProxy accountConfig.Locale, accountConfig.Timezone = locale, timezone if err := accountConfig.Validate(); err != nil { @@ -559,6 +650,7 @@ func (admin *runtimeAdmin) ImportAccountState(ctx context.Context, input api.Acc label = strings.ToLower(verification.Email) } accountConfig := aistudio.DefaultAccountConfig(label) + accountConfig.Note = aistudio.TruncateAccountNote(input.Note) accountConfig.AuthUser = input.AuthUser accountConfig.Proxy = strings.TrimSpace(input.Proxy) exit := environment() @@ -640,7 +732,7 @@ func (admin *runtimeAdmin) syncedAccount(account *aistudio.Account) (api.AdminAc return admin.account(account.ID) } -// upsertAccount 在 id 对应的账户已存在时就地更新其认证状态并保留运行态资源绑定,否则以 accountConfig 新增账户 +// upsertAccount 在 id 对应的账户已存在时就地更新其认证状态并保留运行态资源绑定(原备注为空时才填入默认备注),否则以 accountConfig 新增账户 func (admin *runtimeAdmin) upsertAccount( ctx context.Context, id string, @@ -649,7 +741,7 @@ func (admin *runtimeAdmin) upsertAccount( fingerprintDirectory string, ) (*aistudio.Account, error) { if existing := admin.accountID(id); existing != "" { - return admin.updateImportedAccount(ctx, existing, accountConfig.AuthUser, state, fingerprintDirectory) + return admin.updateImportedAccount(ctx, existing, accountConfig.AuthUser, accountConfig.Note, state, fingerprintDirectory) } return admin.addAccount(accountConfig, state, fingerprintDirectory) } @@ -664,11 +756,12 @@ func (admin *runtimeAdmin) accountID(id string) string { return "" } -// updateImportedAccount 就地替换已有账户的 Cookie、认证材料与会话序号,保留 runtime-state.json 中的文件资源绑定与模型资格 +// updateImportedAccount 就地替换已有账户的 Cookie、认证材料与会话序号,保留 runtime-state.json 中的文件资源绑定与模型资格,仅在账户备注为空时补填 defaultNote func (admin *runtimeAdmin) updateImportedAccount( ctx context.Context, accountID string, authUser int, + defaultNote string, state aistudio.StorageState, fingerprintDirectory string, ) (*aistudio.Account, error) { @@ -683,7 +776,7 @@ func (admin *runtimeAdmin) updateImportedAccount( if err := replaceAccountState(lease, state, fingerprintDirectory); err != nil { return nil, errors.Join(err, lease.Release()) } - if err := setCookieAuthUser(lease, authUser, admin.workers.prepareUpdate); err != nil { + if err := setImportedAccountConfig(lease, authUser, defaultNote, admin.workers.prepareUpdate); err != nil { return nil, errors.Join(err, lease.Release()) } if err := admin.service.changeModels(func() error { @@ -800,6 +893,7 @@ func (admin *runtimeAdmin) saveAccountConfig(ctx context.Context, accountID stri return api.AdminAccount{}, nil, invalidAccount(fmt.Errorf("账户邮箱不可修改")) } accountConfig := aistudio.DefaultAccountConfig(strings.ToLower(strings.TrimSpace(accountID))) + accountConfig.Note = strings.TrimSpace(input.Note) accountConfig.Enabled = input.Enabled accountConfig.Proxy = strings.TrimSpace(input.Proxy) accountConfig.Locale = strings.TrimSpace(input.Locale) @@ -815,9 +909,21 @@ func (admin *runtimeAdmin) saveAccountConfig(ctx context.Context, accountID stri if err != nil { return api.AdminAccount{}, nil, err } - if current.Enabled != accountConfig.Enabled && current.Proxy == accountConfig.Proxy && - current.Locale == accountConfig.Locale && current.Timezone == accountConfig.Timezone { - updated, err := admin.setAccountEnabled(accountID, accountConfig.Enabled) + if current.Proxy == accountConfig.Proxy && current.Locale == accountConfig.Locale && current.Timezone == accountConfig.Timezone { + if current.Note != accountConfig.Note { + if _, err := admin.pool.SetNote(accountID, accountConfig.Note); err != nil { + return api.AdminAccount{}, nil, accountOperationError(err) + } + } + if current.Enabled != accountConfig.Enabled { + updated, err := admin.setAccountEnabled(accountID, accountConfig.Enabled) + return updated, nil, err + } + if current.Note != accountConfig.Note { + admin.requests.log("auth", "INFO", "账户配置已更新", "account", accountConfig.Label) + admin.publishRuntimeSnapshot(admin.lifecycle) + } + updated, err := admin.account(accountID) return updated, nil, err } lease, err := admin.acquireAccount(ctx, accountID) @@ -1013,40 +1119,242 @@ func (admin *runtimeAdmin) LoginAccount(ctx context.Context, accountID string, v admin.requests.logStage(label, "ERROR", api.LogStage{Name: "账户登录", State: "failed"}, "账户登录失败", "duration", time.Since(startedAt), "error", err) } }() - admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", Step: 1, Steps: 2}, "等待隔离登录") + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", Step: 1, Steps: 3}, "等待隔离登录") api.ReportTaskStep(ctx, api.TaskStepLogin) request := admin.loginRequest(account, directory) request.View = view + saveAccount := func(saveCtx context.Context, logged aistudio.IsolatedLoginResult) (*runtimeAdmin, *aistudio.Account, error) { + if !strings.EqualFold(strings.TrimSpace(logged.Email), account.ID) { + return nil, nil, invalidAccount(fmt.Errorf("登录邮箱与账户不一致: %s", logged.Email)) + } + if logged.DriveError != "" { + admin.requests.logStage(label, "WARN", api.LogStage{Name: "账户登录"}, "Drive 授权失败", "error", logged.DriveError) + } + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", Step: 2, Steps: 3}, "保存认证状态") + api.ReportTaskStep(ctx, api.TaskStepSaving) + if _, authErr := aistudio.NewSigner().Authorization(logged.StorageState); authErr != nil { + return nil, nil, fmt.Errorf("认证状态无法用于 AI Studio: %w", authErr) + } + target, done := admin.accountCommit() + saved, saveErr := target.saveLogin(saveCtx, accountID, logged.StorageState, directory) + done() + if saveErr != nil { + return nil, nil, saveErr + } + return target, saved, nil + } + request.OnLoggedIn = func(saveCtx context.Context, logged aistudio.IsolatedLoginResult) error { + target, _, saveErr := saveAccount(saveCtx, logged) + if saveErr != nil { + return saveErr + } + target.publishRuntimeSnapshot(target.lifecycle) + return nil + } + request.CheckVerification = func(checkCtx context.Context, updated aistudio.StorageState) (bool, error) { + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", Step: 3, Steps: 3}, "核对账户验证状态") + target, done := admin.accountCommit() + defer done() + return target.verifyAccountNow(checkCtx, accountID, updated) + } + request.OnVerifyStep = func(step string) { reportAccountVerifyStep(ctx, step) } result, err := admin.login.Login(ctx, request) if err != nil { return api.AdminAccount{}, err } - if !strings.EqualFold(strings.TrimSpace(result.Email), account.ID) { - return api.AdminAccount{}, invalidAccount(fmt.Errorf("登录邮箱与账户不一致: %s", result.Email)) - } - if result.DriveError != "" { - admin.requests.logStage(label, "WARN", api.LogStage{Name: "账户登录"}, "Drive 授权失败", "error", result.DriveError) - } if result.CloseError != "" { admin.requests.logStage(label, "WARN", api.LogStage{Name: "账户登录"}, "关闭 Camoufox 失败", "error", result.CloseError) } - admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", Step: 2, Steps: 2}, "保存认证状态") - api.ReportTaskStep(ctx, api.TaskStepSaving) - if _, err := aistudio.NewSigner().Authorization(result.StorageState); err != nil { - return api.AdminAccount{}, fmt.Errorf("认证状态无法用于 AI Studio: %w", err) + var saved api.AdminAccount + if result.Saved { + if result.VerificationError != "" { + admin.requests.logStage(label, "WARN", api.LogStage{Name: "账户登录"}, "账户验证核对失败", "error", result.VerificationError) + } + target, done := admin.accountCommit() + saved, err = target.account(accountID) + done() + } else { + var target *runtimeAdmin + target, account, err = saveAccount(ctx, result) + if err == nil { + saved, err = target.verifiedAccount(account) + } + } + if err != nil { + return api.AdminAccount{}, err + } + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", State: "completed"}, "账户登录完成", "duration", time.Since(startedAt)) + return saved, nil +} + +// VerifyAccount 打开停在官网验证页的 Camoufox 窗口供用户完成验证,并在页面变化或定时自动再核对,验证通过后自动关闭窗口恢复就绪 +func (admin *runtimeAdmin) VerifyAccount(ctx context.Context, accountID string, view *camoufoxnative.LiveView) (_ api.AdminAccount, err error) { + account, err := admin.pool.Account(accountID) + if err != nil { + return api.AdminAccount{}, accountOperationError(err) + } + verifier, ok := admin.login.(aistudio.AccountVerifyDriver) + if !ok { + return api.AdminAccount{}, fmt.Errorf("当前登录驱动不支持打开验证窗口") + } + state, loadErr := aistudio.LoadStorageState(account.StoragePath) + if loadErr != nil { + state = account.StorageState + } + if len(state.Cookies) == 0 { + return api.AdminAccount{}, fmt.Errorf("账户没有可用于验证的 Cookie") + } + directory, err := os.MkdirTemp("", "aistudio2api-account-verify-*") + if err != nil { + return api.AdminAccount{}, fmt.Errorf("创建隔离验证目录: %w", err) + } + defer os.RemoveAll(directory) + if err := camoufoxnative.PersistAccountFingerprint(account.Directory, directory); err != nil { + return api.AdminAccount{}, err + } + startedAt := time.Now() + label := account.Config.Label + defer func() { + if err != nil { + admin.requests.logStage(label, "ERROR", api.LogStage{Name: "账户验证", State: "failed"}, "账户验证失败", "duration", time.Since(startedAt), "error", err) + } + }() + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户验证", Step: 1, Steps: 2}, "等待完成账户验证") + api.ReportTaskStep(ctx, api.TaskStepVerify) + pending, err := verifier.Verify(ctx, aistudio.AccountVerifyRequest{ + Directory: directory, + StorageState: state, + AuthUser: account.Config.AuthUser, + Proxy: account.EffectiveProxy(admin.globalProxy), + Locale: account.Config.Locale, + Timezone: account.Config.Timezone, + View: view, + CheckVerification: func(checkCtx context.Context, updated aistudio.StorageState) (bool, error) { + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户验证", Step: 2, Steps: 2}, "核对账户验证状态") + target, done := admin.accountCommit() + defer done() + return target.verifyAccountNow(checkCtx, accountID, updated) + }, + OnVerifyStep: func(step string) { reportAccountVerifyStep(ctx, step) }, + }) + if err != nil { + return api.AdminAccount{}, err } target, done := admin.accountCommit() - account, err = target.saveLogin(ctx, accountID, result.StorageState, directory) + current, err := target.account(accountID) done() if err != nil { return api.AdminAccount{}, err } - saved, err := target.syncedAccount(account) + message := "账户验证完成" + if pending || current.VerificationRequired { + message = "账户验证窗口已关闭,账户仍需要验证" + } + admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户验证", State: "completed"}, message, "duration", time.Since(startedAt)) + return current, nil +} + +// reportAccountVerifyStep 把验证阶段的步骤映射并报告到账户任务 +func reportAccountVerifyStep(ctx context.Context, step string) { + switch step { + case "verifying": + api.ReportTaskStep(ctx, api.TaskStepVerifying) + case "verify": + api.ReportTaskStep(ctx, api.TaskStepVerify) + } +} + +// verifiedAccount 在后台同步账户目录并核对一次验证状态,立即返回账户 +func (admin *runtimeAdmin) verifiedAccount(account *aistudio.Account) (api.AdminAccount, error) { + admin.cancelTransition(account.ID) + admin.startTransition(account.ID, aistudio.AccountSyncing, func(ctx context.Context) { + verifyCtx := aistudio.ContextWithRefreshSteps(ctx, func(step aistudio.AccountStep, _, _ int) { + if step == aistudio.AccountStepWaiting { + admin.requests.log("auth", "INFO", refreshStepMessages[step], "account", account.ID) + } + admin.pool.SetTransition(account.ID, aistudio.AccountSyncing, step) + admin.publishRuntimeSnapshot(admin.lifecycle) + }) + if err := admin.service.verifyAccount(verifyCtx, account.ID); err != nil { + if ctx.Err() == nil { + admin.requests.log(account.Config.Label, "WARN", "账户验证核对失败", "error", err) + } + return + } + if admin.pool.VerificationRequired(account.ID) { + admin.requests.log(account.Config.Label, "WARN", "账户需要验证") + return + } + admin.requests.log(account.Config.Label, "INFO", "账户核对完成") + }) + return admin.account(account.ID) +} + +// verifyAccountNow 在账户行显示核对步骤并执行一次目录同步与生成核对,返回账户是否仍需要验证 +func (admin *runtimeAdmin) verifyAccountNow(ctx context.Context, accountID string, updated aistudio.StorageState) (bool, error) { + admin.cancelTransition(accountID) + if len(updated.Cookies) > 0 { + if err := admin.syncVerifiedCookies(ctx, accountID, updated); err != nil { + return admin.pool.VerificationRequired(accountID), err + } + } + admin.pool.SetTransition(accountID, aistudio.AccountSyncing, aistudio.AccountStepCatalog) + admin.publishRuntimeSnapshot(admin.lifecycle) + verifyCtx := aistudio.ContextWithRefreshSteps(ctx, func(step aistudio.AccountStep, _, _ int) { + if step == aistudio.AccountStepWaiting { + admin.requests.log("auth", "INFO", refreshStepMessages[step], "account", accountID) + } + admin.pool.SetTransition(accountID, aistudio.AccountSyncing, step) + admin.publishRuntimeSnapshot(admin.lifecycle) + }) + err := admin.service.verifyAccount(verifyCtx, accountID) + admin.pool.SetTransition(accountID, "", "") + admin.publishRuntimeSnapshot(admin.lifecycle) + return admin.pool.VerificationRequired(accountID), err +} + +// syncVerifiedCookies 把验证浏览器导出的最新 Cookie 写回账户(保留原 AuthExtension),认证签名 Cookie 变化时重置 Worker +func (admin *runtimeAdmin) syncVerifiedCookies(ctx context.Context, accountID string, updated aistudio.StorageState) error { + if len(updated.Cookies) == 0 { + return nil + } + lease, err := admin.pool.AcquireAccount(ctx, accountID) if err != nil { - return api.AdminAccount{}, err + return err } - admin.requests.logStage(label, "INFO", api.LogStage{Name: "账户登录", State: "completed"}, "账户登录完成", "duration", time.Since(startedAt)) - return saved, nil + previous := lease.Account().StorageState.Cookies + if slices.Equal(previous, updated.Cookies) { + return lease.Release() + } + changed := signingCookiesChanged(previous, updated.Cookies) + err = lease.ReplaceCookies(updated.Cookies) + releaseErr := lease.Release() + if err = errors.Join(err, releaseErr); err != nil { + return err + } + if changed { + return admin.workers.Reset(accountID) + } + return nil +} + +// signingCookiesChanged 判断两次 Cookie 集合中 Google 认证签名 Cookie 是否变化 +func signingCookiesChanged(previous, next []aistudio.StateCookie) bool { + names := []string{"SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID", "__Secure-1PSID", "__Secure-3PSID"} + lookup := func(list []aistudio.StateCookie, name string) string { + for _, cookie := range list { + if cookie.Name == name && cookie.Domain == ".google.com" { + return cookie.Value + } + } + return "" + } + for _, name := range names { + if lookup(previous, name) != lookup(next, name) { + return true + } + } + return false } // saveLogin 以浏览器登录得到的认证状态与指纹目录替换账户的登录状态,重建该账户的 Worker 并返回账户 @@ -1091,6 +1399,34 @@ func replaceAccountState(lease *aistudio.AccountLease, state aistudio.StorageSta return lease.SaveStorageState(state) } +// setImportedAccountConfig 在重新导入时同步会话序号,并在原备注为空时填入 defaultNote +func setImportedAccountConfig(lease *aistudio.AccountLease, authUser int, defaultNote string, prepare func(*aistudio.Account, aistudio.AccountConfig) (*accountWorkerUpdate, error)) error { + account := lease.Account() + fillNote := strings.TrimSpace(account.Config.Note) == "" && strings.TrimSpace(defaultNote) != "" + if account.Config.AuthUser == authUser && !fillNote { + return nil + } + accountConfig := account.Config + authUserChanged := accountConfig.AuthUser != authUser + accountConfig.AuthUser = authUser + if fillNote { + accountConfig.Note = aistudio.TruncateAccountNote(defaultNote) + } + if !authUserChanged { + return lease.SaveConfig(accountConfig) + } + 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 +} + // setCookieAuthUser 把账户 Cookie 的会话序号改为 authUser 并同步到 Worker func setCookieAuthUser(lease *aistudio.AccountLease, authUser int, prepare func(*aistudio.Account, aistudio.AccountConfig) (*accountWorkerUpdate, error)) error { account := lease.Account() @@ -1307,12 +1643,14 @@ func (admin *runtimeAdmin) loginRequest(account *aistudio.Account, directory str func adminAccountDTO(status aistudio.AccountStatus) api.AdminAccount { account := api.AdminAccount{ - ID: status.ID, Label: status.Label, Enabled: status.Enabled, State: string(status.State), + ID: status.ID, Label: status.Label, Note: status.Note, Enabled: status.Enabled, State: string(status.State), 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), } if status.Transition != "" { account.TransitionSince = &status.TransitionSince @@ -1391,7 +1729,8 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt 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: strings.TrimSpace(value.ContinuationPrompt), - FirstEventHedge: strings.ToLower(strings.TrimSpace(value.FirstEventHedge)), FirstEventHedgeModels: strings.TrimSpace(value.FirstEventHedgeModels), AuthStates: value.AuthStates, ListenAddr: value.ListenAddr, PreviewListenAddr: value.PreviewListenAddr, + ReplyTool: value.ReplyTool, UserMessageRewrite: strings.ToLower(strings.TrimSpace(value.UserMessageRewrite)), ThinkingGuard: value.ThinkingGuard, + FirstEventHedge: strings.ToLower(strings.TrimSpace(value.FirstEventHedge)), FirstEventHedgeModels: strings.TrimSpace(value.FirstEventHedgeModels), FirstEventTimeout: strings.ToLower(strings.TrimSpace(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, @@ -1744,7 +2083,8 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig { NonstreamKeepalive: cfg.NonstreamKeepalive, FakeStream: cfg.FakeStream, YouTubeLinks: cfg.YouTubeLinks, SearchModelAliases: cfg.SearchModelAliases, DiscoverHiddenModels: cfg.DiscoverHiddenModels, GoogleSearch: cfg.GoogleSearch, StripThoughtSignatures: cfg.StripThoughtSignatures, ContinuationRewrite: cfg.ContinuationRewrite, ContinuationPrompt: cfg.ContinuationPrompt, - FirstEventHedge: cfg.FirstEventHedge, FirstEventHedgeModels: cfg.FirstEventHedgeModels, AuthStates: cfg.AuthStates, ListenAddr: cfg.ListenAddr, APIKey: cfg.ProxyAPIKey, + 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, PreviewListenAddr: cfg.PreviewListenAddr, ActivePreviewListenAddr: cfg.PreviewListenAddr, Proxy: cfg.Proxy, InitTimeout: cfg.InitTimeout.String(), RequestTimeout: cfg.RequestTimeout.String(), diff --git a/internal/app/admin_config_test.go b/internal/app/admin_config_test.go index fb709a3f..5951cc61 100644 --- a/internal/app/admin_config_test.go +++ b/internal/app/admin_config_test.go @@ -26,7 +26,7 @@ func TestAdminConfig(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() pool := aistudio.NewAccountPool(nil, 1) - admin := &runtimeAdmin{configPath: path, requests: newRequestRegistry(ctx), pool: pool, service: &trackedService{pool: pool}} + admin := &runtimeAdmin{configPath: path, requests: newRequestRegistry(), pool: pool, service: &trackedService{pool: pool}} value, err := admin.RuntimeConfig(ctx) if err != nil { t.Fatal(err) diff --git a/internal/app/app.go b/internal/app/app.go index 90caed60..6fdfe1ae 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -138,6 +138,7 @@ func runService(ctx context.Context, cancel func(), cfg config.Config, options c if err != nil { return false, err } + defer manager.requests.close() logService := func(level, message string, attrs ...any) { manager.requests.log("service", level, message, attrs...) } diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go index 7078fe57..d59ee17e 100644 --- a/internal/app/auth_retry.go +++ b/internal/app/auth_retry.go @@ -168,7 +168,7 @@ func newAuthRuntimeRefresher( // importCurrentChromeState 从原来源中更新同一 Google 账户的认证材料 func importCurrentChromeState(ctx context.Context, source aistudio.AuthSource, material aistudio.ChromeOAuthMaterial, proxy string) (aistudio.StorageState, error) { - root, err := chromeauth.DefaultChromeRoot() + root, err := chromeauth.ChromeRoot(source.Root) if err != nil { return aistudio.StorageState{}, err } @@ -460,8 +460,54 @@ func (refresher *authRuntimeRefresher) ensureBound(ctx context.Context) error { if !ok { return nil } + account := lease.Account() + return refresher.ensureBoundWith( + ctx, + account.ID, + account.EffectiveProxy(refresher.globalProxy), + lease.ReloadStorageState, + lease.MergeSetCookieHeaders, + ) +} + +// ensureBoundAccount 为指定账户刷新即将到期的 DBSC 会话并写回磁盘与当前 Worker,ctx 带有同账户租约时直接经租约读写 +func (refresher *authRuntimeRefresher) ensureBoundAccount(ctx context.Context, accountID string) error { + if lease, ok := aistudio.AccountLeaseFromContext(ctx); ok && lease.Account().ID == accountID { + return refresher.ensureBound(ctx) + } + if refresher.pool == nil { + return nil + } + account, err := refresher.pool.Account(accountID) + if err != nil { + return err + } + return refresher.ensureBoundWith( + ctx, + account.ID, + account.EffectiveProxy(refresher.globalProxy), + func() (aistudio.StorageState, error) { + return refresher.pool.ReloadStorageState(account.ID) + }, + func(headers []string, requestURL string, now time.Time) error { + return refresher.pool.MergeSetCookieHeaders(account.ID, headers, requestURL, now) + }, + ) +} + +// ensureBoundWith 按账户级互斥锁在 DBSC 绑定 Cookie 剩余不足 boundRefreshThreshold 时刷新并写回账户与当前 Worker +func (refresher *authRuntimeRefresher) ensureBoundWith( + ctx context.Context, + accountID string, + proxy string, + reload func() (aistudio.StorageState, error), + merge func([]string, string, time.Time) error, +) error { + if refresher.rotate == nil { + return nil + } due := func() (aistudio.StorageState, aistudio.AuthExtension, bool, error) { - state, err := lease.ReloadStorageState() + state, err := reload() if err != nil { return state, aistudio.AuthExtension{}, false, err } @@ -474,8 +520,7 @@ func (refresher *authRuntimeRefresher) ensureBound(ctx context.Context) error { if _, _, refresh, err := due(); err != nil || !refresh { return err } - account := lease.Account() - value, _ := refresher.boundLocks.LoadOrStore(account.ID, &sync.Mutex{}) + value, _ := refresher.boundLocks.LoadOrStore(accountID, &sync.Mutex{}) mu := value.(*sync.Mutex) mu.Lock() defer mu.Unlock() @@ -483,17 +528,20 @@ func (refresher *authRuntimeRefresher) ensureBound(ctx context.Context) error { if err != nil || !refresh { return err } - headers, err := refresher.rotate(ctx, state, extension, account.EffectiveProxy(refresher.globalProxy)) + headers, err := refresher.rotate(ctx, state, extension, proxy) if errors.Is(err, chromeauth.ErrBoundSessionRejected) { return errors.Join(camoufoxnative.ErrAuthenticationRequired, err) } if err != nil { - return fmt.Errorf("刷新账户 %s DBSC 会话: %w", account.ID, err) + return fmt.Errorf("刷新账户 %s DBSC 会话: %w", accountID, err) } - if err := lease.MergeSetCookieHeaders(headers, extension.Bound.RefreshURL, time.Now()); err != nil { - return fmt.Errorf("保存账户 %s DBSC 会话 Cookie: %w", account.ID, err) + if err := merge(headers, extension.Bound.RefreshURL, time.Now()); err != nil { + return fmt.Errorf("保存账户 %s DBSC 会话 Cookie: %w", accountID, err) + } + if refresher.mergeWorker == nil { + return nil } - return refresher.mergeWorker(ctx, account.ID, headers, extension.Bound.RefreshURL) + return refresher.mergeWorker(ctx, accountID, headers, extension.Bound.RefreshURL) } // Available 返回当前租约账户是否保存了 Chrome OAuth 续签材料 @@ -521,7 +569,7 @@ func authenticationFailed(response *aistudio.RPCResponse) bool { func readAuthenticationFailure(method string, response *aistudio.RPCResponse) (*aistudio.RPCError, error) { body, readErr := io.ReadAll(response.Body) if err := errors.Join(readErr, response.Body.Close()); err != nil { - return nil, fmt.Errorf("读取认证失败响应: %w", err) + return nil, &aistudio.ResponseReadError{Err: fmt.Errorf("读取认证失败响应: %w", err)} } return aistudio.DecodeRPCError(method, response.StatusCode, body), nil } diff --git a/internal/app/auth_retry_test.go b/internal/app/auth_retry_test.go index 3568a685..3b622a92 100644 --- a/internal/app/auth_retry_test.go +++ b/internal/app/auth_retry_test.go @@ -37,7 +37,7 @@ func TestAuthRefreshKeepsAccountSource(t *testing.T) { 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(t.Context()), + 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{ diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 5673e10d..887ccdfd 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -2,6 +2,7 @@ package app import ( "context" + "errors" "net/http" "reflect" "slices" @@ -35,6 +36,7 @@ type generationAdmin interface { AccountExits(context.Context) ([]api.AccountExit, error) CreateAccount(context.Context, api.AccountCreateInput, *camoufoxnative.LiveView) (api.AdminAccount, error) ChromeImportProfiles(context.Context) ([]api.ChromeImportProfile, error) + CheckChromeImportTiers(context.Context, api.ChromeTierCheckInput, func(api.ChromeProfileTier)) error CookieBrowsers(ctx context.Context, proxy string) ([]api.CookieBrowser, error) DiscoverCookieAccounts(context.Context, api.CookieImportInput) ([]api.CookieBrowser, error) ImportChromeAccounts(context.Context, api.ChromeImportInput) ([]api.AdminAccount, error) @@ -44,6 +46,7 @@ type generationAdmin interface { SetAccountState(ctx context.Context, accountID string, state string) (api.AdminAccount, error) DeleteAccount(context.Context, string) error LoginAccount(context.Context, string, *camoufoxnative.LiveView) (api.AdminAccount, error) + VerifyAccount(context.Context, string, *camoufoxnative.LiveView) (api.AdminAccount, error) RefreshAccount(context.Context, string) (api.AdminAccountRefresh, error) StartService(context.Context) (api.AdminStatus, error) StopService(context.Context) (api.AdminStatus, error) @@ -143,16 +146,18 @@ func newRuntimeManager( cfg config.Config, overrides dataConfigOverrides, ) (*runtimeManager, error) { - requests := newRequestRegistry(ctx) + requests := newRequestRegistry() manager := &runtimeManager{ lifecycle: ctx, configPath: configPath, activeManagement: cfg, overrides: overrides, requests: requests, factory: buildRuntimeGeneration, } generation, err := manager.factory(ctx, ctx, cfg, requests) if err != nil { + requests.close() return nil, err } generation.service.SetAPIKeyAccounts(apiKeyAccounts(cfg.ProxyAPIKey, cfg.APIKeyAccounts, cfg)) + manager.settings.Store(requestSettingsOf(cfg)) manager.current = generation manager.wireAccounts(generation) if cfg.AutoStart { @@ -363,29 +368,38 @@ func (manager *runtimeManager) stopAutoStart() { } } -// Close 释放当前生成服务 +// Close 停止生成服务并释放当前生成服务实例 func (manager *runtimeManager) Close() error { + _, stopErr := manager.StopService(context.Background()) manager.mu.RLock() current := manager.current manager.mu.RUnlock() - return current.Close() + return errors.Join(stopErr, current.Close()) } // 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 } // requestSettingsOf 返回 cfg 中只决定新请求行为的设置 func requestSettingsOf(cfg config.Config) *requestSettings { return &requestSettings{ modes: api.ResponseModes{NonstreamKeepalive: cfg.NonstreamKeepalive, FakeStream: cfg.FakeStream}, - searchModelAliases: cfg.SearchModelAliases, googleSearch: cfg.GoogleSearch, - mediaOutput: cfg.MediaOutput, mediaBaseURL: cfg.MediaBaseURL, + searchModelAliases: cfg.SearchModelAliases, + googleSearch: cfg.GoogleSearch, + mediaOutput: cfg.MediaOutput, + mediaBaseURL: cfg.MediaBaseURL, + replyTool: cfg.ReplyTool, + userMessageRewrite: cfg.UserMessageRewrite, + thinkingGuard: cfg.ThinkingGuard, } } @@ -438,6 +452,13 @@ func (manager *runtimeManager) CountTokens(ctx context.Context, request aistudio // Generate 由当前生成服务生成事件流 func (manager *runtimeManager) Generate(ctx context.Context, request aistudio.GenerateRequest) (<-chan aistudio.Event, error) { + if settings := manager.settings.Load(); settings != nil { + request.ReplyTool = request.ReplyTool || settings.replyTool + if request.UserMessageRewrite == "" { + request.UserMessageRewrite = settings.userMessageRewrite + } + request.ThinkingGuard = request.ThinkingGuard || settings.thinkingGuard + } current, done := manager.generation() defer done() return current.service.Generate(ctx, request) @@ -632,6 +653,13 @@ func (manager *runtimeManager) ChromeImportProfiles(ctx context.Context) ([]api. return current.admin.ChromeImportProfiles(ctx) } +// CheckChromeImportTiers 按需检测选中的本机 Chrome 账号的 AI Studio 权益并逐条回调结果 +func (manager *runtimeManager) CheckChromeImportTiers(ctx context.Context, input api.ChromeTierCheckInput, emit func(api.ChromeProfileTier)) error { + current, done := manager.generation() + defer done() + return current.admin.CheckChromeImportTiers(ctx, input, emit) +} + // CookieBrowsers 返回当前生成服务发现的本机调试浏览器,proxy 为识别账户的请求出口 func (manager *runtimeManager) CookieBrowsers(ctx context.Context, proxy string) ([]api.CookieBrowser, error) { current, done := manager.generation() @@ -688,6 +716,14 @@ func (manager *runtimeManager) LoginAccount(ctx context.Context, id string, view return manager.currentAdmin().LoginAccount(ctx, id, view) } +// VerifyAccount 等 Camoufox 就绪后打开账户验证页并自动再核对,期间不阻止生成服务换代 +func (manager *runtimeManager) VerifyAccount(ctx context.Context, id string, view *camoufoxnative.LiveView) (api.AdminAccount, error) { + if err := manager.prepareLoginCamoufox(ctx, id); err != nil { + return api.AdminAccount{}, err + } + return manager.currentAdmin().VerifyAccount(ctx, id, view) +} + // prepareLoginCamoufox 在浏览器登录前等 Camoufox 就绪,需要下载时记录等待,失败时记录原因 func (manager *runtimeManager) prepareLoginCamoufox(ctx context.Context, source string) error { if !camoufoxnative.PreparationState().Ready { @@ -744,8 +780,13 @@ func (manager *runtimeManager) UpdateRuntimeConfig(ctx context.Context, value ap 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, + searchModelAliases: updated.SearchModelAliases, + googleSearch: updated.GoogleSearch, + mediaOutput: updated.MediaOutput, + mediaBaseURL: updated.MediaBaseURL, + replyTool: updated.ReplyTool, + userMessageRewrite: updated.UserMessageRewrite, + thinkingGuard: updated.ThinkingGuard, }) updated = manager.decorateRuntimeConfig(updated, current.config) manager.ledger.SetBodyCapture(updated.RequestBodyLog) @@ -832,6 +873,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat DiscoverHiddenModels: value.DiscoverHiddenModels, FirstEventHedge: value.FirstEventHedge, FirstEventHedgeModels: value.FirstEventHedgeModels, + FirstEventTimeout: value.FirstEventTimeout, ContinuationRewrite: value.ContinuationRewrite, ContinuationPrompt: value.ContinuationPrompt, } @@ -841,7 +883,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat 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.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 } diff --git a/internal/app/pairing_renewal.go b/internal/app/pairing_renewal.go index a777283e..3faff76a 100644 --- a/internal/app/pairing_renewal.go +++ b/internal/app/pairing_renewal.go @@ -51,6 +51,12 @@ func writePairingRenewal(directory string, renewal pairingRenewal) error { return os.WriteFile(filepath.Join(directory, pairingRenewalName), data, 0o600) } +// hasPairingRenewal 表示账户目录保存了远程配对的续签凭据 +func hasPairingRenewal(directory string) bool { + renewal, err := readPairingRenewal(directory) + return err == nil && renewal.TokenSHA256 != "" +} + // pairingRenewedAt 返回账户目录记录的最近一次配对续签时间,没有续签过时为 nil func pairingRenewedAt(directory string) *time.Time { renewal, err := readPairingRenewal(directory) diff --git a/internal/app/proxy_pool.go b/internal/app/proxy_pool.go index 1aa32c6f..903bb3b7 100644 --- a/internal/app/proxy_pool.go +++ b/internal/app/proxy_pool.go @@ -90,18 +90,15 @@ func (admin *runtimeAdmin) probeProxies(ctx context.Context) { } } -// rebindAccounts 在后台按代理池的新绑定重建账户的请求头客户端与 Worker +// rebindAccounts 在后台按代理池的新绑定各自重建受影响账户的请求头客户端与 Worker func (admin *runtimeAdmin) rebindAccounts(accountIDs []string) { - if len(accountIDs) == 0 { - return - } - go func() { - for _, accountID := range accountIDs { + for _, accountID := range accountIDs { + go func() { if err := admin.rebindAccount(admin.lifecycle, accountID); err != nil && admin.lifecycle.Err() == nil { admin.requests.log(accountID, "WARN", "代理改绑失败", "error", err) } - } - }() + }() + } } func (admin *runtimeAdmin) rebindAccount(ctx context.Context, accountID string) error { diff --git a/internal/app/request_registry.go b/internal/app/request_registry.go index 0de12acf..18696f48 100644 --- a/internal/app/request_registry.go +++ b/internal/app/request_registry.go @@ -16,11 +16,13 @@ import ( // requestRegistry 保存活动请求与事件订阅 type requestRegistry struct { - mu sync.Mutex - active map[string]trackedRequest - logs []api.AdminLog - subscribers map[*eventSubscriber]struct{} - console chan api.AdminLog + mu sync.Mutex + active map[string]trackedRequest + logs []api.AdminLog + subscribers map[*eventSubscriber]struct{} + console chan api.AdminLog + consoleClosed bool + consoleDone chan struct{} // firstEvents 是各模型与通道近期原请求的首事件等待,生成服务重启后保留 firstEvents *firstEventStats } @@ -53,16 +55,17 @@ type trackedRequest struct { publishedDataAt time.Time } -// newRequestRegistry 创建活动请求注册表 -func newRequestRegistry(ctx context.Context) *requestRegistry { +// newRequestRegistry 创建活动请求注册表,进程退出前调用 close 排空控制台日志队列 +func newRequestRegistry() *requestRegistry { registry := &requestRegistry{ active: make(map[string]trackedRequest), logs: make([]api.AdminLog, 0, 128), subscribers: make(map[*eventSubscriber]struct{}), console: make(chan api.AdminLog, 256), + consoleDone: make(chan struct{}), firstEvents: newFirstEventStats(), } - go registry.writeConsole(ctx) + go registry.writeConsole() return registry } @@ -225,39 +228,48 @@ func (registry *requestRegistry) recordLog(entry api.AdminLog) { registry.logs = registry.logs[:adminLogRetain] } registry.publishLocked(api.AdminEvent{Type: "log", Data: entry}) - registry.mu.Unlock() - select { - case registry.console <- entry: - default: + if !registry.consoleClosed { + select { + case registry.console <- entry: + default: + } } + registry.mu.Unlock() } -func (registry *requestRegistry) writeConsole(ctx context.Context) { - for { - select { - case entry := <-registry.console: - level := slog.LevelInfo - switch entry.Level { - case "ERROR": - level = slog.LevelError - case "WARN": - level = slog.LevelWarn - } - record := slog.NewRecord(entry.Time, level, entry.Message, 0) - record.AddAttrs(slog.String("event", entry.Event), slog.String("source", entry.Source)) - if entry.Stage != nil { - record.AddAttrs(slog.Any("stage", entry.Stage)) - } - for _, field := range entry.Fields { - record.AddAttrs(slog.String(field.Key, field.Value)) - } - if entry.Request != nil { - record.AddAttrs(slog.Any("request", entry.Request)) - } - _ = slog.Default().Handler().Handle(ctx, record) - case <-ctx.Done(): - return +// close 关闭控制台日志队列并等待已缓冲日志全部写出 +func (registry *requestRegistry) close() { + registry.mu.Lock() + if !registry.consoleClosed { + registry.consoleClosed = true + close(registry.console) + } + registry.mu.Unlock() + <-registry.consoleDone +} + +func (registry *requestRegistry) writeConsole() { + defer close(registry.consoleDone) + for entry := range registry.console { + level := slog.LevelInfo + switch entry.Level { + case "ERROR": + level = slog.LevelError + case "WARN": + level = slog.LevelWarn + } + record := slog.NewRecord(entry.Time, level, entry.Message, 0) + record.AddAttrs(slog.String("event", entry.Event), slog.String("source", entry.Source)) + if entry.Stage != nil { + record.AddAttrs(slog.Any("stage", entry.Stage)) + } + for _, field := range entry.Fields { + record.AddAttrs(slog.String(field.Key, field.Value)) + } + if entry.Request != nil { + record.AddAttrs(slog.Any("request", entry.Request)) } + _ = slog.Default().Handler().Handle(context.Background(), record) } } diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 495caa20..1469f01c 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -112,6 +112,7 @@ func newRuntime( 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.discoverHiddenModels = cfg.DiscoverHiddenModels mapping, _ := config.ParseModelMapping(cfg.ModelMapping) service.SetRequestPolicy(mapping, cfg.MaxAccountSwitches) @@ -179,6 +180,8 @@ type trackedService struct { hedgeAfter time.Duration // hedgeModels 是发起备用请求的模型 hedgeModels []string + // firstEventTimeout 是单次尝试从取得账户起等待首个上游事件的最长时间,零值表示不限制 + firstEventTimeout time.Duration // hedges 是正在进行的备用请求数 hedges atomic.Int32 // maxAccountSwitches 是一个请求因非额度失败换号的次数上限,保存设置后立即替换 @@ -778,14 +781,21 @@ func (service *trackedService) withAliases(models []aistudio.Model) []aistudio.M return models } -// mappedModel 返回 MODEL_MAPPING 中别名映射到的模型名,别名带思考后缀时该后缀替换目标自带的后缀,不是别名时原样返回 +// oneMillionContextSuffix 是 Claude Code 1M 上下文模式加在模型名末尾的标记,按去掉它的模型处理 +const oneMillionContextSuffix = "[1m]" + +// mappedModel 返回 MODEL_MAPPING 中别名映射到的模型名,别名带思考后缀时该后缀替换目标自带的后缀,不是别名时原样返回;完整名称不是别名时去掉末尾的 [1m] 再映射 func (service *trackedService) mappedModel(name string) string { - trimmed := strings.TrimPrefix(strings.TrimSpace(name), "models/") + name = strings.TrimSpace(name) + trimmed := strings.TrimPrefix(name, "models/") for _, alias := range service.aliases() { if alias.Alias == trimmed { return alias.Model } } + if strings.HasSuffix(strings.ToLower(trimmed), oneMillionContextSuffix) { + return service.mappedModel(name[:len(name)-len(oneMillionContextSuffix)]) + } open := strings.LastIndex(trimmed, "(") if open <= 0 || !strings.HasSuffix(trimmed, ")") { return name @@ -1026,6 +1036,25 @@ func (service *trackedService) syncAccountModels(ctx context.Context, accountID return models, err } +// verifyAccount 在服务生命周期中同步账户目录并发一次生成请求核对验证状态,刷新目录快照并发布状态 +func (service *trackedService) verifyAccount(ctx context.Context, accountID string) error { + requestCtx, cancel := service.lifecycleRequestContext(ctx) + defer cancel() + var err error + if verifier, ok := service.catalog.(interface { + VerifyAccount(context.Context, string) error + }); ok { + err = verifier.VerifyAccount(requestCtx, accountID) + } else { + _, err = service.refreshAccountModelCatalog(requestCtx, accountID, true) + } + service.modelSyncMu.Lock() + service.applyCachedModelCatalog() + service.modelSyncMu.Unlock() + service.publishModelAccess() + return err +} + // retryModelCatalogs 每 30 秒重新载入待同步账户的页面重试目录,自 startedAt 起每 24 小时重新载入启用账户的页面读取权益与目录;到期资源在启动时与每 10 分钟删除 func (service *trackedService) retryModelCatalogs(ctx context.Context, startedAt time.Time) { var patrol sync.WaitGroup @@ -1790,7 +1819,7 @@ func (service *trackedService) acquireWarmLease(ctx context.Context, selection a } failedWorkers[accountID] = struct{}{} promoteFailure = promoteErr - if *failures++; int64(*failures) > service.maxAccountSwitches.Load() { + if !service.countSwitchFailure(failures, promoteErr) { return nil, promotionFailure(service.pool, selection, promoteErr) } continue @@ -2094,13 +2123,17 @@ type generateAttempt struct { source <-chan aistudio.Event first aistudio.Event firstAt time.Time - err error - cancel context.CancelFunc - done chan struct{} + err error + cancel context.CancelFunc + stopFirstEvent func() + done chan struct{} // serving 是正在生成回答的账户租约,续写轮换账户后为新账户的租约 serving atomic.Pointer[aistudio.AccountLease] // failures 是请求已用掉的换号次数,续写轮换号在此基础上计数 failures int + // interactionStream 与 interactionTask 是租约账户与通道对该模型的 Interaction 路由 + interactionStream bool + interactionTask bool } // generateRetry 是生成请求跨尝试的换号与恢复状态 @@ -2170,7 +2203,7 @@ func (service *trackedService) generateWithRetry( } else { preferredAccountID = service.pool.InlineMediaAccount(request.Contents) } - hedgeable := !request.Background && !assistant && !service.pool.InteractionAgentModel(modelID) && (service.hedgeAuto || service.hedgeAfter > 0) && slices.Contains(service.hedgeModels, modelID) + hedgeable := !request.Background && !assistant && (service.hedgeAuto || service.hedgeAfter > 0) && slices.Contains(service.hedgeModels, modelID) hedged := false var winner *generateAttempt var activity *upstreamActivity @@ -2261,6 +2294,7 @@ func (service *trackedService) generateWithRetry( var ownerCooling *aistudio.AllCoolingError if fileBound && !copyFiles && (errors.Is(acquireErr, aistudio.ErrNoEligibleAccount) || errors.As(acquireErr, &ownerCooling)) && requestCtx.Err() == nil { copyFiles = true + retry.maxAttempts++ continue } var cooling *aistudio.AllCoolingError @@ -2298,7 +2332,7 @@ func (service *trackedService) generateWithRetry( service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "等待上游响应") primary := service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, lease, selection, false, retry.failures) var plan *hedgePlan - if hedgeable && !hedged { + if hedgeable && !primary.interactionTask && !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)} @@ -2452,14 +2486,34 @@ func (service *trackedService) startAttempt( ) *generateAttempt { unbound := strings.TrimSpace(request.AccountID) == "" && resourceID == "" request.AccountID = lease.Account().ID + interactionStream, interactionTask := 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, } attempt.serving.Store(lease) - attemptCtx, cancel := context.WithCancel(requestCtx) - attempt.cancel = cancel + attemptCtx, cancel := context.WithCancelCause(requestCtx) + attempt.cancel = func() { cancel(context.Canceled) } + if service.firstEventTimeout > 0 && !request.Background && !attempt.interactionTask { + timeout := service.firstEventTimeout + var mu sync.Mutex + stopped := false + timer := time.AfterFunc(timeout, func() { + mu.Lock() + defer mu.Unlock() + if !stopped { + cancel(&firstEventTimeoutError{timeout: timeout}) + } + }) + attempt.stopFirstEvent = func() { + mu.Lock() + stopped = true + timer.Stop() + mu.Unlock() + } + } go func() { defer close(attempt.done) service.runAttempt(attemptCtx, request, resourceID, modelID, fallbackReason, attempt) @@ -2476,17 +2530,13 @@ func (service *trackedService) runAttempt( fallbackReason string, attempt *generateAttempt, ) { + if attempt.stopFirstEvent != nil { + defer attempt.stopFirstEvent() + } lease, accountLabel := attempt.lease, attempt.accountLabel - inlineImages := false - for _, model := range service.modelSnapshot() { - if model.ID != modelID { - continue - } - if model.Capabilities["interaction_task"] { - // agent 后台任务只发送 AgentInput 选出的内容,其余轮次的文件不复制、附件不上传 - request.Contents = aistudio.AgentInput(request.Contents, request.PreviousInteractionID != "") - } - inlineImages = model.Capabilities["interaction_stream"] + if attempt.interactionTask { + // agent 后台任务只发送 AgentInput 选出的内容,其余轮次的文件不复制、附件不上传 + request.Contents = aistudio.AgentInput(request.Contents, request.PreviousInteractionID != "") } originalContents := request.Contents ctx = aistudio.ContextWithAccountLease(ctx, lease) @@ -2512,7 +2562,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, inlineImages) + }).UploadInlineMediaToLease(ctx, lease, request.Contents, attempt.copies, attempt.interactionStream) if err == nil { service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "内联附件处理完成", "attachments", mediaCount, "bytes", fmt.Sprintf("%d B", mediaBytes), "duration", time.Since(uploadStartedAt)) @@ -2525,6 +2575,12 @@ func (service *trackedService) runAttempt( service.requests.logRequestProgress(request.ID, accountLabel, "WARN", "请求准备等待", "waited", waited, "current_step", current, "model", modelID) }) ctx = aistudio.ContextWithStreamActivityObserver(ctx, attempt.activity.observe) + ctx = aistudio.ContextWithRegenerationObserver(ctx, func(regenerated int, reason string) { + service.requests.logRequestProgress(request.ID, accountLabel, "WARN", "重新生成", "attempt", regenerated, "model", modelID, "reason", reason) + }) + ctx = aistudio.ContextWithReplyToolBypassObserver(ctx, func() { + service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "模型没有使用回复工具", "model", modelID) + }) ctx = aistudio.ContextWithRequestPhaseObserver(ctx, prepareTiming.observe) if err == nil { attempt.source, err = service.service.Generate(ctx, request) @@ -2556,6 +2612,21 @@ func (service *trackedService) runAttempt( "waited", time.Since(upstreamStartedAt), "first_event", attempt.first.Kind, "model", modelID) } } + if attempt.stopFirstEvent != nil { + attempt.stopFirstEvent() + } + var timedOut *firstEventTimeoutError + if errors.As(context.Cause(ctx), &timedOut) { + var rpcErr *aistudio.RPCError + if err == nil || !errors.As(err, &rpcErr) { + if err == nil && attempt.source != nil { + for range attempt.source { + } + attempt.source = nil + } + err = timedOut + } + } attempt.err = err } @@ -2603,10 +2674,8 @@ func (service *trackedService) continuationAccount(ctx context.Context, requestI if releaseErr := current.Release(); releaseErr != nil { return nil, releaseErr } - if !quota && !errors.Is(err, aistudio.ErrAccountCoolingDown) { - if attempt.failures++; int64(attempt.failures) > service.maxAccountSwitches.Load() { - return nil, aistudio.ErrNoEligibleAccount - } + if !service.countSwitchFailure(&attempt.failures, err) { + return nil, aistudio.ErrNoEligibleAccount } selection := aistudio.AccountSelection{ModelID: modelID, Method: "generateContent", PlaygroundOnly: true, AllowedAccountIDs: []string{}} for _, accountID := range service.pool.EnabledAccounts() { @@ -2861,8 +2930,9 @@ func (service *trackedService) settleAttempt( } service.workers.spareForCooling(requestCtx, attempt.selection, accountID, cooledUntil) recoverWorker := false - // 上游以额度、权限拒绝或服务受限拒绝账户时不重建 Worker 重放,直接换号 - if requestCtx.Err() == nil && mayRecover && !quotaFailure && !rejected && denial == nil { + var firstEventTimedOut *firstEventTimeoutError + // 上游以额度、权限拒绝、服务受限或首字超时结束尝试时不重建 Worker 重放,直接换号 + if requestCtx.Err() == nil && mayRecover && !quotaFailure && !rejected && denial == nil && !errors.As(err, &firstEventTimedOut) { var resetErr error recoverWorker, _, resetErr = service.recoverWorkerOnce( requestCtx, accountID, workerGeneration, retry.recoveredWorker, @@ -2874,13 +2944,24 @@ func (service *trackedService) settleAttempt( retryable = false } } - if retryable && !quotaFailure && !buildRejected && !missingInlineMedia && !recoverWorker && !coolingDown { - retry.failures++ - retryable = int64(retry.failures) <= service.maxAccountSwitches.Load() + if retryable && !buildRejected && !missingInlineMedia && !recoverWorker { + retryable = service.countSwitchFailure(&retry.failures, err) } 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 { + if aistudio.DefinitiveAuthenticationFailure(err) || errors.Is(err, aistudio.ErrAccountCoolingDown) { + return true + } + if _, quota := aistudio.QuotaCooldownForError(err, time.Now()); quota { + return true + } + *failures++ + return int64(*failures) <= service.maxAccountSwitches.Load() +} + // rejectedBuildAttempt 表示 Build 以参数错误拒绝、改由 Playground 重试的尝试 type rejectedBuildAttempt struct { accountID string @@ -2986,6 +3067,10 @@ func retryableGenerateAccountError(ctx context.Context, err error) bool { if errors.As(err, &interrupted) { return ctx.Err() == nil } + var readError *aistudio.ResponseReadError + if errors.As(err, &readError) { + return ctx.Err() == nil + } var workerInitError *accountWorkerInitError if errors.As(err, &workerInitError) { return ctx.Err() == nil @@ -3014,92 +3099,147 @@ func (service *trackedService) lifecycleRequestContext(ctx context.Context) (con } } -// dataRequestContext 返回绑定数据面生命周期、期限为 REQUEST_TIMEOUT 的请求上下文,自动续写每开始一轮期限重新计时 +// dataRequestContext 返回绑定数据面生命周期的请求上下文,上游连续 REQUEST_TIMEOUT 没有数据时到期 func (service *trackedService) dataRequestContext(ctx context.Context) (context.Context, context.CancelFunc, error) { service.lifecycleMu.Lock() if service.state.Load() != serviceRunning || service.dataContext == nil { service.lifecycleMu.Unlock() return nil, nil, service.stoppedError() } - deadline, cancel := newRoundDeadlineContext(ctx, service.timeout) + deadline, cancel := newIdleDeadlineContext(ctx, service.timeout) run := service.dataContext stopData := context.AfterFunc(run, cancel) service.lifecycleMu.Unlock() - return aistudio.ContextWithServiceRun(aistudio.ContextWithContinuationObserver(deadline, deadline.extend), run), func() { + return aistudio.ContextWithServiceRun(aistudio.ContextWithStreamActivityObserver(deadline, deadline.observe), run), func() { stopData() cancel() }, nil } -// endedRequestError 在请求所属的生成服务已停止时把非空的 err 换成生成服务已停止的错误,其余原样返回 err +// endedRequestError 在请求所属的生成服务已停止或上游连续没有数据超过 REQUEST_TIMEOUT 时把非空的 err 换成说明原因的错误,其余原样返回 err func endedRequestError(ctx context.Context, err error) error { - if err != nil && aistudio.ServiceStopped(ctx) { + if err == nil { + return nil + } + if aistudio.ServiceStopped(ctx) { return &serviceStoppedError{} } + if deadline, ok := ctx.Value(idleDeadlineKey{}).(*idleDeadlineContext); ok { + deadline.mu.Lock() + cause := deadline.cause + deadline.mu.Unlock() + if cause != nil { + return cause + } + } return err } -// roundDeadlineContext 是期限可在自动续写每轮开始时重新计时的请求上下文,到期时 Err 为 context.DeadlineExceeded -type roundDeadlineContext struct { - parent context.Context - timeout time.Duration - done chan struct{} - mu sync.Mutex - timer *time.Timer - stop func() bool - deadline time.Time - err error +// idleDeadlineContext 是上游连续 timeout 没有数据时到期的请求上下文,请求开始到首个字节同样计入,到期时 Err 为 context.DeadlineExceeded +// 约束:active 为最近一次收到上游数据距 started 的纳秒数,由读取上游响应的 goroutine 并发写入 +type idleDeadlineContext struct { + parent context.Context + timeout time.Duration + started time.Time + active atomic.Int64 + done chan struct{} + mu sync.Mutex + timer *time.Timer + stop func() bool + err error + // cause 是上游连续没有数据超过 REQUEST_TIMEOUT 时说明原因的错误,其余结束方式为 nil + cause error +} + +type idleDeadlineKey struct{} + +// upstreamIdleError 是上游连续 REQUEST_TIMEOUT 没有数据时请求的结束原因 +type upstreamIdleError struct { + timeout time.Duration +} + +func (e *upstreamIdleError) Error() string { + return fmt.Sprintf("上游连续 %s 没有数据,超过 REQUEST_TIMEOUT", e.timeout) +} + +func (e *upstreamIdleError) Is(target error) bool { + return target == context.DeadlineExceeded +} + +// firstEventTimeoutError 是单次尝试在 FIRST_EVENT_TIMEOUT 内没有收到首个上游事件的失败原因 +type firstEventTimeoutError struct { + timeout time.Duration +} + +func (e *firstEventTimeoutError) Error() string { + return fmt.Sprintf("上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT", e.timeout) +} + +func (e *firstEventTimeoutError) Is(target error) bool { + return target == context.DeadlineExceeded } -// newRoundDeadlineContext 返回期限为 timeout、随 parent 结束的请求上下文 -func newRoundDeadlineContext(parent context.Context, timeout time.Duration) (*roundDeadlineContext, context.CancelFunc) { - ctx := &roundDeadlineContext{parent: parent, timeout: timeout, done: make(chan struct{}), deadline: time.Now().Add(timeout)} +// newIdleDeadlineContext 返回上游连续 timeout 没有数据时到期、随 parent 结束的请求上下文 +func newIdleDeadlineContext(parent context.Context, timeout time.Duration) (*idleDeadlineContext, context.CancelFunc) { + ctx := &idleDeadlineContext{parent: parent, timeout: timeout, started: time.Now(), done: make(chan struct{})} ctx.mu.Lock() - ctx.timer = time.AfterFunc(timeout, func() { ctx.finish(context.DeadlineExceeded) }) - ctx.stop = context.AfterFunc(parent, func() { ctx.finish(parent.Err()) }) + ctx.timer = time.AfterFunc(timeout, ctx.expire) + ctx.stop = context.AfterFunc(parent, func() { ctx.finish(parent.Err(), nil) }) ctx.mu.Unlock() - return ctx, func() { ctx.finish(context.Canceled) } + return ctx, func() { ctx.finish(context.Canceled, nil) } } -func (ctx *roundDeadlineContext) finish(err error) { - ctx.mu.Lock() - defer ctx.mu.Unlock() - if ctx.err != nil { - return - } - ctx.err = err - ctx.timer.Stop() - ctx.stop() - close(ctx.done) +// observe 记录收到上游数据的时刻 +func (ctx *idleDeadlineContext) observe(int) { + ctx.active.Store(int64(time.Since(ctx.started))) } -// extend 把期限重新计为 timeout -func (ctx *roundDeadlineContext) extend() { +// expire 在计时到达时结束请求,计时期间收到过上游数据时改为从最近一次数据起再计 timeout +func (ctx *idleDeadlineContext) expire() { + remaining := time.Duration(ctx.active.Load()) + ctx.timeout - time.Since(ctx.started) + if remaining <= 0 { + ctx.finish(context.DeadlineExceeded, &upstreamIdleError{timeout: ctx.timeout}) + return + } ctx.mu.Lock() defer ctx.mu.Unlock() if ctx.err == nil { - ctx.deadline = time.Now().Add(ctx.timeout) - ctx.timer.Reset(ctx.timeout) + ctx.timer.Reset(remaining) } } -func (ctx *roundDeadlineContext) Deadline() (time.Time, bool) { +// finish 以 err 结束请求上下文,cause 为说明原因的错误 +func (ctx *idleDeadlineContext) finish(err error, cause error) { ctx.mu.Lock() defer ctx.mu.Unlock() - return ctx.deadline, true + if ctx.err != nil { + return + } + ctx.err, ctx.cause = err, cause + ctx.timer.Stop() + ctx.stop() + close(ctx.done) +} + +// Deadline 返回最近一次收到上游数据之后 timeout 的时刻 +func (ctx *idleDeadlineContext) Deadline() (time.Time, bool) { + return ctx.started.Add(time.Duration(ctx.active.Load()) + ctx.timeout), true } -func (ctx *roundDeadlineContext) Done() <-chan struct{} { +func (ctx *idleDeadlineContext) Done() <-chan struct{} { return ctx.done } -func (ctx *roundDeadlineContext) Err() error { +func (ctx *idleDeadlineContext) Err() error { ctx.mu.Lock() defer ctx.mu.Unlock() return ctx.err } -func (ctx *roundDeadlineContext) Value(key any) any { +func (ctx *idleDeadlineContext) Value(key any) any { + if key == (idleDeadlineKey{}) { + return ctx + } return ctx.parent.Value(key) } diff --git a/internal/app/waa_backend.go b/internal/app/waa_backend.go index f331c1ef..dfd329e6 100644 --- a/internal/app/waa_backend.go +++ b/internal/app/waa_backend.go @@ -69,3 +69,16 @@ func (driver camoufoxLoginDriver) Login(ctx context.Context, request aistudio.Is } return login.Login(ctx, request) } + +// Verify 等 Camoufox 就绪后打开账户验证页并自动再核对 +func (driver camoufoxLoginDriver) Verify(ctx context.Context, request aistudio.AccountVerifyRequest) (bool, error) { + path, err := camoufoxnative.Prepare(ctx, driver.proxy) + if err != nil { + return true, err + } + login, err := aistudio.NewNativeLoginDriver(path) + if err != nil { + return true, err + } + return login.Verify(ctx, request) +} diff --git a/internal/app/worker_manager.go b/internal/app/worker_manager.go index a1aac9e3..7fd3fb97 100644 --- a/internal/app/worker_manager.go +++ b/internal/app/worker_manager.go @@ -891,7 +891,13 @@ func (manager *accountWorkerManager) PageCatalog(ctx context.Context, accountID return worker.PageCatalog(), nil } generation := authGeneration(ctx) - err := manager.reloadWorker(ctx, accountID, worker) + var err error + if manager.refresher != nil { + err = manager.refresher.ensureBoundAccount(ctx, accountID) + } + if err == nil { + err = manager.reloadWorker(ctx, accountID, worker) + } if err == nil { return worker.PageCatalog(), nil } @@ -1178,6 +1184,11 @@ func (manager *accountWorkerManager) startReservedWorker( options.StartupProgress = func(stage camoufoxnative.StartupStage) { logStep(workerStartupProgress(stage)) } + if manager.refresher != nil { + options.RefreshCookies = func(refreshCtx context.Context) error { + return manager.refresher.ensureBoundAccount(refreshCtx, account.id) + } + } worker, initErr := newWAAWorker(initCtx, account.id, options) if initErr == nil { if initErr = manager.rememberPageHeaders(account.id, worker); initErr != nil { diff --git a/internal/camoufoxnative/fingerprint.go b/internal/camoufoxnative/fingerprint.go index cadaae2f..95b71d69 100644 --- a/internal/camoufoxnative/fingerprint.go +++ b/internal/camoufoxnative/fingerprint.go @@ -13,6 +13,7 @@ import ( "regexp" "slices" "strings" + "sync" "github.com/brainplusplus/go-browserforge/fingerprints" bfheaders "github.com/brainplusplus/go-browserforge/headers" @@ -33,8 +34,13 @@ type savedFingerprint struct { Rhythm *rhythm.Rhythm `json:"rhythm,omitempty"` } +// fingerprintMu 串行化账户指纹文件的读写 +var fingerprintMu sync.Mutex + // PersistAccountFingerprint 将隔离登录指纹保存到账户目录 func PersistAccountFingerprint(sourceDirectory string, targetDirectory string) error { + fingerprintMu.Lock() + defer fingerprintMu.Unlock() source := filepath.Join(sourceDirectory, "camoufox-fingerprint.json") data, err := os.ReadFile(source) if errors.Is(err, os.ErrNotExist) { @@ -118,6 +124,8 @@ func loadAccountCamoufoxConfig(storageStatePath string, ffVersion int, locale st timezone = "UTC" } path := filepath.Join(filepath.Dir(storageStatePath), "camoufox-fingerprint.json") + fingerprintMu.Lock() + defer fingerprintMu.Unlock() data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { config, buildErr := buildCamoufoxConfig(ffVersion, locale, timezone) @@ -214,12 +222,30 @@ func applyLocaleTimezone(config map[string]any, locale string, timezone string) config["voices"] = windowsVoices(locale) } +// writeAccountCamoufoxConfig 先写入同目录临时文件并刷盘,再以 os.Rename 替换账户指纹文件 func writeAccountCamoufoxConfig(path string, saved savedFingerprint) error { encoded, err := json.Marshal(saved) if err != nil { return fmt.Errorf("编码账户 Camoufox 指纹: %w", err) } - if err := os.WriteFile(path, encoded, 0o600); err != nil { + temporary, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+"-*.tmp") + if err != nil { + return fmt.Errorf("创建账户 Camoufox 指纹临时文件: %w", err) + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if _, err := temporary.Write(encoded); err != nil { + _ = temporary.Close() + return fmt.Errorf("写入账户 Camoufox 指纹: %w", err) + } + if err := temporary.Sync(); err != nil { + _ = temporary.Close() + return fmt.Errorf("同步账户 Camoufox 指纹: %w", err) + } + if err := temporary.Close(); err != nil { + return fmt.Errorf("关闭账户 Camoufox 指纹临时文件: %w", err) + } + if err := os.Rename(temporaryPath, path); err != nil { return fmt.Errorf("写入账户 Camoufox 指纹: %w", err) } return nil diff --git a/internal/camoufoxnative/function.go b/internal/camoufoxnative/function.go index f6e3101f..f377233f 100644 --- a/internal/camoufoxnative/function.go +++ b/internal/camoufoxnative/function.go @@ -17,6 +17,9 @@ const ( // FunctionCallMarker 是 GenerateContent 响应流中函数调用 Part 的开头:十个空字段后为带函数名的 functionCall var FunctionCallMarker = []byte(`[null,null,null,null,null,null,null,null,null,null,["`) +// ErrFunctionTabUnavailable 表示没有最后一轮是本请求回应的函数调用的空闲标签页 +var ErrFunctionTabUnavailable = errors.New("没有最后一轮是本请求回应的函数调用的标签页") + // functionTab 返回最后一轮是 contents 所回应的函数调用、输入框中没有未发出输入的空闲标签页,即 contents 在其上一轮的对话后追加了 model 与 user 两轮,没有时为 nil;调用方持有 mu func (worker *Worker) functionTab(contents []json.RawMessage) *chatTab { for _, tab := range worker.chats { @@ -44,7 +47,7 @@ func (worker *Worker) acquireFunctionChat(contents []json.RawMessage) (*chatTab, defer worker.mu.Unlock() tab := worker.functionTab(contents) if tab == nil { - return nil, errors.New("没有最后一轮是本请求回应的函数调用的标签页") + return nil, ErrFunctionTabUnavailable } tab.busy = true worker.useTab(tab.contextID) diff --git a/internal/camoufoxnative/generate.go b/internal/camoufoxnative/generate.go index 21455c90..6b3fea0d 100644 --- a/internal/camoufoxnative/generate.go +++ b/internal/camoufoxnative/generate.go @@ -86,7 +86,7 @@ type chatTab struct { page pageHandle // busy 表示标签页正在运行一轮对话 busy bool - // contents 是标签页上一轮发出的 GenerateContent 的 contents,页面没有对话或上一轮以上游错误结束时为空 + // contents 是标签页上一轮成功完成的 GenerateContent 的 contents,页面没有对话或上一轮未成功完成时为空 contents []json.RawMessage // resetting 表示一轮对话结束后正在后台新开对话,或页面正在原标签页重新载入 resetting bool @@ -223,11 +223,6 @@ 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},再依次发出响应头、正文块与结束标记 @@ -399,7 +394,7 @@ func (worker *Worker) generate(ctx context.Context, tab *chatTab, unboost func() turn.report(StepSent) sent.observe(ctx, locked) worker.mu.Lock() - tab.contents = contents + tab.contents = nil tab.unsent = false worker.mu.Unlock() status, header, err := readResponseHead(ctx, channel) @@ -407,11 +402,6 @@ func (worker *Worker) generate(ctx context.Context, tab *chatTab, unboost func() client.closeChannel(requestID) return nil, errors.Join(err, worker.stopTurn(tab)) } - if status != http.StatusOK { - worker.mu.Lock() - tab.contents = nil - worker.mu.Unlock() - } bodyCtx, cancelBody := context.WithCancel(ctx) return &ProtectedResponse{ StatusCode: status, @@ -419,7 +409,16 @@ func (worker *Worker) generate(ctx context.Context, tab *chatTab, unboost func() Proof: sent.Proof, Body: &protectedResponseBody{ ctx: bodyCtx, cancel: cancelBody, worker: worker, contextID: tab.contextID, page: tab.page, requestID: requestID, channel: channel, - stop: func() error { return worker.stopTurn(tab) }, release: func(done, call bool) { worker.releaseChat(tab, done && status == http.StatusOK && !call) }, + stop: func() error { return worker.stopTurn(tab) }, + release: func(completed, call bool) { + ok := completed && status == http.StatusOK + if ok { + worker.mu.Lock() + tab.contents = contents + worker.mu.Unlock() + } + worker.releaseChat(tab, ok && !call) + }, }, }, nil } @@ -759,14 +758,26 @@ func (worker *Worker) acquireChat(ctx context.Context) (*chatTab, error) { return nil, errors.New("Camoufox runtime 已关闭") } resetting := false + var fallback *chatTab for _, tab := range worker.chats { if !tab.busy { - tab.busy = true - worker.useTab(tab.contextID) - return tab, nil + if tab.contents == nil && !tab.unsent { + tab.busy = true + worker.useTab(tab.contextID) + return tab, nil + } + if fallback == nil { + fallback = tab + } + continue } resetting = resetting || tab.resetting } + if fallback != nil { + fallback.busy = true + worker.useTab(fallback.contextID) + return fallback, nil + } if !resetting && !worker.chatOpening { if waited && worker.chatOpenErr != nil { return nil, worker.chatOpenErr @@ -797,20 +808,35 @@ func (worker *Worker) notifyChats() { } } -// openChat 在后台新建标签页并载入官网页面,结束后把它作为空闲标签页加入或记下失败原因,并唤醒等待标签页的请求;调用方持有 mu +// openChat 在后台新建标签页并载入官网页面,结束后把它作为空闲标签页加入或记下失败原因,并唤醒等待标签页的请求;期间发生重新载入时关闭该旧标签页;调用方持有 mu func (worker *Worker) openChat() { worker.chatOpening, worker.chatOpenErr = true, nil + generation := worker.reloads options := worker.options options.StartupProgress = nil go func() { tab, err := worker.loadChat(context.Background(), options) worker.mu.Lock() - defer worker.mu.Unlock() - worker.chatOpening, worker.chatOpenErr = false, err - if err == nil && !worker.closed { + closed := worker.closed + stale := worker.reloads != generation + if stale { + worker.chatOpenErr = nil + } else { + worker.chatOpenErr = err + } + worker.chatOpening = false + if err == nil && !closed && !stale { worker.chats = append(worker.chats, tab) + } else if err == nil && worker.selected == tab.contextID { + worker.selected = "" } worker.notifyChats() + worker.mu.Unlock() + if err == nil && !closed && stale { + if closeErr := worker.closeTab(tab.contextID); closeErr != nil { + slog.Warn("关闭重新载入前新开的 Camoufox 标签页失败", "context", tab.contextID, "error", closeErr) + } + } }() } @@ -843,10 +869,11 @@ func (worker *Worker) loadChat(ctx context.Context, options Options) (*chatTab, return &chatTab{contextID: contextID, page: loaded.page}, nil } -// releaseChat 结束标签页上的一轮对话;completed 表示本轮成功完成,此时在后台新开对话,下一轮在空白对话中直接输入 +// releaseChat 结束标签页上的一轮对话;completed 表示本轮成功完成,标签页未退役时在后台新开对话,下一轮在空白对话中直接输入 func (worker *Worker) releaseChat(tab *chatTab, completed bool) { worker.mu.Lock() - reset := completed && !worker.closed + retired := worker.tabs[tab.contextID] != nil && worker.tabs[tab.contextID].retired + reset := completed && !worker.closed && !retired if reset { tab.resetting = true } else { @@ -886,6 +913,12 @@ func (worker *Worker) clearChat(ctx context.Context, tab *chatTab) error { defer unboost() worker.lockInputIdle() defer worker.inputMu.Unlock() + worker.mu.Lock() + retired := worker.closed || (worker.tabs[tab.contextID] != nil && worker.tabs[tab.contextID].retired) + worker.mu.Unlock() + if retired { + return nil + } if err := worker.selectChat(ctx, tab); err != nil { return err } diff --git a/internal/camoufoxnative/liveview.go b/internal/camoufoxnative/liveview.go index 1ba0eacc..886b7b00 100644 --- a/internal/camoufoxnative/liveview.go +++ b/internal/camoufoxnative/liveview.go @@ -48,6 +48,10 @@ const ( liveViewWaiting = "waiting" // liveViewSaving 表示登录完成,正在授权 Drive 并保存认证状态 liveViewSaving = "saving" + // liveViewChecking 表示账户已保存,正在发一次生成请求核对账户状态 + liveViewChecking = "checking" + // liveViewVerifying 表示官网要求验证,窗口停在验证页等待完成验证 + liveViewVerifying = "verifying" ) // errLiveViewReplaced 表示同一 LiveView 连接了新的登录窗口 diff --git a/internal/camoufoxnative/login.go b/internal/camoufoxnative/login.go index d9ccc0ff..113e075d 100644 --- a/internal/camoufoxnative/login.go +++ b/internal/camoufoxnative/login.go @@ -36,18 +36,50 @@ type LoginOptions struct { Timeout time.Duration Log io.Writer View *LiveView + // OnLoggedIn 在导出认证状态后、关闭浏览器之前保存账户,为空时直接关闭浏览器并返回 + OnLoggedIn func(context.Context, LoginResult) error + // CheckVerification 核对已保存账户是否需要验证,传入最新导出的 storage state JSON + CheckVerification func(context.Context, []byte) (bool, error) + // OnVerifyStep 报告核对与验证页步骤(verifying 或 verify) + OnVerifyStep func(string) + // VerifyPollInterval 是停在验证页时定时自动再核对的间隔,不大于 0 时默认 10 秒 + VerifyPollInterval time.Duration } // LoginResult 返回隔离浏览器导出的 Playwright storage state type LoginResult struct { - StorageStateJSON []byte - Email string - PageURL string - VerifiedAt time.Time - DriveError string - CloseError string + StorageStateJSON []byte + Email string + PageURL string + VerifiedAt time.Time + DriveError string + CloseError string + Saved bool + VerificationPending bool + VerificationError string } +// VerifyOptions 定义在隔离 Camoufox 中打开已有账户验证页的环境与核对回调 +type VerifyOptions struct { + ExecutablePath string + Directory string + StorageStateJSON []byte + AuthUser int + Locale string + Timezone string + Proxy string + ProxyBypass string + Timeout time.Duration + Log io.Writer + View *LiveView + CheckVerification func(context.Context, []byte) (bool, error) + OnVerifyStep func(string) + PollInterval time.Duration +} + +// defaultVerifyPollInterval 是验证页自动再核对的默认间隔 +const defaultVerifyPollInterval = 10 * time.Second + type loginSession struct { process *browserProcess connection *websocket.Conn @@ -65,7 +97,7 @@ func HasDisplay() bool { return runtime.GOOS != "linux" || os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != "" } -// Login 启动隔离 Camoufox 供用户登录 Google,并在 AI Studio 可用后导出认证状态;登录期间浏览器退出时返回 loginBrowserExit 的错误 +// Login 启动隔离 Camoufox 供用户登录 Google,并在 AI Studio 可用后导出认证状态;配置 OnLoggedIn 时先保存账户再核对,官网要求验证时窗口停在验证页并自动再核对 func Login(ctx context.Context, options LoginOptions) (result LoginResult, err error) { if options.View == nil && !HasDisplay() { return LoginResult{}, ErrNoDisplay @@ -73,7 +105,7 @@ func Login(ctx context.Context, options LoginOptions) (result LoginResult, err e options.View.setStatus(liveViewStarting) loginCtx, cancel := context.WithTimeout(ctx, options.Timeout) defer cancel() - session, err := startLoginSession(loginCtx, options, storageState{}) + session, err := startLoginSession(loginCtx, options, storageState{}, aiStudioOrigin+"/prompts/new_chat") if err != nil { if exited := loginBrowserExit(err); exited != nil { return LoginResult{}, exited @@ -82,6 +114,12 @@ func Login(ctx context.Context, options LoginOptions) (result LoginResult, err e } defer func() { closeErr := session.Close() + if result.Saved { + if err == nil && closeErr != nil { + result.CloseError = closeErr.Error() + } + return + } if exited := loginBrowserExit(err); exited != nil { err = errors.Join(exited, closeErr) return @@ -119,13 +157,214 @@ func Login(ctx context.Context, options LoginOptions) (result LoginResult, err e if err != nil { return LoginResult{}, fmt.Errorf("编码 storage state: %w", err) } - return LoginResult{ + result = LoginResult{ StorageStateJSON: encoded, Email: email, PageURL: pageURL, VerifiedAt: time.Now().UTC(), DriveError: errorText(driveErr), - }, nil + } + if options.OnLoggedIn == nil { + return result, nil + } + if err := options.OnLoggedIn(loginCtx, result); err != nil { + return LoginResult{}, err + } + result.Saved = true + if options.CheckVerification == nil { + return result, nil + } + options.View.setStatus(liveViewChecking) + reportVerifyStep(options.OnVerifyStep, "verifying") + needVerify, checkErr := options.CheckVerification(loginCtx, result.StorageStateJSON) + if checkErr != nil { + result.VerificationPending = needVerify + result.VerificationError = checkErr.Error() + return result, nil + } + if !needVerify { + return result, nil + } + wait := "interactive" + if options.View != nil { + wait = "none" + } + if _, navErr := session.client.command(loginCtx, "browsingContext.navigate", map[string]any{ + "context": session.contextID, + "url": AccountVerificationURL, + "wait": wait, + }); navErr != nil && !commandErrorContains(navErr, "NS_ERROR_ABORT") { + result.VerificationPending = true + if loginBrowserExit(navErr) == nil && loginCtx.Err() == nil { + result.VerificationError = navErr.Error() + } + return result, nil + } + pending, latest, verifyErr := session.waitVerification(loginCtx, options.View, origins, options.CheckVerification, options.OnVerifyStep, options.VerifyPollInterval) + if len(latest) > 0 { + result.StorageStateJSON = latest + } + result.VerificationPending = pending + result.VerificationError = errorText(verifyErr) + return result, nil +} + +// Verify 启动隔离 Camoufox 载入已有账户认证状态并停在官网验证页,扫码后自动再核对,返回结束时账户是否仍需要验证 +func Verify(ctx context.Context, options VerifyOptions) (bool, error) { + if options.View == nil && !HasDisplay() { + return true, ErrNoDisplay + } + var state storageState + if err := json.Unmarshal(options.StorageStateJSON, &state); err != nil { + return true, fmt.Errorf("解析账户 storage state: %w", err) + } + if len(state.Cookies) == 0 { + return true, errors.New("账户没有可用于验证的 Cookie") + } + timeout := options.Timeout + if timeout <= 0 { + timeout = 30 * time.Minute + } + options.View.setStatus(liveViewStarting) + verifyCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + loginOptions := LoginOptions{ + ExecutablePath: options.ExecutablePath, + Directory: options.Directory, + Locale: options.Locale, + Timezone: options.Timezone, + Proxy: options.Proxy, + ProxyBypass: options.ProxyBypass, + Timeout: timeout, + Log: options.Log, + View: options.View, + } + session, err := startLoginSession(verifyCtx, loginOptions, state, verificationURLForAuthUser(options.AuthUser)) + if err != nil { + if loginBrowserExit(err) != nil || verifyCtx.Err() != nil { + return true, nil + } + return true, err + } + defer func() { _ = session.Close() }() + origins := make(map[string]storageOrigin, len(state.Origins)) + for _, origin := range state.Origins { + if origin.Origin != "" { + origins[origin.Origin] = origin + } + } + pending, _, verifyErr := session.waitVerification(verifyCtx, options.View, origins, options.CheckVerification, options.OnVerifyStep, options.PollInterval) + if verifyErr != nil && (loginBrowserExit(verifyErr) != nil || verifyCtx.Err() != nil) { + return true, nil + } + return pending, verifyErr +} + +// reportVerifyStep 回调验证阶段步骤,report 为空时不做任何事 +func reportVerifyStep(report func(string), step string) { + if report != nil { + report(step) + } +} + +// verificationURLForAuthUser 返回第 authUser 个会话的 AI Studio 验证页地址 +func verificationURLForAuthUser(authUser int) string { + if authUser > 0 { + return fmt.Sprintf("%s/u/%d/verify-account", aiStudioOrigin, authUser) + } + return AccountVerificationURL +} + +// isVerificationPageURL 判断页面地址是否为 AI Studio 验证页 +func isVerificationPageURL(raw string) bool { + parsed, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || parsed.Hostname() != "aistudio.google.com" { + return false + } + cleanPath := strings.TrimSuffix(parsed.Path, "/") + return cleanPath == "/verify-account" || strings.HasSuffix(cleanPath, "/verify-account") +} + +// isAIStudioAppURL 判断页面地址是否位于非验证页的 AI Studio 页面 +func isAIStudioAppURL(raw string) bool { + parsed, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || parsed.Hostname() != "aistudio.google.com" { + return false + } + return !isVerificationPageURL(raw) +} + +// waitVerification 保持窗口在验证页并监听页面跳转与定时自动再核对,验证通过返回 pending=false,用户关闭窗口或取消任务返回 pending=true 且不报错 +func (session *loginSession) waitVerification( + ctx context.Context, + view *LiveView, + origins map[string]storageOrigin, + check func(context.Context, []byte) (bool, error), + onStep func(string), + pollInterval time.Duration, +) (bool, []byte, error) { + if pollInterval <= 0 { + pollInterval = defaultVerifyPollInterval + } + view.setStatus(liveViewVerifying) + reportVerifyStep(onStep, "verify") + var latest []byte + sawVerifyPage := false + checkedAppPage := false + lastCheck := time.Now() + for { + if ctx.Err() != nil { + return true, latest, nil + } + pageURL, evalErr := session.client.evaluateString(ctx, session.contextID, "location.href") + if evalErr != nil { + if loginBrowserExit(evalErr) != nil || ctx.Err() != nil { + return true, latest, nil + } + if !retryablePageEvaluation(evalErr) { + return true, latest, fmt.Errorf("读取账户验证页面: %w", evalErr) + } + if waitContext(ctx, 300*time.Millisecond) != nil { + return true, latest, nil + } + continue + } + session.captureCurrentOrigin(ctx, pageURL, origins) + if isVerificationPageURL(pageURL) { + sawVerifyPage = true + checkedAppPage = false + } + leftVerify := isAIStudioAppURL(pageURL) && (sawVerifyPage || !checkedAppPage) + due := time.Since(lastCheck) >= pollInterval + if check != nil && (leftVerify || due) { + if exported, exportErr := session.exportStorageState(ctx, origins); exportErr == nil { + if raw, marshalErr := json.Marshal(exported); marshalErr == nil { + latest = raw + } + } else if loginBrowserExit(exportErr) != nil || ctx.Err() != nil { + return true, latest, nil + } + view.setStatus(liveViewChecking) + reportVerifyStep(onStep, "verifying") + needVerify, checkErr := check(ctx, latest) + lastCheck = time.Now() + if checkErr == nil && !needVerify { + return false, latest, nil + } + if ctx.Err() != nil { + return true, latest, nil + } + if leftVerify { + sawVerifyPage = false + checkedAppPage = true + } + view.setStatus(liveViewVerifying) + reportVerifyStep(onStep, "verify") + } + if waitContext(ctx, 300*time.Millisecond) != nil { + return true, latest, nil + } + } } // errorText 返回错误文本,nil 返回空字符串 @@ -136,7 +375,10 @@ func errorText(err error) string { return err.Error() } -func startLoginSession(ctx context.Context, options LoginOptions, state storageState) (*loginSession, error) { +func startLoginSession(ctx context.Context, options LoginOptions, state storageState, startURL string) (*loginSession, error) { + if startURL == "" { + startURL = aiStudioOrigin + "/prompts/new_chat" + } ffVersion := camoufoxFirefoxMajor fingerprintPath := filepath.Join(options.Directory, "storage-state.json") fingerprint, err := loadAccountCamoufoxConfig(fingerprintPath, ffVersion, options.Locale, options.Timezone) @@ -217,7 +459,7 @@ func startLoginSession(ctx context.Context, options LoginOptions, state storageS } if _, err := session.client.command(ctx, "browsingContext.navigate", map[string]any{ "context": session.contextID, - "url": aiStudioOrigin + "/prompts/new_chat", + "url": startURL, "wait": wait, }); err != nil && !commandErrorContains(err, "NS_ERROR_ABORT") { return nil, fmt.Errorf("导航 AI Studio: %w", err) diff --git a/internal/camoufoxnative/protected.go b/internal/camoufoxnative/protected.go index f7df8371..6952475d 100644 --- a/internal/camoufoxnative/protected.go +++ b/internal/camoufoxnative/protected.go @@ -346,17 +346,18 @@ type protectedResponseBody struct { channel *bidiChannel // stop 在正文读完前关闭时中止请求,为空时在页面中止 XHR stop func() error - // release 在关闭时结束请求所在的标签页使用,参数表示正文已读完与正文中出现了函数调用;为空时按受保护请求结束 - release func(done, call bool) + // release 在关闭时结束请求所在的标签页使用,参数表示正文已正常读完与正文中出现了函数调用;为空时按受保护请求结束 + release func(completed, call bool) // call 表示正文中出现了函数调用 Part,tail 是已读正文末尾不足一个标记长度的字节 call bool tail []byte - mu sync.Mutex - buffer []byte - consumed int - done bool - closed bool + mu sync.Mutex + buffer []byte + consumed int + done bool + completed bool + closed bool } func (body *protectedResponseBody) Read(target []byte) (int, error) { @@ -399,6 +400,7 @@ func (body *protectedResponseBody) Read(target []byte) (int, error) { } if message.Error != "" || message.Done { body.done = true + body.completed = message.Done && message.Error == "" body.worker.client.closeChannel(body.requestID) } if message.Error != "" { @@ -421,10 +423,10 @@ func (body *protectedResponseBody) Close() error { return nil } body.closed = true - done, call := body.done, body.call + done, completed, call := body.done, body.completed, body.call body.mu.Unlock() if body.release != nil { - defer body.release(done, call) + defer body.release(completed, call) } else { defer body.worker.finishRequest(body.contextID) } diff --git a/internal/camoufoxnative/types.go b/internal/camoufoxnative/types.go index c7a7c0e7..f6762c36 100644 --- a/internal/camoufoxnative/types.go +++ b/internal/camoufoxnative/types.go @@ -1,6 +1,7 @@ package camoufoxnative import ( + "context" "errors" "fmt" "io" @@ -122,6 +123,8 @@ type Options struct { ReadyTimeout time.Duration Log io.Writer StartupProgress func(StartupStage) + // RefreshCookies 在重建 WAA VM 前刷新即将到期的 DBSC 绑定 Cookie,为空时跳过 + RefreshCookies func(context.Context) error // liveView 表示无头画面实时显示在管理页登录窗口,页面保持 Firefox 默认刷新帧率 liveView bool } diff --git a/internal/camoufoxnative/worker.go b/internal/camoufoxnative/worker.go index 63c7aceb..8c2c2ffe 100644 --- a/internal/camoufoxnative/worker.go +++ b/internal/camoufoxnative/worker.go @@ -70,6 +70,8 @@ type Worker struct { // chatOpening 表示正在后台新开界面对话标签页,chatOpenErr 是最近一次新开失败的原因 chatOpening bool chatOpenErr error + // reloads 是重新载入切换标签页的次数,用于丢弃切换前开始新开的标签页 + reloads uint64 // selected 是浏览器窗口中选中的标签页 selected string // inputMu 串行化页面输入与标签页切换,同一时刻只有一个标签页接收指针与输入 @@ -495,6 +497,14 @@ func (worker *Worker) Reload(ctx context.Context) error { contextID = opened } 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) } @@ -507,25 +517,44 @@ func (worker *Worker) Reload(ctx context.Context) error { return worker.switchTab(contextID, loaded) } -// switchTab 切换到已载入页面的标签页;页面在原标签页中重新载入时不关闭标签页,否则原标签页没有进行中的受保护请求时立即关闭,有时在其中最后一个请求结束后关闭 +// switchTab 切换到已载入页面的标签页,关闭空闲的额外标签页并退役在用标签页,在用标签页在其中最后一个请求结束后关闭 func (worker *Worker) switchTab(contextID string, loaded loadedPage) error { worker.mu.Lock() previous := worker.contextID + var extra []*chatTab + if len(worker.chats) > 1 { + extra = worker.chats[1:] + } + worker.reloads++ worker.contextID, worker.page, worker.state, worker.pageCatalog = contextID, loaded.page, loaded.state, loaded.catalog - worker.chats[0], worker.selected = &chatTab{contextID: contextID, page: loaded.page}, contextID - if previous == contextID { - worker.mu.Unlock() - return nil + worker.chats = []*chatTab{{contextID: contextID, page: loaded.page}} + if previous != contextID || worker.selected == "" { + worker.selected = contextID + } + var closing []string + retire := func(id string) { + if use := worker.tabs[id]; use != nil { + use.retired = true + return + } + if worker.selected == id { + worker.selected = "" + } + closing = append(closing, id) } - use := worker.tabs[previous] - if use != nil { - use.retired = true + if previous != contextID { + retire(previous) } + for _, tab := range extra { + retire(tab.contextID) + } + worker.notifyChats() worker.mu.Unlock() - if use == nil { - return worker.closeTab(previous) + var err error + for _, id := range closing { + err = errors.Join(err, worker.closeTab(id)) } - return nil + return err } // beginRequest 记下当前标签页中开始的一个受保护请求,返回该标签页与其中的 WAA 页面对象 @@ -554,6 +583,9 @@ func (worker *Worker) finishRequest(contextID string) { delete(worker.tabs, contextID) } closing := idle && use.retired && !worker.closed + if closing && worker.selected == contextID { + worker.selected = "" + } worker.mu.Unlock() if closing { if err := worker.closeTab(contextID); err != nil { @@ -698,9 +730,16 @@ func (worker *Worker) shutdown() error { client := worker.client connection := worker.connection process := worker.process - contexts := make([]string, 0, len(worker.chats)) + contexts := make([]string, 0, len(worker.chats)+len(worker.tabs)) + seen := make(map[string]struct{}, len(worker.chats)+len(worker.tabs)) for _, tab := range worker.chats { contexts = append(contexts, tab.contextID) + seen[tab.contextID] = struct{}{} + } + for contextID := range worker.tabs { + if _, ok := seen[contextID]; !ok { + contexts = append(contexts, contextID) + } } worker.mu.Unlock() if worker.idle != nil { diff --git a/internal/chromeauth/abe_windows_amd64.go b/internal/chromeauth/abe_windows_amd64.go index c36d87ba..824a63c0 100644 --- a/internal/chromeauth/abe_windows_amd64.go +++ b/internal/chromeauth/abe_windows_amd64.go @@ -3,12 +3,15 @@ package chromeauth import ( + "bytes" _ "embed" "encoding/base64" + "encoding/binary" "encoding/json" "fmt" "os" "path/filepath" + "runtime" "strings" "time" "unicode/utf16" @@ -41,11 +44,15 @@ const ( ) var ( - kernel32 = windows.NewLazySystemDLL("kernel32.dll") - procVirtualAllocEx = kernel32.NewProc("VirtualAllocEx") - procWriteProcessMemory = kernel32.NewProc("WriteProcessMemory") - procCreateRemoteThread = kernel32.NewProc("CreateRemoteThread") - procLoadLibraryW = kernel32.NewProc("LoadLibraryW") + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + procVirtualAllocEx = kernel32.NewProc("VirtualAllocEx") + procWriteProcessMemory = kernel32.NewProc("WriteProcessMemory") + procCreateRemoteThread = kernel32.NewProc("CreateRemoteThread") + procLoadLibraryW = kernel32.NewProc("LoadLibraryW") + versionDLL = windows.NewLazySystemDLL("version.dll") + procGetFileVersionInfoSize = versionDLL.NewProc("GetFileVersionInfoSizeW") + procGetFileVersionInfo = versionDLL.NewProc("GetFileVersionInfoW") + procVerQueryValue = versionDLL.NewProc("VerQueryValueW") ) //go:embed native/abe_helper_amd64.bin @@ -92,20 +99,130 @@ func readAppBoundCiphertext(chromeRoot string) ([]byte, error) { return decoded[len(appBoundPrefix):], nil } -// findChromeExecutable 定位稳定版 Chrome 可执行文件 +// findChromeExecutable 定位官方稳定版 Google Chrome 可执行文件 func findChromeExecutable() (string, error) { + return findChromeExecutableWith(chromeExecutableFromRegistry, chromeExecutableFallbacks()) +} + +// findChromeExecutableWith 依次从 HKCU、HKLM 注册表与常见安装目录查找官方 Google Chrome 可执行文件 +func findChromeExecutableWith(fromRegistry func(registry.Key) (string, error), fallbacks []string) (string, error) { for _, root := range []registry.Key{registry.CURRENT_USER, registry.LOCAL_MACHINE} { - path, err := chromeExecutableFromRegistry(root) - if err == nil { + path, err := fromRegistry(root) + if err == nil && isGoogleChromeExecutable(path) { return path, nil } } - for _, path := range chromeExecutableFallbacks() { - if fileInfo, err := os.Stat(path); err == nil && !fileInfo.IsDir() { + for _, path := range fallbacks { + if isGoogleChromeExecutable(path) { return path, nil } } - return "", fmt.Errorf("找不到 chrome.exe") + return "", fmt.Errorf("找不到官方 Google Chrome chrome.exe") +} + +// isGoogleChromeExecutable 通过 Windows PE 版本信息核对可执行文件为官方 Google Chrome +func isGoogleChromeExecutable(path string) bool { + if fileInfo, err := os.Stat(path); err != nil || fileInfo.IsDir() { + return false + } + pathUTF16, err := windows.UTF16PtrFromString(path) + if err != nil { + return false + } + var handle uint32 + size, _, _ := procGetFileVersionInfoSize.Call( + uintptr(unsafe.Pointer(pathUTF16)), + uintptr(unsafe.Pointer(&handle)), + ) + if size == 0 { + return false + } + block := make([]byte, size) + ok, _, _ := procGetFileVersionInfo.Call( + uintptr(unsafe.Pointer(pathUTF16)), + 0, + size, + uintptr(unsafe.Pointer(&block[0])), + ) + if ok == 0 { + return false + } + for _, langCodePage := range versionTranslations(block) { + company := strings.TrimSpace(versionStringValue(block, fmt.Sprintf(`\StringFileInfo\%s\CompanyName`, langCodePage))) + product := strings.TrimSpace(versionStringValue(block, fmt.Sprintf(`\StringFileInfo\%s\ProductName`, langCodePage))) + if (strings.EqualFold(company, "Google LLC") || strings.EqualFold(company, "Google Inc.")) && + strings.EqualFold(product, "Google Chrome") { + return true + } + } + return false +} + +// versionTranslations 读取版本资源中的语言与代码页列表,缺失时回退到英文 Unicode 表 +func versionTranslations(block []byte) []string { + subBlock, err := windows.UTF16PtrFromString(`\VarFileInfo\Translation`) + if err != nil { + return []string{"040904b0"} + } + var ptr uintptr + var length uint32 + ok, _, _ := procVerQueryValue.Call( + uintptr(unsafe.Pointer(&block[0])), + uintptr(unsafe.Pointer(subBlock)), + uintptr(unsafe.Pointer(&ptr)), + uintptr(unsafe.Pointer(&length)), + ) + defer runtime.KeepAlive(block) + base := uintptr(unsafe.Pointer(&block[0])) + if ok == 0 || ptr < base || length < 4 { + return []string{"040904b0"} + } + offset := int(ptr - base) + size := int(length) + if offset < 0 || offset+size > len(block) { + return []string{"040904b0"} + } + count := size / 4 + raw := block[offset : offset+count*4] + translations := make([]string, 0, count) + for i := 0; i < count; i++ { + lang := binary.LittleEndian.Uint16(raw[i*4 : i*4+2]) + codePage := binary.LittleEndian.Uint16(raw[i*4+2 : i*4+4]) + translations = append(translations, fmt.Sprintf("%04x%04x", lang, codePage)) + } + return translations +} + +// versionStringValue 从 PE 版本资源块中读取指定字符串项 +func versionStringValue(block []byte, path string) string { + subBlock, err := windows.UTF16PtrFromString(path) + if err != nil { + return "" + } + var ptr uintptr + var length uint32 + ok, _, _ := procVerQueryValue.Call( + uintptr(unsafe.Pointer(&block[0])), + uintptr(unsafe.Pointer(subBlock)), + uintptr(unsafe.Pointer(&ptr)), + uintptr(unsafe.Pointer(&length)), + ) + defer runtime.KeepAlive(block) + base := uintptr(unsafe.Pointer(&block[0])) + if ok == 0 || ptr < base || length == 0 { + return "" + } + offset := int(ptr - base) + byteLen := int(length) * 2 + if offset < 0 || offset+byteLen > len(block) { + return "" + } + units := make([]uint16, int(length)) + raw := block[offset : offset+byteLen] + for i := range units { + units[i] = binary.LittleEndian.Uint16(raw[i*2 : i*2+2]) + } + return windows.UTF16ToString(units) } // chromeExecutableFromRegistry 读取 Windows App Paths @@ -119,7 +236,7 @@ func chromeExecutableFromRegistry(root registry.Key) (string, error) { if err != nil { return "", err } - value = strings.TrimSpace(value) + value = strings.Trim(strings.TrimSpace(value), `"`) if value == "" { return "", fmt.Errorf("Chrome App Paths 为空") } @@ -184,7 +301,7 @@ func decryptAppBoundCiphertext(chromePath string, encrypted []byte) ([]byte, err for time.Now().Before(deadline) { data, err := os.ReadFile(outputPath) if err == nil { - if len(data) != 32 { + if bytes.HasPrefix(data, []byte("ERR ")) || len(data) != 32 { return nil, fmt.Errorf("Chrome ABE helper 返回异常: %s", strings.TrimSpace(string(data))) } return data, nil diff --git a/internal/chromeauth/auth.go b/internal/chromeauth/auth.go index 5e3c6254..8de2641f 100644 --- a/internal/chromeauth/auth.go +++ b/internal/chromeauth/auth.go @@ -7,6 +7,7 @@ import ( "fmt" "sort" "strings" + "sync" "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" @@ -43,6 +44,90 @@ type ImportResult struct { State aistudio.StorageState } +// ProfileTierResult 是按需检测单个本机 Chrome 账号权益的结果 +type ProfileTierResult struct { + ID string + BenefitTier string + Restricted string + Error string +} + +// CheckProfileTiers 复用一次主密钥读取与官网公共头,并发检测所选 Chrome 账号的 AI Studio 权益并逐条回调结果 +func CheckProfileTiers(ctx context.Context, options ImportOptions, onResult func(ProfileTierResult)) error { + if err := ensurePlatformImport(); err != nil { + return err + } + proxyURL := strings.TrimSpace(options.Proxy) + if err := config.ValidateProxy(proxyURL); err != nil { + return err + } + accounts, err := Discover(options.ChromeRoot) + if err != nil { + return err + } + selected, err := selectAccounts(accounts, options.Profiles, options.Emails, options.AccountIDs) + if err != nil { + return err + } + masterKey, err := retrieveV20Key(options.ChromeRoot) + if err != nil { + return err + } + client, err := aistudio.NewProxyHTTPClient(proxyURL) + if err != nil { + return err + } + defer client.CloseIdleConnections() + headers, err := aistudio.DiscoverPublicHeaders(ctx, client) + if err != nil { + return err + } + const maxConcurrency = 4 + sem := make(chan struct{}, maxConcurrency) + var emitMu sync.Mutex + var group sync.WaitGroup + for _, account := range selected { + if ctx.Err() != nil { + break + } + account := account + group.Go(func() { + select { + case sem <- struct{}{}: + defer func() { <-sem }() + case <-ctx.Done(): + return + } + item := ProfileTierResult{ID: account.ID} + imported, err := importAccount(ctx, options.ChromeRoot, proxyURL, account, masterKey) + if err != nil { + if ctx.Err() != nil { + return + } + item.Error = err.Error() + } else if tier, err := fetchBenefitTier(ctx, client, &imported.State, headers, 0); err != nil { + if ctx.Err() != nil { + return + } + if denial := aistudio.RestrictionDenial(err); denial != nil { + item.Restricted = denial.Error() + } else { + item.Error = err.Error() + } + } else { + item.BenefitTier = tier.String() + } + if onResult != nil && ctx.Err() == nil { + emitMu.Lock() + onResult(item) + emitMu.Unlock() + } + }) + } + group.Wait() + return ctx.Err() +} + // Import 用本机 Chrome 的 OAuth 续签材料生成 Playwright storage state func Import(ctx context.Context, options ImportOptions) ([]ImportResult, error) { if err := ensurePlatformImport(); err != nil { @@ -88,6 +173,14 @@ func Refresh(ctx context.Context, source aistudio.AuthSource, material aistudio. return toStorageCookies(cookies), bound, nil } +// ChromeRoot 返回非空的自定义 Chrome User Data 目录,root 为空时返回稳定版默认目录 +func ChromeRoot(root string) (string, error) { + if trimmed := strings.TrimSpace(root); trimmed != "" { + return trimmed, nil + } + return DefaultChromeRoot() +} + // sourceIdentity 返回导入来源 Chrome profile 的请求身份与校验后的代理,来源未记录目录时使用稳定版 Chrome 目录 func sourceIdentity(source aistudio.AuthSource, proxy string) (chromeIdentity, string, error) { if err := ensurePlatformImport(); err != nil { @@ -98,11 +191,9 @@ func sourceIdentity(source aistudio.AuthSource, proxy string) (chromeIdentity, s if err != nil { return chromeIdentity{}, "", err } - root := source.Root - if root == "" { - if root, err = DefaultChromeRoot(); err != nil { - return chromeIdentity{}, "", err - } + root, err := ChromeRoot(source.Root) + if err != nil { + return chromeIdentity{}, "", err } identity, err := readChromeIdentity(root, source.Profile) return identity, proxyURL, err diff --git a/internal/chromeauth/native/abe_helper.c b/internal/chromeauth/native/abe_helper.c index 744ef3ae..97dc89b3 100644 --- a/internal/chromeauth/native/abe_helper.c +++ b/internal/chromeauth/native/abe_helper.c @@ -62,11 +62,66 @@ static void write_error(const wchar_t *path, const char *message) { write_output(path, (const BYTE *)message, (DWORD)lstrlenA(message)); } +// append_str 追加 ASCII 字符串,返回新的写入位置 +static char *append_str(char *dst, char *end, const char *src) { + while (*src != '\0' && dst < end) { + *dst++ = *src++; + } + return dst; +} + +// append_hex32 追加 8 位小写十六进制数 +static char *append_hex32(char *dst, char *end, DWORD value) { + static const char digits[] = "0123456789abcdef"; + for (int shift = 28; shift >= 0 && dst < end; shift -= 4) { + *dst++ = digits[(value >> shift) & 0xF]; + } + return dst; +} + +// append_dec 追加无符号十进制数 +static char *append_dec(char *dst, char *end, DWORD value) { + char buf[16]; + int n = 0; + do { + buf[n++] = (char)('0' + (value % 10)); + value /= 10; + } while (value != 0); + while (n > 0 && dst < end) { + *dst++ = buf[--n]; + } + return dst; +} + +// write_decrypt_error 写出带阶段、HRESULT 与系统错误码的诊断信息 +static void write_decrypt_error(const wchar_t *path, const char *stage, HRESULT hr, DWORD last_error) { + char buf[96]; + char *p = buf; + char *end = buf + sizeof(buf) - 1; + p = append_str(p, end, "ERR "); + p = append_str(p, end, stage); + p = append_str(p, end, " hr=0x"); + p = append_hex32(p, end, (DWORD)hr); + p = append_str(p, end, " err="); + p = append_dec(p, end, last_error); + *p = '\0'; + write_error(path, buf); +} + // call_decrypt 调用 Chrome IElevator 解开 App-Bound 主密钥 -static HRESULT call_decrypt(const BYTE *ciphertext, DWORD ciphertext_size, BYTE *plaintext, DWORD plaintext_size) { +static HRESULT call_decrypt( + const BYTE *ciphertext, + DWORD ciphertext_size, + BYTE *plaintext, + DWORD plaintext_size, + const char **stage_out, + DWORD *last_error_out +) { const IID clsid_chrome = {0x708860E0, 0xF641, 0x4611, {0x88, 0x95, 0x7D, 0x86, 0x7D, 0xD3, 0x67, 0x5B}}; const IID iid_chrome_v2 = {0x1BF5208B, 0x295F, 0x4992, {0xB5, 0xF4, 0x3A, 0x9B, 0xB6, 0x49, 0x48, 0x38}}; const IID iid_chrome_v1 = {0x463ABECF, 0x410D, 0x407F, {0x8A, 0xF5, 0x0D, 0xF3, 0x5A, 0x00, 0x5C, 0xC8}}; + *stage_out = "cocreate"; + *last_error_out = 0; IUnknown *object = NULL; HRESULT hr = CoCreateInstance(&clsid_chrome, NULL, CLSCTX_LOCAL_SERVER, &iid_chrome_v2, (void **)&object); if (FAILED(hr)) { @@ -76,6 +131,7 @@ static HRESULT call_decrypt(const BYTE *ciphertext, DWORD ciphertext_size, BYTE return hr; } + *stage_out = "blanket"; hr = CoSetProxyBlanket(object, RPC_C_AUTHN_DEFAULT, RPC_C_AUTHZ_DEFAULT, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_DYNAMIC_CLOAKING); if (FAILED(hr)) { @@ -83,6 +139,7 @@ static HRESULT call_decrypt(const BYTE *ciphertext, DWORD ciphertext_size, BYTE return hr; } + *stage_out = "alloc"; BSTR input = SysAllocStringByteLen((LPCSTR)ciphertext, ciphertext_size); if (input == NULL) { object->lpVtbl->Release(object); @@ -92,12 +149,15 @@ static HRESULT call_decrypt(const BYTE *ciphertext, DWORD ciphertext_size, BYTE DWORD last_error = 0; void **vtable = *(void ***)object; DecryptDataFn decrypt_data = (DecryptDataFn)vtable[5]; + *stage_out = "decrypt"; hr = decrypt_data(object, input, &output, &last_error); SysFreeString(input); if (FAILED(hr)) { + *last_error_out = last_error; object->lpVtbl->Release(object); return hr; } + *stage_out = "size"; UINT size = SysStringByteLen(output); if (size != plaintext_size) { SysFreeString(output); @@ -127,16 +187,18 @@ static DWORD WINAPI worker(LPVOID parameter) { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); BOOL com_initialized = SUCCEEDED(hr); if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) { - write_error(output_path, "ERR cominit"); + write_decrypt_error(output_path, "cominit", hr, 0); HeapFree(GetProcessHeap(), 0, ciphertext); goto done; } BYTE key[32] = {0}; - hr = call_decrypt(ciphertext, ciphertext_size, key, sizeof(key)); + const char *stage = "decrypt"; + DWORD last_error = 0; + hr = call_decrypt(ciphertext, ciphertext_size, key, sizeof(key), &stage, &last_error); if (SUCCEEDED(hr)) { write_output(output_path, key, sizeof(key)); } else { - write_error(output_path, "ERR decrypt"); + write_decrypt_error(output_path, stage, hr, last_error); } if (com_initialized) { CoUninitialize(); diff --git a/internal/chromeauth/native/abe_helper_amd64.bin b/internal/chromeauth/native/abe_helper_amd64.bin index 5a890aa0..5f4f5595 100644 Binary files a/internal/chromeauth/native/abe_helper_amd64.bin and b/internal/chromeauth/native/abe_helper_amd64.bin differ diff --git a/internal/chromeauth/verify.go b/internal/chromeauth/verify.go index a7edb169..b8c0e763 100644 --- a/internal/chromeauth/verify.go +++ b/internal/chromeauth/verify.go @@ -12,6 +12,7 @@ import ( "slices" "strconv" "strings" + "sync" "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" @@ -39,6 +40,8 @@ type Verification struct { type CookieAccount struct { AuthUser int Email string + // BenefitTier 是识别阶段顺带读取的账户权益等级,读取失败时为空 + BenefitTier string // Restricted 是该会话打开 AI Studio 时被转到 Google 受限页的原因,此时邮箱为空 Restricted string } @@ -112,6 +115,20 @@ func discoverSessions(ctx context.Context, client *http.Client, state *aistudio. } accounts = append(accounts, CookieAccount{AuthUser: authUser, Email: email}) } + var group sync.WaitGroup + for index := range accounts { + if accounts[index].Restricted != "" || accounts[index].Email == "" { + continue + } + accountIndex := index + authUser := accounts[accountIndex].AuthUser + group.Go(func() { + if tier, err := fetchBenefitTier(ctx, client, state, headers, authUser); err == nil { + accounts[accountIndex].BenefitTier = tier.String() + } + }) + } + group.Wait() return accounts, nil } @@ -181,6 +198,23 @@ func verifyChatPage(ctx context.Context, client *http.Client, state *aistudio.St return email, mergeResponseCookies(state, response, targetURL) } +// fetchBenefitTier 以页面的请求头与 Cookie 读取 GetAiStudioBenefitTier 并解码账户权益等级 +func fetchBenefitTier(ctx context.Context, client *http.Client, state *aistudio.StorageState, headers http.Header, authUser int) (aistudio.BenefitTier, error) { + response, err := makerSuiteRequest(ctx, client, state, headers, authUser, "GetAiStudioBenefitTier") + if err != nil { + return aistudio.BenefitTierFree, fmt.Errorf("读取 AI Studio 账户权益: %w", err) + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + return aistudio.BenefitTierFree, err + } + if response.StatusCode != http.StatusOK { + return aistudio.BenefitTierFree, aistudio.DecodeRPCError("GetAiStudioBenefitTier", response.StatusCode, body) + } + return aistudio.DecodeBenefitTier(body) +} + // verifyLoggingContext 以页面的请求头读取 GetLoggingContext,上游拒绝时返回解码后的错误 func verifyLoggingContext(ctx context.Context, client *http.Client, state *aistudio.StorageState, headers http.Header, authUser int) error { response, err := makerSuiteRequest(ctx, client, state, headers, authUser, "GetLoggingContext") diff --git a/internal/config/config.go b/internal/config/config.go index ba46c0bd..38627486 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -69,8 +69,12 @@ var configKeys = [...]string{ "GOOGLE_SEARCH", "FIRST_EVENT_HEDGE", "FIRST_EVENT_HEDGE_MODELS", + "FIRST_EVENT_TIMEOUT", "CONTINUATION_REWRITE", "CONTINUATION_PROMPT", + "REPLY_TOOL", + "USER_MESSAGE_REWRITE", + "THINKING_GUARD", } // LogFileMB 是单个日志文件的轮转大小 @@ -94,6 +98,9 @@ const FirstEventHedgeOff = "off" // FirstEventHedgeAuto 表示按模型与通道近期原请求首事件等待的 p95 发起备用请求 const FirstEventHedgeAuto = "auto" +// FirstEventTimeoutOff 表示不限制单次尝试等待首个事件的时间 +const FirstEventTimeoutOff = "off" + // DefaultMaxAccountSwitches 是 MAX_ACCOUNT_SWITCHES 的默认值 const DefaultMaxAccountSwitches = 3 @@ -106,6 +113,15 @@ const MediaOutputInline = "inline" // MediaOutputURL 表示生成的媒体保存到本地,Chat 与 Messages 正文以 URL 引用 const MediaOutputURL = "url" +// UserMessageRewriteOff 表示不改写用户消息文字 +const UserMessageRewriteOff = "off" + +// UserMessageRewriteTraditional 表示发送前将用户消息中的简体中文转为繁体 +const UserMessageRewriteTraditional = "traditional" + +// UserMessageRewriteMartian 表示发送前将用户消息中的中文转为火星文 +const UserMessageRewriteMartian = "martian" + // DefaultContinuationPrompt 是 CONTINUATION_PROMPT 未设置时改写末尾 assistant 轮所用的续写提示词 const DefaultContinuationPrompt = "Continue the assistant response after the following prefix. Return only the continuation, without repeating the prefix." @@ -129,8 +145,12 @@ type Config struct { GoogleSearch bool FirstEventHedge string FirstEventHedgeModels string + FirstEventTimeout string ContinuationRewrite bool ContinuationPrompt string + ReplyTool bool + UserMessageRewrite string + ThinkingGuard bool AuthStates string ListenAddr string PreviewListenAddr string @@ -182,8 +202,10 @@ func Default() Config { SearchModelAliases: true, FirstEventHedge: FirstEventHedgeOff, FirstEventHedgeModels: DefaultFirstEventHedgeModels, + FirstEventTimeout: FirstEventTimeoutOff, ContinuationRewrite: true, ContinuationPrompt: DefaultContinuationPrompt, + UserMessageRewrite: UserMessageRewriteOff, AuthStates: defaultAuthStates, ListenAddr: defaultListenAddr, PreviewListenAddr: defaultPreviewListenAddr, @@ -234,7 +256,10 @@ 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 }), + "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 }), @@ -247,6 +272,7 @@ var configSetters = map[string]func(*Config, string) error{ "ADMIN_PASSWORD": textSetter(func(c *Config) *string { return &c.AdminPassword }, func(value string) string { return value }), "FIRST_EVENT_HEDGE": textSetter(func(c *Config) *string { return &c.FirstEventHedge }, lowerTrim), "FIRST_EVENT_HEDGE_MODELS": textSetter(func(c *Config) *string { return &c.FirstEventHedgeModels }, strings.TrimSpace), + "FIRST_EVENT_TIMEOUT": textSetter(func(c *Config) *string { return &c.FirstEventTimeout }, lowerTrim), "CONTINUATION_PROMPT": textSetter(func(c *Config) *string { return &c.ContinuationPrompt }, strings.TrimSpace), "AISTUDIO_AUTH_STATES": textSetter(func(c *Config) *string { return &c.AuthStates }, strings.TrimSpace), "LISTEN_ADDR": textSetter(func(c *Config) *string { return &c.ListenAddr }, strings.TrimSpace), @@ -436,12 +462,24 @@ var configChecks = []configCheck{ _, _, err := ParseFirstEventHedge(c.FirstEventHedge) return err }}, + {[]string{"FIRST_EVENT_TIMEOUT"}, func(c Config) error { + _, err := ParseFirstEventTimeout(c.FirstEventTimeout) + return err + }}, {[]string{"MEDIA_OUTPUT"}, func(c Config) error { if c.MediaOutput != MediaOutputInline && c.MediaOutput != MediaOutputURL { return fmt.Errorf("MEDIA_OUTPUT 必须是 inline 或 url") } return nil }}, + {[]string{"USER_MESSAGE_REWRITE"}, func(c Config) error { + switch c.UserMessageRewrite { + case UserMessageRewriteOff, UserMessageRewriteTraditional, UserMessageRewriteMartian: + return nil + default: + return fmt.Errorf("USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian") + } + }}, {[]string{"MEDIA_BASE_URL"}, func(c Config) error { if c.MediaBaseURL == "" { return nil @@ -610,8 +648,12 @@ func (c Config) envValues() map[string]string { "GOOGLE_SEARCH": strconv.FormatBool(c.GoogleSearch), "FIRST_EVENT_HEDGE": c.FirstEventHedge, "FIRST_EVENT_HEDGE_MODELS": c.FirstEventHedgeModels, - "CONTINUATION_REWRITE": strconv.FormatBool(c.ContinuationRewrite), - "CONTINUATION_PROMPT": c.ContinuationPrompt, + "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), "AISTUDIO_AUTH_STATES": c.AuthStates, "LISTEN_ADDR": c.ListenAddr, "PREVIEW_LISTEN_ADDR": c.PreviewListenAddr, @@ -724,6 +766,18 @@ func ParseFirstEventHedge(value string) (bool, time.Duration, error) { return false, time.Duration(seconds) * time.Second, nil } +// ParseFirstEventTimeout 解析 FIRST_EVENT_TIMEOUT,返回单次尝试等待首个事件的最长时间,off 时为零值 +func ParseFirstEventTimeout(value string) (time.Duration, error) { + if value == FirstEventTimeoutOff { + return 0, nil + } + seconds, err := strconv.Atoi(value) + if err != nil || seconds <= 0 { + return 0, fmt.Errorf("FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒") + } + return time.Duration(seconds) * time.Second, 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 291efc4a..6388b408 100644 --- a/internal/i18n/messages/de.json +++ b/internal/i18n/messages/de.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Drive-Autorisierung unvollständig, Popup verblieb auf {0}: {1}", "Drive 文件回收失败": "Drive-Datei konnte nicht gelöscht werden", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE muss off, auto oder eine positive ganze Zahl in Sekunden sein", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT muss off oder eine positive ganze Zahl in Sekunden sein", "Gemini Live JSON 无效: %v": "Ungültiges Gemini-Live-JSON: {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken gab HTTP {0} zurück", "GenerateContent contents 不能为空": "contents für GenerateContent darf nicht leer sein", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS darf nur playground und build enthalten", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS muss mindestens playground oder build enthalten", "UPSTREAM_CHANNELS 通道 %s 重复": "UPSTREAM_CHANNELS: Kanal {0} ist doppelt vorhanden", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE muss off, traditional oder martian sein", "Value 同时设置多个 oneof 字段": "Value: Mehrere oneof-Felder gleichzeitig gesetzt", "Value 缺少 oneof 字段": "Value: oneof-Feld fehlt", "VirtualAllocEx 失败: %w": "VirtualAllocEx fehlgeschlagen: {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "Konto-Verzeichnis {0} scannen: {1}", "找不到 Chrome Profile: %s": "Chrome-Profile nicht gefunden: {0}", "找不到 Chrome 账号: %s": "Chrome-Konto nicht gefunden: {0}", - "找不到 chrome.exe": "chrome.exe nicht gefunden", + "找不到官方 Google Chrome chrome.exe": "Offizielle Google-Chrome-Datei chrome.exe nicht gefunden", + "创建隔离验证目录: %w": "isoliertes Verifizierungsverzeichnis erstellen: {0}", + "当前登录驱动不支持打开验证窗口": "Der aktuelle Anmeldetreiber unterstützt kein Verifizierungsfenster", + "核对账户验证状态": "Verifizierungsstatus des Kontos wird geprüft", + "等待完成账户验证": "Warten auf Kontoverifizierung", + "编码账户认证状态: %w": "Authentifizierungsstatus des Kontos kodieren: {0}", + "解析账户 storage state: %w": "Storage-State des Kontos parsen: {0}", + "解析验证状态: %w": "Verifizierungsstatus parsen: {0}", + "读取账户验证页面: %w": "Verifizierungsseite des Kontos lesen: {0}", + "账户核对完成": "Kontoprüfung abgeschlossen", + "账户没有可用于验证的 Cookie": "Das Konto hat keine Cookies für die Verifizierung", + "账户需要验证": "Kontoverifizierung erforderlich", + "账户验证": "Kontoverifizierung", + "账户验证失败": "Kontoverifizierung fehlgeschlagen", + "账户验证完成": "Kontoverifizierung abgeschlossen", + "账户验证核对失败": "Prüfung der Kontoverifizierung fehlgeschlagen", + "账户验证窗口已关闭,账户仍需要验证": "Verifizierungsfenster geschlossen; das Konto muss weiterhin verifiziert werden", "找不到选中的 Chrome 账号": "Ausgewähltes Chrome-Konto nicht gefunden", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "Remote-Debugging-Adresse von Antidetect-Browser oder Chromium zum Auslesen der Cookies", "排队等待": "Warten in der Warteschlange", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "Im Skript des Cookie-Banners fehlt der API-Schlüssel", "api.js 缺少 gapi 模块配置": "In api.js fehlt die gapi-Modulkonfiguration", "入门卡片模块系列 %s 的预览图: %w": "Vorschaubild der Serie {0} im Einstiegskarten-Modul: {1}", - "关闭 Cookie 提示条失败": "Cookie-Banner konnte nicht geschlossen werden", "关闭 WAA Worker": "WAA-Worker wird beendet", "解析页面 localStorage: %w": "Seiten-localStorage parsen: {0}", "读取页面 localStorage: %w": "Seiten-localStorage lesen: {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "Der Seite fehlt die Adresse des gapi-client-Moduls", "关闭重新载入前的页面失败": "Seite von vor dem Neuladen konnte nicht geschlossen werden", "设置收缩模式: %w": "Komprimierungsmodus festlegen: {0}", - "预先打开页面失败": "Seite konnte nicht vorab geöffnet werden" + "预先打开页面失败": "Seite konnte nicht vorab geöffnet werden", + "重新生成": "Neu generieren", + "模型没有使用回复工具": "Das Modell hat das Antwort-Tool nicht verwendet", + "结束原因 %s": "Abschlussgrund {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "Seit {0} keine Daten vom Upstream, REQUEST_TIMEOUT überschritten", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "Seit {0} kein erstes Ereignis vom Upstream, FIRST_EVENT_TIMEOUT überschritten", + "创建账户 Camoufox 指纹临时文件: %w": "Temporäre Camoufox-Fingerabdruckdatei des Kontos erstellen: {0}", + "同步账户 Camoufox 指纹: %w": "Camoufox-Fingerabdruck des Kontos synchronisieren: {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "Temporäre Camoufox-Fingerabdruckdatei des Kontos schließen: {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "Neu geöffneter Camoufox-Tab von vor dem Neuladen konnte nicht geschlossen werden", + "账户备注不能超过 %d 个字符": "Die Kontonotiz darf höchstens {0} Zeichen enthalten", + "读取 AI Studio 账户权益: %w": "AI Studio-Kontostufe lesen: {0}" } diff --git a/internal/i18n/messages/en.json b/internal/i18n/messages/en.json index 75739fb2..4b1ece83 100644 --- a/internal/i18n/messages/en.json +++ b/internal/i18n/messages/en.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Drive authorization not completed, popup stopped at {0}: {1}", "Drive 文件回收失败": "Drive file recycling failed", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE must be off, auto, or a positive integer in seconds", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT must be off or a positive integer in seconds", "Gemini Live JSON 无效: %v": "Invalid Gemini Live JSON: {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken returned HTTP {0}", "GenerateContent contents 不能为空": "GenerateContent contents cannot be empty", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS can only contain playground and build", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS must contain at least playground or build", "UPSTREAM_CHANNELS 通道 %s 重复": "Duplicate UPSTREAM_CHANNELS Channel {0}", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE must be off, traditional, or martian", "Value 同时设置多个 oneof 字段": "Value has multiple oneof fields set", "Value 缺少 oneof 字段": "Value is missing oneof field", "VirtualAllocEx 失败: %w": "VirtualAllocEx failed: {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "Scan account directory {0}: {1}", "找不到 Chrome Profile: %s": "Chrome Profile not found: {0}", "找不到 Chrome 账号: %s": "Chrome account not found: {0}", - "找不到 chrome.exe": "chrome.exe not found", + "找不到官方 Google Chrome chrome.exe": "Official Google Chrome chrome.exe not found", + "创建隔离验证目录: %w": "create isolated verification directory: {0}", + "当前登录驱动不支持打开验证窗口": "The current sign-in driver does not support opening a verification window", + "核对账户验证状态": "Checking account verification status", + "等待完成账户验证": "Waiting for account verification", + "编码账户认证状态: %w": "encode account authentication state: {0}", + "解析账户 storage state: %w": "parse account storage state: {0}", + "解析验证状态: %w": "parse verification state: {0}", + "读取账户验证页面: %w": "read account verification page: {0}", + "账户核对完成": "Account verification check completed", + "账户没有可用于验证的 Cookie": "Account has no cookies available for verification", + "账户需要验证": "Account verification required", + "账户验证": "Account verification", + "账户验证失败": "Account verification failed", + "账户验证完成": "Account verification completed", + "账户验证核对失败": "Account verification check failed", + "账户验证窗口已关闭,账户仍需要验证": "Verification window closed; account still requires verification", "找不到选中的 Chrome 账号": "Selected Chrome account not found", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "Remote debugging address of fingerprint browser or Chromium to read Cookies from", "排队等待": "Queue waiting", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "Cookie banner script is missing the API key", "api.js 缺少 gapi 模块配置": "api.js is missing the gapi module configuration", "入门卡片模块系列 %s 的预览图: %w": "Preview image for series {0} in the getting-started card module: {1}", - "关闭 Cookie 提示条失败": "Failed to close the cookie banner", "关闭 WAA Worker": "Stopping WAA Workers", "解析页面 localStorage: %w": "Parse page localStorage: {0}", "读取页面 localStorage: %w": "Read page localStorage: {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "The page is missing the gapi client module URL", "关闭重新载入前的页面失败": "Failed to close the page from before the reload", "设置收缩模式: %w": "Set vacuum mode: {0}", - "预先打开页面失败": "Failed to open a spare page in advance" + "预先打开页面失败": "Failed to open a spare page in advance", + "重新生成": "Regenerating", + "模型没有使用回复工具": "Model did not use the reply tool", + "结束原因 %s": "Finish reason {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "No data from upstream for {0}, exceeding REQUEST_TIMEOUT", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "No first event from upstream for {0}, exceeding FIRST_EVENT_TIMEOUT", + "创建账户 Camoufox 指纹临时文件: %w": "Create temporary account Camoufox fingerprint file: {0}", + "同步账户 Camoufox 指纹: %w": "Sync account Camoufox fingerprint: {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "Close temporary account Camoufox fingerprint file: {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "Failed to close the newly opened Camoufox tab before reload", + "账户备注不能超过 %d 个字符": "Account note cannot exceed {0} characters", + "读取 AI Studio 账户权益: %w": "Read AI Studio account tier: {0}" } diff --git a/internal/i18n/messages/fr.json b/internal/i18n/messages/fr.json index 1ebfbd1a..8fc5fb05 100644 --- a/internal/i18n/messages/fr.json +++ b/internal/i18n/messages/fr.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Autorisation Drive non terminée, la fenêtre contextuelle s’est arrêtée à {0} : {1}", "Drive 文件回收失败": "Échec de la mise à la corbeille du fichier Drive", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE doit être off, auto ou un entier positif en secondes", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT doit être off ou un entier positif en secondes", "Gemini Live JSON 无效: %v": "JSON Gemini Live non valide : {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken a renvoyé HTTP {0}", "GenerateContent contents 不能为空": "contents de GenerateContent ne peut pas être vide", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS ne peut contenir que playground et build", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS doit contenir au moins playground ou build", "UPSTREAM_CHANNELS 通道 %s 重复": "Canal UPSTREAM_CHANNELS {0} en double", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE doit être off, traditional ou martian", "Value 同时设置多个 oneof 字段": "Plusieurs champs oneof définis simultanément dans Value", "Value 缺少 oneof 字段": "Champ oneof manquant dans Value", "VirtualAllocEx 失败: %w": "Échec de VirtualAllocEx : {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "Analyse du répertoire de comptes {0} : {1}", "找不到 Chrome Profile: %s": "Profile Chrome introuvable : {0}", "找不到 Chrome 账号: %s": "Compte Chrome introuvable : {0}", - "找不到 chrome.exe": "chrome.exe introuvable", + "找不到官方 Google Chrome chrome.exe": "Exécutable officiel Google Chrome chrome.exe introuvable", + "创建隔离验证目录: %w": "création du répertoire de vérification isolé : {0}", + "当前登录驱动不支持打开验证窗口": "Le pilote de connexion actuel ne prend pas en charge l’ouverture d’une fenêtre de vérification", + "核对账户验证状态": "Vérification de l’état du compte", + "等待完成账户验证": "En attente de la vérification du compte", + "编码账户认证状态: %w": "encodage de l’état d’authentification du compte : {0}", + "解析账户 storage state: %w": "analyse du storage state du compte : {0}", + "解析验证状态: %w": "analyse de l’état de vérification : {0}", + "读取账户验证页面: %w": "lecture de la page de vérification du compte : {0}", + "账户核对完成": "Vérification du compte terminée", + "账户没有可用于验证的 Cookie": "Le compte ne dispose d’aucun cookie utilisable pour la vérification", + "账户需要验证": "Vérification du compte requise", + "账户验证": "Vérification du compte", + "账户验证失败": "Échec de la vérification du compte", + "账户验证完成": "Vérification du compte terminée", + "账户验证核对失败": "Échec du contrôle de vérification du compte", + "账户验证窗口已关闭,账户仍需要验证": "Fenêtre de vérification fermée ; le compte nécessite toujours une vérification", "找不到选中的 Chrome 账号": "Compte Chrome sélectionné introuvable", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "Adresse de débogage distant du navigateur antidétection ou Chromium, pour en lire les Cookies", "排队等待": "En attente dans la file", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "Clé API manquante dans le script du bandeau de cookies", "api.js 缺少 gapi 模块配置": "Configuration du module gapi manquante dans api.js", "入门卡片模块系列 %s 的预览图: %w": "Image d’aperçu de la série {0} du module de cartes de démarrage : {1}", - "关闭 Cookie 提示条失败": "Échec de la fermeture du bandeau de cookies", "关闭 WAA Worker": "Fermeture du Worker WAA", "解析页面 localStorage: %w": "Analyse du localStorage de page : {0}", "读取页面 localStorage: %w": "Lecture du localStorage de page : {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "Adresse du module gapi client manquante dans la page", "关闭重新载入前的页面失败": "Échec de la fermeture de la page d’avant le rechargement", "设置收缩模式: %w": "Définir le mode de compactage : {0}", - "预先打开页面失败": "Échec de l’ouverture anticipée d’une page" + "预先打开页面失败": "Échec de l’ouverture anticipée d’une page", + "重新生成": "Nouvelle génération", + "模型没有使用回复工具": "Le modèle n’a pas utilisé l’outil de réponse", + "结束原因 %s": "Motif de fin {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "Aucune donnée de l’amont pendant {0}, au-delà de REQUEST_TIMEOUT", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "Aucun premier événement de l’amont pendant {0}, au-delà de FIRST_EVENT_TIMEOUT", + "创建账户 Camoufox 指纹临时文件: %w": "Création du fichier temporaire d’empreinte Camoufox du compte : {0}", + "同步账户 Camoufox 指纹: %w": "Synchronisation de l’empreinte Camoufox du compte : {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "Fermeture du fichier temporaire d’empreinte Camoufox du compte : {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "Échec de la fermeture du nouvel onglet Camoufox ouvert avant le rechargement", + "账户备注不能超过 %d 个字符": "La note du compte ne peut pas dépasser {0} caractères", + "读取 AI Studio 账户权益: %w": "Lecture du forfait du compte AI Studio : {0}" } diff --git a/internal/i18n/messages/ja.json b/internal/i18n/messages/ja.json index 05a68ca3..83ab5ced 100644 --- a/internal/i18n/messages/ja.json +++ b/internal/i18n/messages/ja.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Drive 認証が未完了です。ポップアップが {0} で停止しています: {1}", "Drive 文件回收失败": "Drive ファイルの回収に失敗しました", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE は off、auto、または正の整数(秒)である必要があります", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT は off または正の整数(秒)である必要があります", "Gemini Live JSON 无效: %v": "Gemini Live JSON が無効です: {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken が HTTP {0} を返しました", "GenerateContent contents 不能为空": "GenerateContent の contents は空にできません", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS に含めることができるのは playground と build のみです", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS には playground または build の少なくとも一方を含める必要があります", "UPSTREAM_CHANNELS 通道 %s 重复": "UPSTREAM_CHANNELS チャネル {0} が重複しています", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE は off、traditional、または martian である必要があります", "Value 同时设置多个 oneof 字段": "Value に複数の oneof フィールドが同時に設定されています", "Value 缺少 oneof 字段": "Value に oneof フィールドがありません", "VirtualAllocEx 失败: %w": "VirtualAllocEx 失敗: {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "アカウント ディレクトリ {0} のスキャン: {1}", "找不到 Chrome Profile: %s": "Chrome Profile が見つかりません: {0}", "找不到 Chrome 账号: %s": "Chrome アカウントが見つかりません: {0}", - "找不到 chrome.exe": "chrome.exe が見つかりません", + "找不到官方 Google Chrome chrome.exe": "公式 Google Chrome の chrome.exe が見つかりません", + "创建隔离验证目录: %w": "隔離認証ディレクトリの作成: {0}", + "当前登录驱动不支持打开验证窗口": "現在のログインドライバーは認証ウィンドウを開くことに対応していません", + "核对账户验证状态": "アカウント認証状態を確認中", + "等待完成账户验证": "アカウント認証の完了を待機中", + "编码账户认证状态: %w": "アカウント認証状態のエンコード: {0}", + "解析账户 storage state: %w": "アカウント storage state の解析: {0}", + "解析验证状态: %w": "認証状態の解析: {0}", + "读取账户验证页面: %w": "アカウント認証ページの読み取り: {0}", + "账户核对完成": "アカウント確認が完了しました", + "账户没有可用于验证的 Cookie": "認証に使用できる Cookie がアカウントにありません", + "账户需要验证": "アカウントの認証が必要です", + "账户验证": "アカウント認証", + "账户验证失败": "アカウント認証に失敗しました", + "账户验证完成": "アカウント認証が完了しました", + "账户验证核对失败": "アカウント認証の確認に失敗しました", + "账户验证窗口已关闭,账户仍需要验证": "認証ウィンドウが閉じられました。アカウントは引き続き認証が必要です", "找不到选中的 Chrome 账号": "選択された Chrome アカウントが見つかりません", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "フィンガープリント ブラウザまたは Chromium のリモート デバッグ アドレス。Cookie を読み取ります", "排队等待": "順番待ち", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "Cookie バナーのスクリプトに API キーがありません", "api.js 缺少 gapi 模块配置": "api.js に gapi モジュールの設定がありません", "入门卡片模块系列 %s 的预览图: %w": "入門カード モジュールのシリーズ {0} のプレビュー画像: {1}", - "关闭 Cookie 提示条失败": "Cookie バナーを閉じられませんでした", "关闭 WAA Worker": "WAA Worker を終了", "解析页面 localStorage: %w": "ページ localStorage の解析: {0}", "读取页面 localStorage: %w": "ページ localStorage の読み込み: {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "ページに gapi client モジュールのアドレスがありません", "关闭重新载入前的页面失败": "再読み込み前のページを閉じられませんでした", "设置收缩模式: %w": "縮小モードの設定: {0}", - "预先打开页面失败": "ページの事前オープンに失敗しました" + "预先打开页面失败": "ページの事前オープンに失敗しました", + "重新生成": "再生成", + "模型没有使用回复工具": "モデルが返信ツールを使用しませんでした", + "结束原因 %s": "終了理由 {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "上流から {0} データが届かず、REQUEST_TIMEOUT を超えました", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "上流から {0} 最初のイベントが届かず、FIRST_EVENT_TIMEOUT を超えました", + "创建账户 Camoufox 指纹临时文件: %w": "アカウントの Camoufox フィンガープリント一時ファイルの作成: {0}", + "同步账户 Camoufox 指纹: %w": "アカウントの Camoufox フィンガープリントの同期: {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "アカウントの Camoufox フィンガープリント一時ファイルのクローズ: {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "再読み込み前に新しく開いた Camoufox タブを閉じられませんでした", + "账户备注不能超过 %d 个字符": "アカウントのメモは {0} 文字以内で入力してください", + "读取 AI Studio 账户权益: %w": "AI Studio アカウントのプラン読み取り: {0}" } diff --git a/internal/i18n/messages/ko.json b/internal/i18n/messages/ko.json index 79c059e5..b3a46220 100644 --- a/internal/i18n/messages/ko.json +++ b/internal/i18n/messages/ko.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Drive 승인이 완료되지 않았으며, 팝업이 {0}에 멈춰 있습니다: {1}", "Drive 文件回收失败": "Drive 파일 회수 실패", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE는 off, auto 또는 양의 정수(초)여야 합니다", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT은 off 또는 양의 정수(초)여야 합니다", "Gemini Live JSON 无效: %v": "Gemini Live JSON이 유효하지 않습니다: {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken에서 HTTP {0}을(를) 반환했습니다", "GenerateContent contents 不能为空": "GenerateContent contents는 비워 둘 수 없습니다", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS에는 playground와 build만 포함될 수 있습니다", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS는 적어도 playground 또는 build를 포함해야 합니다", "UPSTREAM_CHANNELS 通道 %s 重复": "UPSTREAM_CHANNELS 채널 {0} 중복", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE는 off, traditional 또는 martian이어야 합니다", "Value 同时设置多个 oneof 字段": "Value에 여러 oneof 필드가 동시에 설정됨", "Value 缺少 oneof 字段": "Value에 oneof 필드가 없습니다", "VirtualAllocEx 失败: %w": "VirtualAllocEx 실패: {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "계정 디렉터리 검사 {0}: {1}", "找不到 Chrome Profile: %s": "Chrome Profile을 찾을 수 없습니다: {0}", "找不到 Chrome 账号: %s": "Chrome 계정을 찾을 수 없습니다: {0}", - "找不到 chrome.exe": "chrome.exe를 찾을 수 없습니다", + "找不到官方 Google Chrome chrome.exe": "공식 Google Chrome의 chrome.exe를 찾을 수 없습니다", + "创建隔离验证目录: %w": "격리 인증 디렉터리 생성: {0}", + "当前登录驱动不支持打开验证窗口": "현재 로그인 드라이버는 인증 창 열기를 지원하지 않습니다", + "核对账户验证状态": "계정 인증 상태 확인 중", + "等待完成账户验证": "계정 인증 완료 대기 중", + "编码账户认证状态: %w": "계정 인증 상태 인코딩: {0}", + "解析账户 storage state: %w": "계정 storage state 파싱: {0}", + "解析验证状态: %w": "인증 상태 파싱: {0}", + "读取账户验证页面: %w": "계정 인증 페이지 읽기: {0}", + "账户核对完成": "계정 확인 완료", + "账户没有可用于验证的 Cookie": "인증에 사용할 수 있는 쿠키가 계정에 없습니다", + "账户需要验证": "계정 인증 필요", + "账户验证": "계정 인증", + "账户验证失败": "계정 인증 실패", + "账户验证完成": "계정 인증 완료", + "账户验证核对失败": "계정 인증 확인 실패", + "账户验证窗口已关闭,账户仍需要验证": "인증 창이 닫혔으며 계정은 여전히 인증이 필요합니다", "找不到选中的 Chrome 账号": "선택한 Chrome 계정을 찾을 수 없습니다", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "핑거프린트 브라우저 또는 Chromium의 원격 디버깅 주소에서 쿠키를 읽어옵니다", "排队等待": "대기 중", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "쿠키 배너 스크립트에 API 키가 없습니다", "api.js 缺少 gapi 模块配置": "api.js에 gapi 모듈 구성이 없습니다", "入门卡片模块系列 %s 的预览图: %w": "시작하기 카드 모듈 시리즈 {0}의 미리보기 이미지: {1}", - "关闭 Cookie 提示条失败": "쿠키 배너를 닫지 못했습니다", "关闭 WAA Worker": "WAA Worker 종료", "解析页面 localStorage: %w": "페이지 localStorage 파싱: {0}", "读取页面 localStorage: %w": "페이지 localStorage 읽기: {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "페이지에 gapi client 모듈 주소가 없습니다", "关闭重新载入前的页面失败": "다시 불러오기 전 페이지를 닫지 못했습니다", "设置收缩模式: %w": "축소 모드 설정: {0}", - "预先打开页面失败": "페이지를 미리 열지 못했습니다" + "预先打开页面失败": "페이지를 미리 열지 못했습니다", + "重新生成": "다시 생성", + "模型没有使用回复工具": "모델이 응답 도구를 사용하지 않았습니다", + "结束原因 %s": "종료 사유 {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "업스트림에서 {0} 동안 데이터가 없어 REQUEST_TIMEOUT을 초과했습니다", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "업스트림에서 {0} 동안 첫 이벤트가 없어 FIRST_EVENT_TIMEOUT을 초과했습니다", + "创建账户 Camoufox 指纹临时文件: %w": "계정 Camoufox 지문 임시 파일 생성: {0}", + "同步账户 Camoufox 指纹: %w": "계정 Camoufox 지문 동기화: {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "계정 Camoufox 지문 임시 파일 닫기: {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "다시 불러오기 전에 새로 연 Camoufox 탭을 닫지 못했습니다", + "账户备注不能超过 %d 个字符": "계정 메모는 {0}자를 초과할 수 없습니다", + "读取 AI Studio 账户权益: %w": "AI Studio 계정 등급 읽기: {0}" } diff --git a/internal/i18n/messages/zh-TW.json b/internal/i18n/messages/zh-TW.json index e4e3a096..11e38140 100644 --- a/internal/i18n/messages/zh-TW.json +++ b/internal/i18n/messages/zh-TW.json @@ -240,6 +240,7 @@ "Drive 授权未完成,弹窗停在 %s: %w": "Drive 授權未完成,彈出視窗停在 {0}: {1}", "Drive 文件回收失败": "Drive 檔案回收失敗", "FIRST_EVENT_HEDGE 必须是 off、auto 或正整数秒": "FIRST_EVENT_HEDGE 必須是 off、auto 或正整數秒", + "FIRST_EVENT_TIMEOUT 必须是 off 或正整数秒": "FIRST_EVENT_TIMEOUT 必須是 off 或正整數秒", "Gemini Live JSON 无效: %v": "Gemini Live JSON 無效: {0}", "GenerateAccessToken 返回 HTTP %d": "GenerateAccessToken 回傳 HTTP {0}", "GenerateContent contents 不能为空": "GenerateContent contents 不能為空", @@ -302,6 +303,7 @@ "UPSTREAM_CHANNELS 只能包含 playground 与 build": "UPSTREAM_CHANNELS 只能包含 playground 與 build", "UPSTREAM_CHANNELS 至少包含 playground 或 build": "UPSTREAM_CHANNELS 至少包含 playground 或 build", "UPSTREAM_CHANNELS 通道 %s 重复": "UPSTREAM_CHANNELS 通道 {0} 重複", + "USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian": "USER_MESSAGE_REWRITE 必須是 off、traditional 或 martian", "Value 同时设置多个 oneof 字段": "Value 同時設定多個 oneof 欄位", "Value 缺少 oneof 字段": "Value 缺少 oneof 欄位", "VirtualAllocEx 失败: %w": "VirtualAllocEx 失敗: {0}", @@ -733,7 +735,23 @@ "扫描账户目录 %q: %w": "掃描帳號目錄 {0}: {1}", "找不到 Chrome Profile: %s": "找不到 Chrome Profile: {0}", "找不到 Chrome 账号: %s": "找不到 Chrome 帳號: {0}", - "找不到 chrome.exe": "找不到 chrome.exe", + "找不到官方 Google Chrome chrome.exe": "找不到官方 Google Chrome chrome.exe", + "创建隔离验证目录: %w": "建立隔離驗證目錄: {0}", + "当前登录驱动不支持打开验证窗口": "目前登入驅動程式不支援開啟驗證視窗", + "核对账户验证状态": "確認帳號驗證狀態", + "等待完成账户验证": "等待完成帳號驗證", + "编码账户认证状态: %w": "編碼帳號驗證狀態: {0}", + "解析账户 storage state: %w": "解析帳號 storage state: {0}", + "解析验证状态: %w": "解析驗證狀態: {0}", + "读取账户验证页面: %w": "讀取帳號驗證頁面: {0}", + "账户核对完成": "帳號確認完成", + "账户没有可用于验证的 Cookie": "帳號沒有可用於驗證的 Cookie", + "账户需要验证": "帳號需要驗證", + "账户验证": "帳號驗證", + "账户验证失败": "帳號驗證失敗", + "账户验证完成": "帳號驗證完成", + "账户验证核对失败": "帳號驗證確認失敗", + "账户验证窗口已关闭,账户仍需要验证": "帳號驗證視窗已關閉,帳號仍需要驗證", "找不到选中的 Chrome 账号": "找不到選取的 Chrome 帳號", "指纹浏览器或 Chromium 的远程调试地址,读取其中的 Cookie": "指紋瀏覽器或 Chromium 的遠端偵錯位址,讀取其中的 Cookie", "排队等待": "排隊等待", @@ -1462,7 +1480,6 @@ "Cookie 提示条脚本缺少 API key": "Cookie 提示列指令碼缺少 API key", "api.js 缺少 gapi 模块配置": "api.js 缺少 gapi 模組設定", "入门卡片模块系列 %s 的预览图: %w": "入門卡片模組系列 {0} 的預覽圖: {1}", - "关闭 Cookie 提示条失败": "關閉 Cookie 提示列失敗", "关闭 WAA Worker": "關閉 WAA Worker", "解析页面 localStorage: %w": "解析頁面 localStorage: {0}", "读取页面 localStorage: %w": "讀取頁面 localStorage: {0}", @@ -1495,5 +1512,16 @@ "页面缺少 gapi client 模块地址": "頁面缺少 gapi client 模組位址", "关闭重新载入前的页面失败": "關閉重新載入前的頁面失敗", "设置收缩模式: %w": "設定收縮模式: {0}", - "预先打开页面失败": "預先開啟頁面失敗" + "预先打开页面失败": "預先開啟頁面失敗", + "重新生成": "重新生成", + "模型没有使用回复工具": "模型沒有使用回覆工具", + "结束原因 %s": "結束原因 {0}", + "上游连续 %s 没有数据,超过 REQUEST_TIMEOUT": "上游連續 {0} 沒有資料,超過 REQUEST_TIMEOUT", + "上游 %s 没有返回首个事件,超过 FIRST_EVENT_TIMEOUT": "上游 {0} 沒有傳回第一個事件,超過 FIRST_EVENT_TIMEOUT", + "创建账户 Camoufox 指纹临时文件: %w": "建立帳號 Camoufox 指紋暫存檔案: {0}", + "同步账户 Camoufox 指纹: %w": "同步帳號 Camoufox 指紋: {0}", + "关闭账户 Camoufox 指纹临时文件: %w": "關閉帳號 Camoufox 指紋暫存檔案: {0}", + "关闭重新载入前新开的 Camoufox 标签页失败": "關閉重新載入前新開的 Camoufox 分頁失敗", + "账户备注不能超过 %d 个字符": "帳號備註不能超過 {0} 個字元", + "读取 AI Studio 账户权益: %w": "讀取 AI Studio 帳號權益: {0}" } diff --git a/internal/pricing/pricing.go b/internal/pricing/pricing.go index 29cd4e40..efc63afe 100644 --- a/internal/pricing/pricing.go +++ b/internal/pricing/pricing.go @@ -1,48 +1,166 @@ -// Package pricing 按 Gemini API 与 Vertex AI 公布的当前文本单价估算请求费用 +// Package pricing 按 Gemini API 与 Vertex AI 公布的文本单价历史分段估算请求费用 package pricing +import ( + "slices" + "time" + _ "time/tzdata" +) + // LongContext 是长上下文分档的输入 token 界限,输入超过该值的请求按长上下文单价计费 const LongContext = 200_000 -// price 是一个模型每百万 token 的美元单价,cached 为缓存命中输入单价,long 前缀为长上下文分档单价,0 表示不分档 +// price 是一个模型在某一时段内每百万 token 的美元单价,from 为生效起始时刻(零值表示自始生效),cached 为缓存命中输入单价(0 表示无缓存单价并按输入单价计),long 前缀为长上下文分档单价(0 表示不分档) type price struct { + from time.Time input, cached, output float64 longInput, longCached, longOutput float64 } -// prices 是按 API 模型 ID 索引的文本生成单价,输出单价包含思考 token -var prices = map[string]price{ - "gemini-4-carbon": {input: 2, cached: 0.10, output: 10}, - "gemini-4-argon": {input: 2, cached: 0.10, output: 10}, - "gemini-4-hydrogen": {input: 1.50, cached: 0.075, output: 7.50}, - "gemini-3.8-flash": {input: 0.75, cached: 0.075, output: 3.75}, - "gemini-3.7-flash": {input: 0.75, cached: 0.075, output: 3.75}, - "gemini-3.6-flash": {input: 0.75, cached: 0.075, output: 3.75}, - "gemini-3.5-flash": {input: 1.50, cached: 0.15, output: 9}, - "gemini-3.5-flash-lite": {input: 0.30, cached: 0.03, output: 2.50}, - "gemini-3.1-pro-preview": {input: 2, cached: 0.20, output: 12, longInput: 4, longCached: 0.40, longOutput: 18}, - "gemini-3.1-pro-preview-customtools": {input: 2, cached: 0.20, output: 12, longInput: 4, longCached: 0.40, longOutput: 18}, - "gemini-3.1-flash-lite": {input: 0.25, cached: 0.025, output: 1.50}, - "gemini-3-flash-preview": {input: 0.50, cached: 0.05, output: 3}, - "gemini-2.5-pro": {input: 1.25, cached: 0.125, output: 10, longInput: 2.50, longCached: 0.25, longOutput: 15}, - "gemini-2.5-flash": {input: 0.30, cached: 0.03, output: 2.50}, - "gemini-2.5-flash-lite": {input: 0.10, cached: 0.01, output: 0.40}, - "gemini-robotics-er-2-preview": {input: 1, cached: 0.10, output: 5}, - "gemini-robotics-er-2-streaming-preview": {input: 1, cached: 0.10, output: 5}, - "gemini-decision-1": {input: 0.10}, +// pacificLocation 是官方价格页调价日期所用的美国太平洋时区 +var pacificLocation = func() *time.Location { + location, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + panic(err) + } + return location +}() + +// pacificDate 返回美国太平洋时间指定日期零点的 UTC 时刻 +func pacificDate(year int, month time.Month, day int) time.Time { + return time.Date(year, month, day, 0, 0, 0, 0, pacificLocation).UTC() +} + +var ( + dec2026 = pacificDate(2026, time.December, 1) + jan2027 = pacificDate(2027, time.January, 1) +) + +// prices 是按 API 模型 ID 索引的文本生成单价历史分段,每项按生效时间升序排列,输出单价包含思考 token +var prices = map[string][]price{ + "gemini-4-carbon": { + {input: 2, cached: 0.10, output: 10}, + {from: dec2026, input: 4, cached: 0.20, output: 20}, + }, + "gemini-4-argon": { + {input: 2, cached: 0.10, output: 10}, + {from: dec2026, input: 4, cached: 0.20, output: 20}, + }, + "gemini-4-neon": { + {input: 3, cached: 0.15, output: 15}, + }, + "gemini-4-hydrogen": { + {input: 1.50, cached: 0.075, output: 7.50}, + }, + "gemini-3.8-flash": { + {input: 0.75, cached: 0.075, output: 3.75}, + {from: jan2027, input: 1.50, cached: 0.15, output: 7.50}, + }, + "gemini-3.7-flash": { + {input: 0.75, cached: 0.075, output: 3.75}, + }, + "gemini-3.6-flash": { + {input: 0.75, cached: 0.075, output: 3.75}, + {from: jan2027, input: 1.50, cached: 0.15, output: 7.50}, + }, + "gemini-3.5-flash": { + {input: 1.50, cached: 0.15, output: 9}, + }, + "gemini-3.5-flash-lite": { + {input: 0.30, cached: 0.03, output: 2.50}, + }, + "gemini-3.1-pro-preview": { + {input: 2, cached: 0.20, output: 12, longInput: 4, longCached: 0.40, longOutput: 18}, + }, + "gemini-3.1-pro-preview-customtools": { + {input: 2, cached: 0.20, output: 12, longInput: 4, longCached: 0.40, longOutput: 18}, + }, + "gemini-3.1-flash-lite": { + {input: 0.25, cached: 0.025, output: 1.50}, + }, + "gemini-3-flash-preview": { + {input: 0.50, cached: 0.05, output: 3}, + }, + "gemini-2.5-pro": { + {input: 1.25, cached: 0.125, output: 10, longInput: 2.50, longCached: 0.25, longOutput: 15}, + }, + "gemini-2.5-flash": { + {input: 0.30, cached: 0.03, output: 2.50}, + }, + "gemini-2.5-flash-lite": { + {input: 0.10, cached: 0.01, output: 0.40}, + }, + "gemini-robotics-er-2-preview": { + {input: 1, cached: 0.10, output: 5}, + {from: jan2027, input: 2, cached: 0.20, output: 10}, + }, + "gemini-robotics-er-2-streaming-preview": { + {input: 1, output: 5}, + {from: jan2027, input: 2, output: 10}, + }, + "gemini-decision-1": { + {input: 0.10}, + }, +} + +// boundaries 是全部模型单价分段切换时刻的升序去重列表 +var boundaries = collectBoundaries() + +// collectBoundaries 收集单价表中全部非零的生效起始时刻并按升序去重 +func collectBoundaries() []time.Time { + var result []time.Time + for _, entries := range prices { + for _, entry := range entries { + if !entry.from.IsZero() { + result = append(result, entry.from) + } + } + } + slices.SortFunc(result, time.Time.Compare) + return slices.CompactFunc(result, time.Time.Equal) +} + +// priceAt 返回在 at 时刻生效的价格段 +func priceAt(entries []price, at time.Time) price { + selected := entries[0] + for _, entry := range entries[1:] { + if at.Before(entry.from) { + break + } + selected = entry + } + return selected +} + +// Boundaries 返回严格落在开区间 (from, to) 内的全部单价切换时刻,按时间升序排列 +func Boundaries(from, to time.Time) []time.Time { + var result []time.Time + for _, at := range boundaries { + if at.After(from) && at.Before(to) { + result = append(result, at) + } + } + return result } // Priced 返回模型是否有单价 func Priced(model string) bool { - _, ok := prices[model] - return ok + return len(prices[model]) > 0 } -// TierCost 返回一组同模型同分档请求的美元费用,long 表示这些请求的输入都超过 LongContext,token 为各请求之和,cached 为 input 中命中缓存的部分,output 为思考与回复 token 之和,模型没有单价时为 0 -func TierCost(model string, long bool, input, cached, output int64) float64 { - value := prices[model] +// TierCost 返回一组同模型同分档请求在 at 时刻的美元费用,long 表示这些请求的输入都超过 LongContext,token 为各请求之和,cached 为 input 中命中缓存的部分,output 为思考与回复 token 之和,模型没有单价时为 0 +func TierCost(model string, at time.Time, long bool, input, cached, output int64) float64 { + entries := prices[model] + if len(entries) == 0 { + return 0 + } + value := priceAt(entries, at) if value.longInput > 0 && long { value.input, value.cached, value.output = value.longInput, value.longCached, value.longOutput } - return (float64(input-cached)*value.input + float64(cached)*value.cached + float64(output)*value.output) / 1e6 + cachedRate := value.cached + if cachedRate == 0 { + cachedRate = value.input + } + return (float64(input-cached)*value.input + float64(cached)*cachedRate + float64(output)*value.output) / 1e6 } diff --git a/internal/pricing/pricing_test.go b/internal/pricing/pricing_test.go new file mode 100644 index 00000000..4b0bf2d7 --- /dev/null +++ b/internal/pricing/pricing_test.go @@ -0,0 +1,54 @@ +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/usage.go b/internal/requestdb/usage.go index e1626b80..63c2b1a5 100644 --- a/internal/requestdb/usage.go +++ b/internal/requestdb/usage.go @@ -367,46 +367,71 @@ type cost struct { unpriced map[string]bool } -// scanCost 在 SQL 中按分桶、模型与长上下文分档汇总 [from, to) 内符合筛选的原始记录 token,再按单价累加费用,starts 非空时同时累加到各分桶 +// scanCost 在 SQL 中按分桶、单价分段、模型与长上下文分档汇总 [from, to) 内符合筛选的原始记录 token,再按单价累加费用,starts 非空时同时累加到各分桶 func (store *Store) scanCost(ctx context.Context, from, to int64, starts []int64, filters api.UsageFilters) (cost, error) { clause, filterArgs := filterSQL(filters) + boundaries := pricing.Boundaries(time.UnixMilli(from), time.UnixMilli(to)) + cuts := make([]int64, len(boundaries)) + for index, at := range boundaries { + cuts[index] = at.UnixMilli() + } var slots strings.Builder var args []any + addSlot := func(index int, start, stop int64) { + if len(args) > 0 { + slots.WriteByte(',') + } + slots.WriteString("(?,?,?)") + args = append(args, index, start, stop) + } for index := range max(len(starts), 1) { start, stop := from, to if starts != nil { start = max(starts[index], from) if index+1 < len(starts) { - stop = starts[index+1] + stop = min(starts[index+1], to) } } - if index > 0 { - slots.WriteByte(',') + if start >= stop { + continue } - slots.WriteString("(?,?,?)") - args = append(args, index, start, stop) + for _, cut := range cuts { + if cut <= start { + continue + } + if cut >= stop { + break + } + addSlot(index, start, cut) + start = cut + } + addSlot(index, start, stop) + } + result := cost{buckets: make([]float64, len(starts)), unpriced: map[string]bool{}} + if len(args) == 0 { + return result, nil } tier := "input_tokens > " + strconv.Itoa(pricing.LongContext) rows, err := store.db.QueryContext(ctx, `WITH slots(slot, start, stop) AS (VALUES `+slots.String()+`) - SELECT slot, model, `+tier+`, SUM(input_tokens), SUM(cached_tokens), SUM(reasoning_tokens + reply_tokens) + SELECT slot, start, model, `+tier+`, SUM(input_tokens), SUM(cached_tokens), SUM(reasoning_tokens + reply_tokens) FROM slots JOIN requests INDEXED BY requests_cost ON time >= start AND time < stop`+clause+` - GROUP BY slot, model, `+tier, append(args, filterArgs...)...) + GROUP BY slot, start, model, `+tier, append(args, filterArgs...)...) if err != nil { return cost{}, err } - result := cost{buckets: make([]float64, len(starts)), unpriced: map[string]bool{}} var slot int + var start int64 var long bool var input, cached, output int64 var model string for rows.Next() { - if err := rows.Scan(&slot, &model, &long, &input, &cached, &output); err != nil { + if err := rows.Scan(&slot, &start, &model, &long, &input, &cached, &output); err != nil { return cost{}, errors.Join(err, rows.Close()) } if input+output > 0 && !pricing.Priced(model) { result.unpriced[model] = true } - value := pricing.TierCost(model, long, input, cached, output) + value := pricing.TierCost(model, time.UnixMilli(start), long, input, cached, output) result.total += value if starts != nil { result.buckets[slot] += value diff --git a/internal/setup/setup.go b/internal/setup/setup.go index 7f8aa3ad..aa8921c8 100644 --- a/internal/setup/setup.go +++ b/internal/setup/setup.go @@ -179,7 +179,7 @@ func (target *remoteTarget) Save( state.SetAuthExtension(extension) } input := api.AccountStateInput{ - Label: accountConfig.Label, Locale: accountConfig.Locale, Timezone: accountConfig.Timezone, + Label: accountConfig.Label, Note: accountConfig.Note, Locale: accountConfig.Locale, Timezone: accountConfig.Timezone, AuthUser: accountConfig.AuthUser, StorageState: state, } if fingerprintDirectory != "" { @@ -258,6 +258,9 @@ func remoteOrigin(raw string) (string, error) { return parsed.Scheme + "://" + parsed.Host, nil } +// verifyAuthUser 识别 Cookie 登录 AI Studio 的账户 +var verifyAuthUser = chromeauth.VerifyAuthUser + func importStorageState(ctx context.Context, target accountTarget, options setupOptions) error { state, err := aistudio.LoadStorageState(options.storageState) if err != nil { @@ -266,11 +269,18 @@ func importStorageState(ctx context.Context, target accountTarget, options setup if _, err := aistudio.NewSigner().Authorization(state); err != nil { return fmt.Errorf("认证状态无法用于 AI Studio: %w", err) } - label := defaultSetupLabel(options.storageState) + label := "" if extension, exists, err := state.AuthExtension(); err != nil { return err } else if exists && strings.TrimSpace(extension.Source.Email) != "" { - label = extension.Source.Email + label = strings.ToLower(strings.TrimSpace(extension.Source.Email)) + } + if label == "" { + verification, err := verifyAuthUser(ctx, &state, options.egress, options.authUser) + if err != nil { + return fmt.Errorf("识别 Cookie 登录的账户: %w", err) + } + label = strings.ToLower(strings.TrimSpace(verification.Email)) } saved, err := target.Save(ctx, setupAccountConfig(label, options), state, "") if err != nil { @@ -301,7 +311,7 @@ func importCookies(ctx context.Context, target accountTarget, options setupOptio email = options.emails[0] } if email == "" || options.authUserSet { - verification, err := chromeauth.VerifyAuthUser(ctx, &state, options.egress, options.authUser) + verification, err := verifyAuthUser(ctx, &state, options.egress, options.authUser) if err != nil { return fmt.Errorf("识别 Cookie 登录的账户: %w", err) } @@ -408,7 +418,9 @@ func importChromeResult(ctx context.Context, cfg config.Config, target accountTa } saving.Lock() defer saving.Unlock() - if _, err := target.Save(ctx, setupAccountConfig(result.Email, options), result.State, ""); err != nil { + accountConfig := setupAccountConfig(result.Email, options) + accountConfig.Note = aistudio.TruncateAccountNote(result.DisplayName) + if _, err := target.Save(ctx, accountConfig, result.State, ""); err != nil { return err } fmt.Fprintf(output, "已导入: %s (%s),%d 个模型\n", result.Email, result.Profile, verification.ModelCount) @@ -590,14 +602,6 @@ func setupAccountConfig(label string, options setupOptions) aistudio.AccountConf return accountConfig } -func defaultSetupLabel(storageState string) string { - parent := filepath.Base(filepath.Dir(storageState)) - if parent == "." || parent == string(filepath.Separator) { - return "Default" - } - return parent -} - func defaultSetupLoginDriver(ctx context.Context, egress string) (aistudio.IsolatedLoginDriver, error) { camoufoxPath, err := camoufoxnative.FindExecutable(ctx, egress) if err != nil { diff --git a/internal/statedb/statedb.go b/internal/statedb/statedb.go index 0974699f..01d5fa0e 100644 --- a/internal/statedb/statedb.go +++ b/internal/statedb/statedb.go @@ -88,10 +88,12 @@ func (s *Store) Read(id string) ([]byte, bool) { } // Save 在一个事务中写入节点并删除已移除的节点,已有节点保留原保存顺序 -func (s *Store) Save(saved []api.SavedState, removed []string) { +func (s *Store) Save(saved []api.SavedState, removed []string) error { if err := s.save(saved, removed); err != nil { s.log("WARN", "保存续接状态失败", "error", err) + return err } + return nil } func (s *Store) save(saved []api.SavedState, removed []string) error { diff --git a/web/src/App.vue b/web/src/App.vue index 004cce4c..30c36d7d 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -507,6 +507,8 @@ onMounted(revealCurrentTab) :error="errors.accounts" :chrome-import="status?.chrome_import ?? false" :camoufox="status?.camoufox" + :models="models" + :cooldowns="cooldowns" @refresh="loadAccountData" @updated="updateAccount" @notice="showNotice" diff --git a/web/src/access/capabilities.ts b/web/src/access/capabilities.ts index 2a6d8f2b..c93537b9 100644 --- a/web/src/access/capabilities.ts +++ b/web/src/access/capabilities.ts @@ -238,7 +238,6 @@ export const capabilities: Capability[] = [ baseURL: input.origin, prompt: 'A drone flying over a forest at sunrise', settings: { ...defaultSettings(input.model), model: input.modelID }, - references: [], aspectRatios: options.video_aspect_ratios ?? [], durations: (options.video_durations_seconds ?? []).map(Number), resolutions: options.video_output_resolutions ?? [], diff --git a/web/src/access/clients.ts b/web/src/access/clients.ts index b9209331..074d2f23 100644 --- a/web/src/access/clients.ts +++ b/web/src/access/clients.ts @@ -29,13 +29,13 @@ export const protocolNames: Record = { gemini: 'Gemini API', } -// ClientInput 是生成客户端配置所需的服务地址、API key、所选模型、Claude Code 三档模型、全部对话模型、实时目录、终端、接入协议与界面文案 +// ClientInput 是生成客户端配置所需的服务地址、API key、所选模型、Claude Code 四档模型、全部对话模型、实时目录、终端、接入协议与界面文案 export interface ClientInput { origin: string key: string model: Model | undefined modelID: string - tiers: { opus: string; sonnet: string; haiku: string } + tiers: { fable: string; opus: string; sonnet: string; haiku: string } models: Model[] catalog: Model[] shell: Shell @@ -242,12 +242,13 @@ function cherryHost(input: ClientInput): string { : input.origin } -// claudeVariables 是 Claude Code 使用的环境变量:Anthropic 地址、key、主模型、opus、sonnet、haiku 三档模型与主模型的上下文窗口 +// claudeVariables 是 Claude Code 使用的环境变量:Anthropic 地址、key、主模型、fable、opus、sonnet、haiku 四档模型与主模型的上下文窗口 function claudeVariables(input: ClientInput): [string, string][] { return [ ['ANTHROPIC_BASE_URL', input.origin], ['ANTHROPIC_AUTH_TOKEN', input.key], ['ANTHROPIC_MODEL', input.modelID], + ['ANTHROPIC_DEFAULT_FABLE_MODEL', input.tiers.fable], ['ANTHROPIC_DEFAULT_OPUS_MODEL', input.tiers.opus], ['ANTHROPIC_DEFAULT_SONNET_MODEL', input.tiers.sonnet], ['ANTHROPIC_DEFAULT_HAIKU_MODEL', input.tiers.haiku], diff --git a/web/src/api.ts b/web/src/api.ts index 73d28cec..ad99cecd 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -9,6 +9,7 @@ import type { AccountTask, AdminEvent, ChromeImportInput, + ChromeProfileTier, CookieAccountsInput, CookieBrowser, CookieImportInput, @@ -159,6 +160,36 @@ export const api = { ).task, chromeImportProfiles: async () => (await requestJSON('/api/accounts/import/chrome')).profiles, + checkChromeImportTiers: async ( + accountIDs: string[], + proxy: string, + onResult: (item: ChromeProfileTier) => void, + signal?: AbortSignal, + ): Promise => { + const response = await send('/api/accounts/import/chrome/tiers', { + method: 'POST', + body: jsonBody({ account_ids: accountIDs, proxy }), + signal: signal ?? null, + }) + const reader = response.body?.getReader() + if (!reader) return + const decoder = new TextDecoder() + let buffer = '' + for (;;) { + const { value, done } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + for (;;) { + const newline = buffer.indexOf('\n') + if (newline < 0) break + const line = buffer.slice(0, newline).trim() + buffer = buffer.slice(newline + 1) + if (line !== '') onResult(JSON.parse(line) as ChromeProfileTier) + } + } + const tail = (buffer + decoder.decode()).trim() + if (tail !== '') onResult(JSON.parse(tail) as ChromeProfileTier) + }, importChromeAccounts: async (input: ChromeImportInput) => ( await requestJSON('/api/accounts/import/chrome', { @@ -210,6 +241,13 @@ export const api = { body: jsonBody({ view }), }) ).task, + verifyAccount: async (id: string, view: string) => + ( + await requestJSON(`/api/accounts/${encodeURIComponent(id)}/verify`, { + method: 'POST', + body: jsonBody({ view }), + }) + ).task, loginViewURL: (view: string) => `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/api/login-view/${encodeURIComponent(view)}`, paths: (path: string) => requestJSON(`/api/paths?path=${encodeURIComponent(path)}`), @@ -221,6 +259,13 @@ export const api = { requestJSON(`/api/accounts/${encodeURIComponent(id)}/refresh`, { method: 'POST', }), + refreshAccounts: async (ids: string[]) => + ( + await requestJSON('/api/accounts/refresh', { + method: 'POST', + body: jsonBody({ ids }), + }) + ).task, startService: () => requestJSON('/api/control/start', { method: 'POST' }), stopService: () => requestJSON('/api/control/stop', { method: 'POST' }), downloadCamoufox: () => requestJSON('/api/camoufox/download', { method: 'POST' }), diff --git a/web/src/camoufox.ts b/web/src/camoufox.ts index f36ba1d3..ea36cf80 100644 --- a/web/src/camoufox.ts +++ b/web/src/camoufox.ts @@ -2,14 +2,14 @@ import { computed, type ComputedRef } from 'vue' import { useI18n } from '@/i18n' import type { AccountTask, PreparationStatus } from '@/types' -// waitsForCamoufox 判断浏览器登录或重新登录任务是否正在等待 Camoufox 下载或解压 +// waitsForCamoufox 判断浏览器登录、重新登录或账户验证任务是否正在等待 Camoufox 下载或解压 export function waitsForCamoufox( task: AccountTask, camoufox: PreparationStatus | undefined, ): boolean { return ( task.state === 'running' && - (task.kind === 'login' || task.kind === 'relogin') && + (task.kind === 'login' || task.kind === 'relogin' || task.kind === 'verify') && camoufox?.preparing === true ) } diff --git a/web/src/components/AccessPanel.vue b/web/src/components/AccessPanel.vue index 8a6ad0ff..916187ec 100644 --- a/web/src/components/AccessPanel.vue +++ b/web/src/components/AccessPanel.vue @@ -237,12 +237,12 @@ const clientGroups = computed(() => })), ) const clientModel = ref('') -const tiers = reactive({ opus: '', sonnet: '', haiku: '' }) +const tiers = reactive({ fable: '', opus: '', sonnet: '', haiku: '' }) watch( chatModels, (list) => { clientModel.value = keepModel(clientModel.value, list) - for (const tier of ['opus', 'sonnet', 'haiku'] as const) + for (const tier of ['fable', 'opus', 'sonnet', 'haiku'] as const) tiers[tier] = list.some((model) => model.id === tiers[tier]) ? tiers[tier] : clientModel.value }, { immediate: true }, @@ -256,8 +256,9 @@ const clientProtocol = computed({ selectedProtocols[client.value.id] = value }, }) -// tierLabels 是 Claude Code 三档模型的选择框名称 +// tierLabels 是 Claude Code 四档模型的选择框名称 const tierLabels: { tier: keyof typeof tiers; label: TranslationKey }[] = [ + { tier: 'fable', label: 'access.tierFable' }, { tier: 'opus', label: 'access.tierOpus' }, { tier: 'sonnet', label: 'access.tierSonnet' }, { tier: 'haiku', label: 'access.tierHaiku' }, @@ -269,6 +270,7 @@ const clientInput = computed(() => ({ model: chatModels.value.find((model) => model.id === clientModel.value), modelID: clientModel.value || modelPlaceholder, tiers: { + fable: tiers.fable || modelPlaceholder, opus: tiers.opus || modelPlaceholder, sonnet: tiers.sonnet || modelPlaceholder, haiku: tiers.haiku || modelPlaceholder, diff --git a/web/src/components/AccountModelsDialog.vue b/web/src/components/AccountModelsDialog.vue index 77a80e31..2554a7f3 100644 --- a/web/src/components/AccountModelsDialog.vue +++ b/web/src/components/AccountModelsDialog.vue @@ -9,34 +9,217 @@ import { DialogRoot, DialogTitle, } from 'reka-ui' -import { useI18n } from '@/i18n' +import { splitReason } from '@/cooldowns' +import { useI18n, type TranslationKey } from '@/i18n' +import { + capabilityNames, + categoryLabels, + categoryOrder, + modelBadges, + modelFamily, + outputLimit, + tokenLimit, +} from '@/playground/catalog' +import type { Account, Cooldown, Model } from '@/types' +import CopyButton from './CopyButton.vue' import UiIcon from './UiIcon.vue' const props = defineProps<{ - // account 是要查看模型的账户邮箱,为空时对话框关闭 - account: string - models: string[] + // account 是要查看模型的账户,为空时对话框关闭 + account: Account | undefined + // catalog 是服务的实时模型目录,提供账户各模型的名称、上限与能力 + catalog: Model[] + cooldowns: Cooldown[] // trigger 是打开对话框的按钮,关闭后焦点回到这里 trigger: HTMLElement | null }>() const emit = defineEmits<{ close: [] }>() -const { t } = useI18n() +const { t, locale, logText } = useI18n() const query = ref('') const search = useTemplateRef('search') +// selectedID 是右侧显示详情的模型 +const selectedID = ref('') +// detailOpen 是窄屏下是否显示详情,宽屏下列表与详情并排 +const detailOpen = ref(false) + +// AccountModel 是账户的一个模型:目录中的模型信息、所属产品分类与该账户在这个模型上最晚结束的冷却 +interface AccountModel { + id: string + model: Model | undefined + family: number | undefined + cooldown: Cooldown | undefined +} + +// badgeLabels 是官网模型标记的文案 +const badgeLabels: Record<'Confidential' | 'New' | 'Paid', TranslationKey> = { + Confidential: 'pg.badgeConfidential', + New: 'pg.badgeNew', + Paid: 'pg.badgePaid', +} + +// entries 是账户的全部模型,顺序与账户目录相同 +const entries = computed(() => { + const account = props.account + if (account === undefined) return [] + const models = new Map(props.catalog.map((model) => [model.id, model])) + const latest = new Map() + for (const cooldown of props.cooldowns) { + if (cooldown.account_id !== account.id) continue + const current = latest.get(cooldown.model_id) + if (current === undefined || Date.parse(cooldown.until) > Date.parse(current.until)) + latest.set(cooldown.model_id, cooldown) + } + return account.models.map((id) => { + const model = models.get(id) + return { + id, + model, + family: model && modelFamily(model), + cooldown: latest.get(id), + } + }) +}) + +// familyName 返回产品分类的名称,不属于任何产品分类的模型归入其他 +function familyName(family: number | undefined): string { + return family === undefined ? t('accounts.modelsOther') : t(categoryLabels[family]!) +} + +// groups 是按产品分类分组的搜索结果,模型 ID、名称或分类名包含搜索词即命中,不区分大小写 +const groups = computed(() => { + const needle = query.value.trim().toLowerCase() + const families = new Map() + for (const entry of entries.value) { + const text = [entry.id, entry.model?.name ?? '', familyName(entry.family)].join('\n') + if (!text.toLowerCase().includes(needle)) continue + const items = families.get(entry.family) + if (items) items.push(entry) + else families.set(entry.family, [entry]) + } + // rank 是分类在模型选择面板中的位置,其他排在最后 + const rank = (family: number | undefined) => + family === undefined ? Infinity : categoryOrder.indexOf(family) + return [...families.entries()] + .sort(([left], [right]) => rank(left) - rank(right)) + .map(([family, items]) => ({ name: familyName(family), items })) +}) + +// cooling 是账户上正在冷却的模型数 +const cooling = computed(() => entries.value.filter((entry) => entry.cooldown).length) + +// selected 是显示详情的模型,所选模型被搜索滤掉时为结果中的第一个 +const selected = computed(() => { + const visible = groups.value.flatMap((group) => group.items) + return visible.find((entry) => entry.id === selectedID.value) ?? visible[0] +}) watch( - () => props.account, - () => (query.value = ''), + () => props.account?.id, + () => { + query.value = '' + selectedID.value = '' + detailOpen.value = false + }, ) -// matches 是模型 ID 包含搜索词的模型,不区分大小写 -const matches = computed(() => { - const needle = query.value.trim().toLowerCase() - return props.models.filter((model) => model.toLowerCase().includes(needle)) +// choose 显示一个模型的详情 +function choose(entry: AccountModel): void { + selectedID.value = entry.id + detailOpen.value = true +} + +// summary 是对话框标题下的一行:模型数、账户权益与冷却中的模型数 +const summary = computed(() => { + const account = props.account + if (account === undefined) return '' + const count = account.models.length + return [ + count === 1 ? t('models.countOne') : t('models.count').replace('{count}', String(count)), + account.benefit_tier === 'Unknown' ? t('accounts.tierUnknown') : account.benefit_tier, + ...(cooling.value + ? [t('accounts.modelsCooling').replace('{count}', String(cooling.value))] + : []), + ].join(' · ') +}) + +// facts 是详情中的上限与日期 +const facts = computed(() => { + const model = selected.value?.model + const details = model?.details + return [ + { label: t('models.context'), value: tokenLimit(model?.input_token_limit, locale.value) }, + { label: t('models.output'), value: tokenLimit(outputLimit(model), locale.value) }, + ...(details?.release_date + ? [ + { + label: t('models.releaseDate'), + value: new Intl.DateTimeFormat(locale.value, { dateStyle: 'medium' }).format( + details.release_date * 1000, + ), + }, + ] + : []), + ...(details?.knowledge_cutoff + ? [ + { + label: t('models.knowledgeCutoff'), + value: new Intl.DateTimeFormat(locale.value, { + year: 'numeric', + month: 'short', + }).format(details.knowledge_cutoff * 1000), + }, + ] + : []), + ] +}) + +// description 是官网模型卡片的简介,没有简介时为与名称不同的目录描述 +const description = computed(() => { + const model = selected.value?.model + if (model === undefined) return '' + if (model.details?.summary) return model.details.summary + return model.description !== model.name ? (model.description ?? '') : '' }) -// listHeight 是模型列表的固定高度,按全部模型的行数计算并以 24rem 与 55vh 为上限,搜索时对话框大小不变 -const listHeight = computed(() => `min(${props.models.length * 1.75}rem, 24rem, 55vh)`) +// badges 与 capabilities 是所选模型的官网标记与能力名称 +const badges = computed(() => + selected.value?.model ? modelBadges(selected.value.model, 'All') : [], +) +const capabilities = computed(() => + selected.value?.model ? capabilityNames(selected.value.model, t) : [], +) + +// reason 是所选模型当前冷却的上游错误原文 +const reason = computed(() => splitReason(selected.value?.cooldown?.reason).text) + +// cooldownCategory 返回冷却类型的界面文字 +function cooldownCategory(cooldown: Cooldown): string { + const category = splitReason(cooldown.reason).category + return category ? logText(category) : t('cooldowns.other') +} + +// untilText 返回冷却结束的本地时刻与距今的相对时间 +function untilText(cooldown: Cooldown): string { + const until = Date.parse(cooldown.until) + const seconds = Math.max(1, Math.round((until - Date.now()) / 1000)) + const [value, unit] = + seconds < 3600 + ? [Math.ceil(seconds / 60), 'minute' as const] + : seconds < 86_400 + ? [Math.round(seconds / 3600), 'hour' as const] + : [Math.round(seconds / 86_400), 'day' as const] + const relative = new Intl.RelativeTimeFormat(locale.value, { numeric: 'auto' }).format( + value, + unit, + ) + const time = new Intl.DateTimeFormat(locale.value, { + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(until) + return `${time} · ${relative}` +} // restoreFocus 在对话框关闭后把焦点放回打开它的按钮 function restoreFocus(event: Event): void { @@ -46,25 +229,24 @@ function restoreFocus(event: Event): void {