diff --git a/.env.example b/.env.example
index 9678c4d5..64463fca 100644
--- a/.env.example
+++ b/.env.example
@@ -96,6 +96,9 @@ BUILD_NATIVE_NONSTREAM=true
# 提供 -build 对话模型;用过 -build 模型的账户曾被 Google 成批限制使用 AI Studio,关闭时这些模型不出现在 /v1/models,请求时返回已在设置中关闭的错误,保存后立即生效
BUILD_CHAT_MODELS=true
+# -build 对话模型的上游协议:auto(默认,按账户页面启动数据标志 45831005 自动选择)、agency(新版 StreamRunAgentTask)或 legacy(旧版 CodeAssistantOffline),保存后下一次请求生效
+BUILD_CHAT_PROTOCOL=auto
+
# 非流式请求等待超过 10 秒时先返回 200,之后每 10 秒写出一个换行,经反向代理时连接不会因长时间无数据断开
NONSTREAM_KEEPALIVE=true
diff --git a/README.md b/README.md
index 5b25f0a7..950973bd 100644
--- a/README.md
+++ b/README.md
@@ -91,7 +91,7 @@
- **智能模型切换**: 从 AI Studio 实时发现模型并按 `model` 字段路由;开启 `DISCOVER_HIDDEN_MODELS` 后,AI Studio 官网尚未公开的模型在确认账户能用后也会加入模型列表;在“模型目录”中可逐个选择模型是否在 API 中显示
- **Google 工具**: 支持 Search、Image Search、URL Context、Code Execution 和 Maps
- **Files 与 Transcribe**: 支持文件上传、查询、内容读取、删除和音频转录
-- **Live 与 Robotics**: 通过 WebSocket 支持文本、音频、JPEG、媒体结束、工具调用、恢复和中断
+- **Live 与 Robotics**: 通过 WebSocket 支持文本、音频、JPEG、媒体结束、工具调用、恢复和中断;Google Gen AI SDK 的 Live 客户端可直接连接
- **反指纹检测**: 为每个账户固定 Firefox 指纹与出口,官方 WAA 在 SpiderMonkey 的 Firefox 页面环境或 Camoufox 页面中运行
- **图形界面启动器**: 通过网页管理账户、服务启停、实时日志、模型、请求、用量统计(用过多把 API key 时可按 key 拆分)、按模型与账户查看的号池额度和配置,界面提供深色与浅色两种配色,以及简体中文、繁體中文、English、日本語、한국어、Français 与 Deutsch 七种语言
- **桌面版**: Windows、macOS 与 Linux 桌面应用在窗口中显示管理页面,关闭窗口后在系统托盘继续运行
@@ -428,6 +428,7 @@ agy
| 视频 | `POST /v1/videos`、`GET /v1/videos`、`GET`/`DELETE /v1/videos/{id}`、`GET /v1/videos/{id}/content` |
| Gemini 视频 | `POST /v1beta/models/{model}:predictLongRunning`、`GET /v1beta/operations/{id}` |
| Live(含实时翻译、实时转录与实时音乐)/ Robotics | `GET /v1/live`、`GET /v1/robotics/stream` |
+| Gemini Live(Google Gen AI SDK) | `GET /ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`,`v1alpha` 与 `v1` 同样可用 |
Gemini 的 `/v1beta` 路径在 `/v1` 下同样可用,Google Gen AI SDK 3.x 默认使用 `/v1`。`/v1/models` 与 `/v1/files` 的请求带 `x-goog-api-key` 请求头或 `key` 参数且不带 `Authorization` 时按 Gemini 格式返回,其余按 OpenAI 格式返回。
@@ -506,7 +507,7 @@ curl http://127.0.0.1:2048/v1beta/models/gemini-2.5-flash-preview-tts:generateCo
- 可用语音由实时模型目录中的 `capability_options.voices` 返回
- `gemini-3.8-flash-tts` 等带 `speech_metadata` 能力的模型同样接受上面的 `说话人: 台词` 写法,也可以为每个文本 part 设置 `speechMetadata.speaker` 与 `speechMetadata.style`,并用 `multiSpeakerVoiceConfig.mode` 选择 `VERBATIM` 或 `CONVERSATIONAL`
- OpenAI `instructions` 在这些模型上作为语音风格
-- 自定义声音(Voice Design):`POST /v1beta/voices` 以 `{"voice":{"type":"prompted","display_name":"Old Sailor","prompted":{"input":"<声音描述>"}}}` 创建,返回 `voice_...` ID 与试听音频,之后在任一协议的声音参数中填这个 ID;服务按描述挑选最接近的预置音色,生成时把描述作为风格提示。API 试用页的语音页「新建声音」提供同样的流程
+- 自定义声音(Voice Design):`POST /v1beta/voices` 以 `{"voice":{"type":"prompted","display_name":"Old Sailor","prompted":{"input":"<声音描述>"}}}` 创建,返回 `voice_...` ID 与试听音频,之后在任一协议的声音参数中填这个 ID;服务按描述挑选最接近的预置音色,生成时把描述作为风格提示。API 试用页的语音页「新建声音」提供同样的流程,并提供改写描述、以已有声音为基础改编(Remix)与录音复刻(Voice Replication)
### 图片生成 (Nano Banana)
@@ -598,9 +599,9 @@ curl http://127.0.0.1:2048/v1beta/decisions \
| `gemini-3.8-live` | Gemini 3.8 Live | 实时对话 | 131072 | 65536 |
| `gemini-3.5-live-translate-preview` | Gemini 3.5 Live Translate Preview | 实时翻译 | 16384 | 32768 |
-目录中另有 `-latest` 别名、Robotics-ER、Gemini 3 系列与早期版本的图片、TTS、Live 模型,各文本与图片模型带 Google 搜索的 `-search` 变体,以及 Build 通道的 `-build` 模型。Genie 4(`genie-4`)只对开通计费的 API key 开放,列在目录中、不含 `channels`。
+目录中另有 `-latest` 别名、Robotics-ER、Gemini 3 系列与早期版本的图片、TTS、Live 模型,各文本与图片模型带 Google 搜索的 `-search` 变体,以及 Build 通道的 `-build` 模型。只对付费 API key 开放的模型(如 Genie 4,`genie-4`)本服务调用不了,管理端模型目录标注“仅限付费 API key”,公开目录不列出。
-公开端点实现标准 `generateContent`、`countTokens`、`embedContent`、`batchEmbedContents`、`predictLongRunning` 和 `createDecision`(`/v1beta/decisions`);`bidiGenerateContent` 与 `bidiGenerateMusic` 模型经 `/v1/live` 调用。`/v1/models` 与 `/v1beta/models` 原样汇总各账户实时上游目录;调度按目录明确提供的模型 ID、方法、能力字段和账户当前运行状态选择账户。
+公开端点实现标准 `generateContent`、`countTokens`、`embedContent`、`batchEmbedContents`、`predictLongRunning` 和 `createDecision`(`/v1beta/decisions`);`bidiGenerateContent` 模型经 `/v1/live` 或标准 Live 端点调用,`bidiGenerateMusic` 模型经 `/v1/live` 调用。`/v1/models` 与 `/v1beta/models` 原样汇总各账户实时上游目录中本服务调用得了的模型;调度按目录明确提供的模型 ID、方法、能力字段和账户当前运行状态选择账户。
- 启用账户的订阅都不满足的模型(如只对 Google AI Ultra 开放的模型)同样列在目录中、不含 `channels`,调用时返回 403 并写明所需订阅
- 能力含 `output_continuation` 的模型(如 Gemini 4 Argon)与官网一样接受到 `input_token_limit` 的输出上限:未指定输出上限时取 `input_token_limit`,超过 32768 时分轮自动续写,各轮输出合并为一个响应
@@ -693,6 +694,7 @@ cp .env.example .env
| `GENERATE_CONTENT_ACCOUNTS` | 空 | 被 Google 迁到任务接口的模型在这些账户上改用 GenerateContent 发送,账户 ID 逗号分隔;请求方式与官网不同,可能触发 Google 风控;保存后立即生效 |
| `BUILD_NATIVE_NONSTREAM` | `true` | 启用 Build 通道时非流式请求优先使用 Build 原生单次调用;不可用时回退流式并记录原因 |
| `BUILD_CHAT_MODELS` | `true` | 提供 `-build` 对话模型;关闭时这些模型不出现在 `/v1/models`,请求时返回已在设置中关闭的错误;保存后立即生效 |
+| `BUILD_CHAT_PROTOCOL` | `auto` | `-build` 对话模型使用的上游协议:`auto` 按账户页面启动数据标志 `45831005` 自适应选择,`agency` 固定走新版 `StreamRunAgentTask`,`legacy` 固定走旧版 `CodeAssistantOffline`;保存后下一次请求生效 |
| `NONSTREAM_KEEPALIVE` | `true` | 非流式请求等待结果超过 10 秒时先返回 200 并定时写出换行保持连接 |
| `FAKE_STREAM` | `false` | 流式请求先按非流式取得完整结果再按流式格式输出,中途失败时换号重发,等待期间照常发送心跳 |
| `YOUTUBE_LINKS` | `false` | 用户消息文本中的 YouTube 链接作为视频发送给模型,并从文本中移除 |
diff --git a/README_en.md b/README_en.md
index 89f87762..2df9c462 100644
--- a/README_en.md
+++ b/README_en.md
@@ -91,7 +91,7 @@ The three projects connect to AI Studio, the Gemini web app and Antigravity, and
- **Smart Model Switching**: Discover models from AI Studio and route through the `model` field; with `DISCOVER_HIDDEN_MODELS` enabled, models that AI Studio hasn't made public yet are added to the model list once the account is confirmed to be able to use them; the Model catalog page chooses per model whether it is shown in the API
- **Google Tools**: Search, Image Search, URL Context, Code Execution, and Maps
- **Files and Transcribe**: File upload, metadata, content, deletion, and audio transcription
-- **Live and Robotics**: WebSocket text, audio, JPEG images, media end, tool calls, resumption, and interruption
+- **Live and Robotics**: WebSocket text, audio, JPEG images, media end, tool calls, resumption, and interruption; Live clients of the Google Gen AI SDKs connect directly
- **Anti-Fingerprinting**: Each account keeps a stable Firefox fingerprint and network exit, and the official WAA runs in the Firefox page environment of SpiderMonkey or in a Camoufox page
- **GUI Launcher**: Manage accounts, service controls, live logs, models, requests, usage statistics (broken down by API key once several keys are in use), account pool quota by model and by account, and configuration in the web UI, with dark and light color themes and seven languages: 简体中文, 繁體中文, English, 日本語, 한국어, Français, and Deutsch
- **Desktop App**: Windows, macOS, and Linux desktop apps show the management UI in a window and keep running in the system tray after the window is closed
@@ -428,6 +428,7 @@ Main endpoints:
| Video | `POST /v1/videos`, `GET /v1/videos`, `GET`/`DELETE /v1/videos/{id}`, `GET /v1/videos/{id}/content` |
| Gemini Video | `POST /v1beta/models/{model}:predictLongRunning`, `GET /v1beta/operations/{id}` |
| Live (including live translation, live transcription, and live music) / Robotics | `GET /v1/live`, `GET /v1/robotics/stream` |
+| Gemini Live (Google Gen AI SDKs) | `GET /ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`; `v1alpha` and `v1` also work |
The Gemini `/v1beta` paths are also available under `/v1`, which Google Gen AI SDK 3.x uses by default. Requests to `/v1/models` and `/v1/files` that carry an `x-goog-api-key` header or a `key` parameter without `Authorization` get Gemini responses; all others get OpenAI responses.
@@ -506,7 +507,7 @@ curl http://127.0.0.1:2048/v1beta/models/gemini-2.5-flash-preview-tts:generateCo
- Available voices are returned by `capability_options.voices` in the live model catalog
- Models with the `speech_metadata` capability, such as `gemini-3.8-flash-tts`, accept the same `Speaker: line` script; each text part can also set `speechMetadata.speaker` and `speechMetadata.style`, with `multiSpeakerVoiceConfig.mode` selecting `VERBATIM` or `CONVERSATIONAL`
- OpenAI `instructions` become the speech style on these models
-- Custom voices (Voice Design): create one with `POST /v1beta/voices` and `{"voice":{"type":"prompted","display_name":"Old Sailor","prompted":{"input":""}}}`; the response carries a `voice_...` ID and a preview clip, and the ID works in the voice field of every protocol. The service picks the closest prebuilt voice for the description and sends the description as a speaking style. "New voice" on the playground speech page runs the same flow
+- Custom voices (Voice Design): create one with `POST /v1beta/voices` and `{"voice":{"type":"prompted","display_name":"Old Sailor","prompted":{"input":""}}}`; the response carries a `voice_...` ID and a preview clip, and the ID works in the voice field of every protocol. The service picks the closest prebuilt voice for the description and sends the description as a speaking style. "New voice" on the playground speech page runs the same flow, with prompt improvement, remixing an existing voice and voice replication from a recording
### Image Generation (Nano Banana)
@@ -598,9 +599,9 @@ The model catalog follows AI Studio updates; clients read the current values fro
| `gemini-3.8-live` | Gemini 3.8 Live | Live | 131072 | 65536 |
| `gemini-3.5-live-translate-preview` | Gemini 3.5 Live Translate Preview | Live translation | 16384 | 32768 |
-The catalog also includes `-latest` aliases, Robotics-ER, the Gemini 3 series, earlier image, TTS, and Live models, `-search` variants of text and image models with Google Search turned on, and the Build channel's `-build` models. Genie 4 (`genie-4`) is open only to API keys with billing enabled; it is listed without `channels`.
+The catalog also includes `-latest` aliases, Robotics-ER, the Gemini 3 series, earlier image, TTS, and Live models, `-search` variants of text and image models with Google Search turned on, and the Build channel's `-build` models. Models open only to paid API keys (such as Genie 4, `genie-4`) cannot be called by this service; the admin model catalog marks them "Paid API key only" and the public catalog does not list them.
-Public endpoints implement `generateContent`, `countTokens`, `embedContent`, `batchEmbedContents`, `predictLongRunning`, and `createDecision` (`/v1beta/decisions`); `bidiGenerateContent` and `bidiGenerateMusic` models are called through `/v1/live`. `/v1/models` and `/v1beta/models` preserve the live upstream catalogs across accounts; scheduling uses explicit model ID, method, and capability fields plus current account runtime state.
+Public endpoints implement `generateContent`, `countTokens`, `embedContent`, `batchEmbedContents`, `predictLongRunning`, and `createDecision` (`/v1beta/decisions`); `bidiGenerateContent` models are called through `/v1/live` or the standard Live endpoint, and `bidiGenerateMusic` models through `/v1/live`. `/v1/models` and `/v1beta/models` preserve the callable models of the live upstream catalogs across accounts; scheduling uses explicit model ID, method, and capability fields plus current account runtime state.
- Models that no enabled account's subscription covers (such as models open only to Google AI Ultra) are still listed without `channels`, and calls return 403 naming the required subscription
- Models with the `output_continuation` capability (such as Gemini 4 Argon) accept an output limit up to `input_token_limit`, as on the official site: they use `input_token_limit` when the request sets no output limit, and beyond 32768 tokens the response continues automatically in multiple rounds and is returned as one response
@@ -693,6 +694,7 @@ Process environment variables override the same keys in `.env`, and those settin
| `GENERATE_CONTENT_ACCOUNTS` | empty | Account IDs, comma-separated, that send models Google moved to the task API via GenerateContent instead; this differs from AI Studio and may trigger Google's risk controls; applied on save |
| `BUILD_NATIVE_NONSTREAM` | `true` | With the Build channel enabled, prefer native Build unary calls for non-streaming requests; log any fallback to stream collection |
| `BUILD_CHAT_MODELS` | `true` | Offer the `-build` chat models; when off they are left out of `/v1/models` and requests return an error saying they are turned off in settings; applied on save |
+| `BUILD_CHAT_PROTOCOL` | `auto` | Upstream protocol for the `-build` chat models: `auto` follows flag `45831005` in the account's page bootstrap data, `agency` always uses the new `StreamRunAgentTask`, `legacy` always uses the old `CodeAssistantOffline`; applied to the next request after saving |
| `NONSTREAM_KEEPALIVE` | `true` | When a non-streaming request waits longer than 10 seconds, return 200 first and keep the connection open with periodic newlines |
| `FAKE_STREAM` | `false` | Streaming requests get the full result as a non-streaming generation, retry on another account if it fails midway, then stream it in the protocol format; heartbeats continue while waiting |
| `YOUTUBE_LINKS` | `false` | Send YouTube links in user message text to the model as video and remove them from the text |
diff --git a/docs/build.md b/docs/build.md
index 9dbec941..ccf01796 100644
--- a/docs/build.md
+++ b/docs/build.md
@@ -2,8 +2,8 @@
AI Studio Build 页面的对话面板由写代码助手回复。服务把它作为生成通道 `assistant`,经模型名后缀 `-build` 调用,例如 `gemini-3.8-flash-build`。这是 Build 当前可用的通道,第 1 至 8 节定义:
-- 写代码助手的 RPC 与 `-build` 模型的目录与调度
-- 规范请求到 `CodeAssistantOffline` 的映射、对话历史转录与说明文件
+- 写代码助手的 RPC、协议选择(`agency` 与 `legacy`)与 `-build` 模型的目录与调度
+- 规范请求到 `StreamRunAgentTask`(`agency`)与 `CodeAssistantOffline`(`legacy`)的映射、对话历史转录与说明文件
- 每轮的 RPC 顺序、应用与 trajectory 的续接
- 任务流解码与错误处理
@@ -13,15 +13,24 @@ AI Studio Build 页面的对话面板由写代码助手回复。服务把它作
助手带有服务端的系统提示词,用量计入 Build 对话的额度:免费账户为免费请求,Google AI 订阅账户为订阅额度,与 Playground、Build 应用代理分别计算。`assistant` 是 `playground`、`build` 之外的第三个通道。
-第 1 至 8 节的 RPC 地址为 `https://alkalimakersuite-pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService/`,以下两个除外:
+第 1 至 8 节的 RPC 地址为 `https://alkalimakersuite-pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService/`,以下除外:
| RPC | 服务 |
| --- | --- |
+| `StreamRunAgentTask`、`CancelAgentTask` | `https://alkalimakersuiteapplets.pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.applets.AppletGenerationService` |
| `ApplyFileSystemOperation`、`GetBufferedLogs`、`StreamLogs` | 同一主机的 `google.alkali.boq.makersuite.makersuiteappletcontrol.proto.MakersuiteAppletControlService` |
| `MintAppletAuthToken` | `https://alkalimakersuiteapplets.pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.applets.AppletAuthService` |
方法为 `POST`,正文为 `application/json+protobuf` 稀疏数组:protobuf field N 对应 JSON 索引 N-1,中间未设置的 field 写 `null`。
+### 协议选择(`BUILD_CHAT_PROTOCOL`)
+
+官网 Build 前端按账户页面启动数据 `TSDtV` 中的布尔标志 `45831005`(`_.SOc`,缺省为 `false`)选择上游协议:`true` 走新版 `agency`(`AppletGenerationService/StreamRunAgentTask` 与 `CancelAgentTask`),`false` 或缺失走旧版 `legacy`(`MakerSuiteService/CodeAssistantOffline` 等四接口)。
+
+- `BUILD_CHAT_PROTOCOL` 取值 `auto`(默认)、`agency` 或 `legacy`,保存后下一次请求生效;无效值记录校验错误并按 `auto` 运行
+- `auto` 模式下,两种 WAA 后端都在页面载入与重新载入时按官网 `TSDtV` `%.@.` 结构(`root[0][0][1]` 中 `[flagID, ..., boolVal]`)读取标志 `45831005` 并按账户刷新;缺失时按 `legacy` 运行,并在账户取值变化时记一次告警日志,协议或依据变化时记服务日志
+- 两条协议路径出错都不回退到另一套协议
+
## 2. 目录与调度
ListModels 行的主能力码(field 65)含 48 的模型,即 Build 设置面板 “Select model to use in Chat” 下拉框列出的模型。目录解析完成后,每个这样的模型派生一个条目,按原顺序追加在该账户目录末尾;目录已有同名 ID 时不派生。
@@ -58,17 +67,18 @@ ListModels: gemini-3.8-flash(主能力码含 48)
## 3. 请求映射
-| 规范请求 | `CodeAssistantOffline` |
-| --- | --- |
-| contents | field 1,续接 trajectory 时只含续接位置之后的轮次 |
-| system | field 9 自定义指令;超过上限时为 field 1 第一轮开头的说明文件 |
-| 内置工具禁止说明 | field 9 开头 |
-| 函数声明 | field 9 中系统提示之前的函数调用说明;超过上限且函数调用说明也放不下时为说明文件 |
-| 思考强度或思考预算 | field 19 的 thinking level |
+| 规范请求 | `StreamRunAgentTask`(`agency`) | `CodeAssistantOffline`(`legacy`) |
+| --- | --- | --- |
+| contents | field 3,续接 trajectory 时只含续接位置之后的轮次 | field 1,续接 trajectory 时只含续接位置之后的轮次 |
+| system | field 5(`[null, null, <自定义指令>, null, null, 2]`);超过上限时为 contents 第一轮开头的说明文件 | field 9 自定义指令;超过上限时为 field 1 第一轮开头的说明文件 |
+| 内置工具禁止说明 | 自定义指令开头 | field 9 开头 |
+| 函数声明 | 自定义指令中系统提示之前的函数调用说明;放不下时为说明文件 | field 9 中系统提示之前的函数调用说明;放不下时为说明文件 |
+| 思考强度或思考预算 | field 7 的 thinking level(`[1, null, null, ]`) | field 19 的 thinking level |
- 上游请求只携带对话轮、系统提示、函数调用说明与思考强度;生成参数、结构化输出与安全设置使用助手的服务端设置
-- 内联附件按官网对话面板上传,对话轮中以 Part field 18 `[mime, 上传路径, 文件名, 字节数]` 引用:文件名为 `attachment-<序号>`,序号按附件在 field 1 中的顺序从 1 开始;上传见“附件上传”
-- 附件与说明文件的上传与新建应用、开启新 trajectory 的请求(`ListAppletTrajectories`、`ListCodeAssistantOfflineGenerations`)同时进行
+- 内联附件按官网对话面板上传,对话轮中以 Part field 18 `[mime, 上传路径, 文件名, 字节数]` 引用:文件名为 `attachment-<序号>` 加按 MIME 取的扩展名(常见的图片、PDF、文本、音频与视频类型,其余没有扩展名),序号按附件在 contents 中的顺序从 1 开始,字节数为 JSON 数字;上传见“附件上传”
+- 附件与说明文件的上传与新建应用、开启新 trajectory 的请求同时进行
+- 本节其余部分与第 5 节以 `legacy` 的字段号指称这些位置:field 1 为对话轮,field 9 为自定义指令,field 19 为 thinking level,field 21 为 trajectory ID;`agency` 中依次是 field 3、field 5 的第 3 项、field 7 的第 4 项与 field 2
### 自定义指令(field 9)
@@ -233,52 +243,65 @@ field 19 的 thinking level 取值:
账户没有应用或应用已不存在(官网从 Build 首页输入第一条提示):
ListImportedProjects → ListCloudProjects → ListCloudApiKeys(WAA proof)
[GenerateCloudApiKey(WAA proof)] → [CreateCloudProject(WAA proof) → GenerateCloudApiKey(WAA proof)] (见“CreateApplet”的 API key)
- CreateApplet(WAA proof) → StoreRecentApplet
+ CreateApplet(WAA proof) (响应 field 4 为新建应用的初始 trajectory ID;StoreRecentApplet 在 CreateApplet 返回后异步发出,不阻塞首字)
本进程第一次使用账户的应用(官网从 My apps 打开应用):
- GetApplet
- GetCodeAssistantSnapshot、StoreRecentApplet、ProvisionAndInitializeApplet(WAA proof)、ListCodeAssistantFeatures、GetPendingArenaInteraction、
- ListUnsetAppletSecrets、LoadCodeAssistantInteractionHistory、ListCodeAssistantOfflineGenerations、ListAppletTrajectories、ListAppletSecrets
+ GetApplet (响应 field 2 为服务端当前活跃 trajectory ID)
+ GetCodeAssistantSnapshot、ProvisionAndInitializeApplet(WAA proof)、ListCodeAssistantFeatures、GetPendingArenaInteraction、
+ ListUnsetAppletSecrets、LoadCodeAssistantInteractionHistory(field 6 传 GetApplet field 2)、ListAppletTrajectories、ListAppletSecrets
+ (legacy 模式另发 ListCodeAssistantOfflineGenerations;StoreRecentApplet 在后台异步发出)
在后台与本轮同时进行:ApplyFileSystemOperation、GetBufferedLogs → StreamLogs、MintAppletAuthToken(生成服务停止时结束)
开启新 trajectory(官网点 New chat):
- ListAppletTrajectories、ListCodeAssistantOfflineGenerations
-每轮:
- /_/upload(field 1 中每个内联附件一次,与上面新建应用或开启新 trajectory 的请求同时进行)
- CodeAssistantOffline(WAA proof) → 任务 ID 与 trajectory ID
- StreamCodeAssistantOfflineGeneration → 步骤快照流,读到本轮回复结束或上游关闭
- StreamCodeAssistantOfflineGeneration (消息列表在回复完成前结束时再请求一次)
- CodeAssistantOffline、StreamCodeAssistantOfflineGeneration(还没有输出正文与函数调用时回复为空、调用代码块缺失或无法解码、调用了被禁止的工作区工具,追加用户轮,最多 3 次)
+ agency:ListAppletTrajectories(客户端生成新 UUIDv4 作为 trajectory ID)
+ legacy:ListAppletTrajectories、ListCodeAssistantOfflineGenerations
+每轮(下一轮开始前如上一轮后置伴随任务仍在运行,先取消并等待其收尾,避免并发重叠):
+ /_/upload(本轮每个内联附件一次,与上面新建应用或开启新 trajectory 的请求同时进行)
+ agency:
+ StreamRunAgentTask(WAA proof,Priority: u=0) → 步骤快照流,完整读至末尾游标哨兵帧与 EOF
+ StreamRunAgentTask(续接同 trajectory 与最新 cursor;仅在未输出正文与函数调用且回复为空/格式错/调用禁止工具时追加用户轮,最多 3 次)
+ legacy:
+ CodeAssistantOffline(WAA proof,Priority: u=0) → 任务 ID 与 trajectory ID
+ StreamCodeAssistantOfflineGeneration → 步骤快照流,读到本轮回复结束或上游关闭(未完成前结束时再请求一次)
新应用的第一段对话提交后:
ListUnsetAppletSecrets、ListAppletTrajectories、ListAppletSecrets
+每轮结束在后台(含成功、取消与失败):
+ MakerSuiteService/Log(携带本轮 runId、首字耗时、总耗时、轮次类型与工作区基础元数据)
回复完整结束后在后台:
新应用的第一段对话:ProvisionAndInitializeApplet(WAA proof)、ListAppletSecrets、ListUnsetAppletSecrets
→ ApplyFileSystemOperation、SaveApplet、MintAppletAuthToken、GenerateCodeAssistantSuggestionChips(WAA proof)
其余各轮: ApplyFileSystemOperation、SaveApplet、ListAppletSecrets、ListUnsetAppletSecrets、GenerateCodeAssistantSuggestionChips(WAA proof)
→ StoreRecentApplet
回复没有完整结束时在后台:
- CancelCodeAssistantOfflineGeneration (已取得任务 ID、流没有正常解码完成且任务没有以失败步骤结束时)
+ agency:CancelAgentTask(Priority: u=0,带 X-AIStudio-G1-Tier) → ListAppletSecrets
+ legacy:CancelCodeAssistantOfflineGeneration
```
-- 请求头的集合、顺序与取值和 Playground 文本请求的 `GenerateContent` 相同;权益头 `X-AIStudio-G1-Tier` 只随 `CodeAssistantOffline` 发送(Pro 为 `TIER1`、Ultra 为 `TIER2`、Plus 为 `TIER0`,Free 不带)
-- `CodeAssistantOffline` 由账户 WAA Worker 发送;标注 WAA proof 的应用与云项目 RPC 经账户 Worker 写入 fresh proof 后由账户的 MakerSuite Go HTTP transport 发送;其余 RPC 与附件上传经同一 transport,使用同一账户的 Cookie、UA 与出口
+- 请求头的集合、顺序与取值和 Playground 文本请求的 `GenerateContent` 相同;`StreamRunAgentTask`、`CodeAssistantOffline` 与 `CancelAgentTask` 携带 `Priority: u=0`;权益头 `X-AIStudio-G1-Tier` 随 `StreamRunAgentTask`、`CancelAgentTask` 与 `CodeAssistantOffline` 发送(Pro 为 `TIER1`、Ultra 为 `TIER2`,Free 与 Plus 不带)
+- `StreamRunAgentTask` 与 `CodeAssistantOffline` 由账户 WAA Worker 经可信输入 `RunProof`(不触发 Playground 的 New chat 与 2712/GA4 点击上报)生成 proof 并发送;标注 WAA proof 的应用与云项目 RPC 经账户 Worker 写入 fresh proof 后由账户的 MakerSuite Go HTTP transport 发送;其余 RPC 与附件上传经同一 transport,使用同一账户的 Cookie、UA 与出口
- 伴随请求失败时以 WARN 记录 “Build 写代码助手伴随请求失败”,字段为 `account`、`method` 与 `error`,不影响本轮回复
-- 非流式请求同样读取任务流,收齐后输出;日志的“上游调用”记录 `stream` 模式、RPC `CodeAssistantOffline` 与原因 “Build 写代码助手使用服务端流,收集完成后返回”
+- 非流式请求同样读取任务流,收齐后输出;日志的“上游调用”记录 `stream` 模式与实际 RPC(`StreamRunAgentTask` 或 `CodeAssistantOffline`)及原因 “Build 写代码助手使用服务端流,收集完成后返回”
## 5. 对话与应用
上游在应用的 trajectory 中保存对话:
-- 官网新建应用时,第一段对话的 trajectory ID 即应用 ID
-- 点 New chat 后,第一轮 `CodeAssistantOffline` 的 field 23 为 `1`,响应带新的 trajectory ID
-- 同一 trajectory 的后续轮次:field 1 只有新的 user 轮,field 6 为 `2`、field 14 为 `[2]`、field 21 为 trajectory ID
+- `agency` 协议下:
+ - 新建应用时,`CreateApplet` 响应 field 4 返回初始 `trajectoryId`(与 `appletId` 不同),首轮 `StreamRunAgentTask` 直接传入该 `trajectoryId`、field 8 为 `null`、省略 field 13,避免新建应用首轮分裂两条 trajectory
+ - 开启新对话(点 New chat)时,客户端生成随机大写 UUID v4 写入 `StreamRunAgentTask` field 2、field 8 为 `null`、省略 field 13
+ - 同一 trajectory 的后续轮次:field 3 只含新的 user 轮,field 2 为原 `trajectoryId`,field 8 为上一轮末尾游标哨兵帧返回的整数 `cursor`,field 13 为 `[interactionId, cursor]`
+ - 重开应用时读取 `GetApplet` 响应 field 2(服务端当前活跃 `trajectoryId`)传给 `LoadCodeAssistantInteractionHistory` field 6,并用响应 field 4、field 5 回填或更新活跃轨迹的游标与 `interactionId`
+ - 取消按钮发送 `AppletGenerationService/CancelAgentTask`(`[appletId, trajectoryId, stepId?]`)并补发 `ListAppletSecrets`
+- `legacy` 协议下:
+ - 官网新建应用时,第一段对话的 trajectory ID 即应用 ID;点 New chat 后第一轮 `CodeAssistantOffline` field 23 为 `1`,响应带新的 trajectory ID
+ - 同一 trajectory 的后续轮次:field 1 只有新的 user 轮,field 6 为 `2`、field 14 为 `[2]`、field 21 为 trajectory ID
+ - 停止按钮发送 `CancelCodeAssistantOfflineGeneration`
- 之后的生成按原角色读取该 trajectory 以前的 user 轮与 model 轮(含思考与函数调用代码块);取消的回复保存到取消处
-- 官网对话面板的回复没有重新生成按钮;停止按钮发送 `CancelCodeAssistantOfflineGeneration`,回复显示为已取消
每个账户使用一个应用,应用 ID 与可续接的 trajectory 写在账户 `runtime-state.json` 的 `assistant` 中:
```json
"assistant": {
"id": "",
- "trajectories": [{"tip": "<续接位置>", "id": "", "history_groups": 2}]
+ "trajectories": [{"tip": "<续接位置>", "id": "", "cursor": 116, "interaction_id": "v1/default/aistudio_build/...", "protocol": "agency", "history_groups": 2}]
}
```
@@ -287,7 +310,10 @@ field 19 的 thinking level 取值:
| `id` | 账户的应用 ID |
| `trajectories[].tip` | 请求所用 API key 与到本轮回复为止的对话摘要合成的 SHA-256,不含明文 key |
| `trajectories[].id` | trajectory ID |
-| `trajectories[].history_groups` | 开启 trajectory 时转录在 field 9 中的开头分组数,没有转录时省略 |
+| `trajectories[].cursor` | `agency` 协议最近一轮末尾哨兵帧的游标整数,无游标时省略 |
+| `trajectories[].interaction_id` | `agency` 协议该 trajectory 对应的 `interactionId`,缺失时省略 |
+| `trajectories[].protocol` | 创建或最后续接该轨迹使用的协议(`agency` 或 `legacy`),缺失时省略 |
+| `trajectories[].history_groups` | 开启 trajectory 时转录在自定义指令中的开头分组数,没有转录时省略 |
| `trajectories[].context` | trajectory 中最近一个说明文件的系统提示与函数声明的 SHA-256,没有说明文件时省略 |
- 对话轮按连续的 model 轮与其余轮次分组,逐组累积 SHA-256 摘要。每组计入非思考正文 Part 直接连接后按空白归一的结果、函数调用的名称与键排序的参数、函数结果键排序的内容,其余 Part 去掉思考签名计入,内联数据以其 SHA-256 计入;调用 ID 不计入,客户端以不同格式回传同一回复时摘要相同
@@ -296,8 +322,9 @@ field 19 的 thinking level 取值:
- 找不到时在账户的应用中开启新 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 时,删除本轮续接的续接位置,重新打开应用(应用已不存在时新建)后重新提交本轮一次
+- 本进程第一次使用账户的应用时照官网打开它,见“RPC 顺序”;`GetApplet` 返回 404 时新建应用。应用已被删除或续接的 trajectory 不存在时,`CodeAssistantOffline` 返回 404 code 5;已打开的应用上生成请求(`StreamRunAgentTask` 或 `CodeAssistantOffline`)返回 404 且还没有取得任务 ID 时,删除本轮续接的续接位置,重新打开应用(应用已不存在时新建)后重新提交本轮一次
- 服务重启后从 `runtime-state.json` 读取应用与续接位置,打开应用后续接同一 trajectory
+- 同一应用在 `legacy` 与 `agency` 之间切换协议时:若原轨迹由 `legacy` 创建且重开 `LoadCodeAssistantInteractionHistory` 未返回有效游标,或在 `legacy` 模式下命中了 `agency` 创建的轨迹,服务在同一应用中按新协议开启新 trajectory 并完整转录先前对话历史,不跨协议混用轨迹游标
### 附件上传
@@ -310,9 +337,11 @@ field 19 的 thinking level 取值:
两次请求都不带 `Authorization` 与 `X-Goog-Api-Key`。
+请求头顺序与官网一致:start 依次为 `user-agent`、`accept`、`accept-language`、`accept-encoding`、`referer`、`x-goog-hash`、`x-goog-upload-header-content-length`、`x-goog-upload-header-content-type`、`x-goog-upload-protocol`、`x-goog-upload-command`、`content-type`、`content-length: 0`、`origin`、`cookie`、`sec-fetch-*`、`te`;upload 依次为 `user-agent`、`accept`、`accept-language`、`accept-encoding`、`referer`、`content-type`、`x-goog-hash`、`x-goog-upload-command`、`x-goog-upload-offset`、`content-length`、`origin`、`cookie`、`sec-fetch-*`、`te`。
+
| 步骤 | 地址 | 请求头 | 正文 | 响应 |
| --- | --- | --- | --- | --- |
-| start | `https://aistudio.google.com/_/upload` | `X-Goog-Upload-Protocol: resumable`、`X-Goog-Upload-Command: start`、`X-Goog-Upload-Header-Content-Length`、`X-Goog-Upload-Header-Content-Type`、`X-Goog-Hash` | 空 | 200,`X-Goog-Upload-URL` 为上传地址 |
+| start | `https://aistudio.google.com/_/upload` | `Content-Type: application/x-www-form-urlencoded;charset=utf-8`、`X-Goog-Upload-Protocol: resumable`、`X-Goog-Upload-Command: start`、`X-Goog-Upload-Header-Content-Length`、`X-Goog-Upload-Header-Content-Type`、`X-Goog-Hash` | 空 | 200,`X-Goog-Upload-URL` 为上传地址 |
| upload | `X-Goog-Upload-URL` | `Content-Type`、`X-Goog-Hash`、`X-Goog-Upload-Command: upload, finalize`、`X-Goog-Upload-Offset: 0` | 附件字节 | 200,`X-Goog-Upload-Status: final`,正文为上传路径 |
```text
@@ -325,14 +354,14 @@ field 19 的 thinking level 取值:
| RPC | 正文 | 响应 |
| --- | --- | --- |
-| `GetApplet` | `[""]` | field 1 为应用 `[应用 ID, 创建时间, 修改时间, 元数据, ...]`,应用 field 7 为最近一次快照时间、field 12 为 `[开发环境地址]` |
+| `GetApplet` | `[""]` | field 1 为应用 `[应用 ID, 创建时间, 修改时间, 元数据, ...]`,应用 field 7 为最近一次快照时间、field 12 为 `[开发环境地址]`;field 2 为当前活跃 `trajectoryId` |
| `GetCodeAssistantSnapshot` | 有快照时 `["",null,<快照时间>]`,没有快照时 `["",true]` | 丢弃 |
-| `StoreRecentApplet` | `[[null,null,<应用引用>,"<标题>","<描述>",null,1]]` | `[]` |
+| `StoreRecentApplet` | `[[null,null,<应用引用>,"<标题>","<描述>",null,1]]`(后台异步) | `[]` |
| `ProvisionAndInitializeApplet` | `["",1,null,""]`,proof 写入 field 4,binding 为应用 ID | field 1 为 `[开发环境地址]` |
| `ListUnsetAppletSecrets`、`ListAppletTrajectories`、`GetPendingArenaInteraction` | `[""]` | 丢弃 |
| `ListCodeAssistantFeatures` | `[1]` | 丢弃 |
-| `LoadCodeAssistantInteractionHistory` | `["",100,null,null,null,""]` | 丢弃 |
-| `ListCodeAssistantOfflineGenerations` | `[null,null,[1,2],[""]]` | 丢弃 |
+| `LoadCodeAssistantInteractionHistory` | `["",100,null,null,null,""]`(`GetApplet` 无 field 2 时退回 ``) | 读取 field 4(`cursor`)与 field 5(`[interactionId, cursor]`)回填活跃轨迹 |
+| `ListCodeAssistantOfflineGenerations` | `[null,null,[1,2],[""]]`(仅 `legacy` 模式发送) | 丢弃 |
| `ListAppletSecrets` | `["applets/",100]` | 丢弃 |
| `ApplyFileSystemOperation` | `[[[null,null,null,null,["."]]],null,null,null,""]` | 丢弃 |
| `GetBufferedLogs`、`StreamLogs` | `[null,null,null,""]` | 丢弃 |
@@ -375,12 +404,41 @@ field 19 的 thinking level 取值:
上游据首条提示生成应用的标题与描述。响应:
```json
-["",["",["1794569358",319443000],["1794569358",319443000],["<标题>","<描述>","<首条提示>",null,"default",null,null,null,[1],null,[1]],...]]
+["",["",["1794569358",319443000],["1794569358",319443000],["<标题>","<描述>","<首条提示>",null,"default",null,null,null,[1],null,[1]],...],null,""]
+```
+
+服务读取 field 2 中的应用与 field 4 中的初始 `trajectoryId`;缺少应用 ID 或元数据时返回协议错误 “缺少应用 ID 或元数据”。`StoreRecentApplet` 在 `CreateApplet` 返回后记录当前时刻(精确到毫秒),以 `[[[<秒>,<纳秒>],null,<应用引用>,"Untitled","Generated by Gemini."]]` 在后台异步发送,不阻塞首轮生成。
+
+### StreamRunAgentTask(`agency`)
+
+新应用首轮与开启新对话(9 元数组):
+
+```json
+["","",[[[[null,"What is 6*7?"]],"user"]],"",[null,null,"",null,null,2],"models/gemini-4-hydrogen",[1,null,null,3],null,""]
```
-服务读取 field 2 中的应用;缺少应用 ID 或元数据时返回协议错误 “缺少应用 ID 或元数据”。随后发送 `StoreRecentApplet`,正文为 `[[[<秒>,<纳秒>],null,<应用引用>,"Untitled","Generated by Gemini."]]`,时间戳为开始新建应用的时刻、精确到毫秒。
+续接已有 trajectory(13 元数组):
+
+```json
+["","",[[[[null,"<新的 user 轮>"]],"user"]],"",[null,null,"",null,null,2],"models/gemini-4-hydrogen",[1,null,null,3],116,"",null,null,null,["",116]]
+```
-### CodeAssistantOffline
+| field | 内容 |
+| ---: | --- |
+| 1 | 应用 ID |
+| 2 | `trajectoryId`(新应用首轮为 `CreateApplet` field 4;新对话为客户端生成的大写 UUID v4;续接为原 `trajectoryId`) |
+| 3 | 对话轮,编码与 Playground `GenerateContent` 的 contents 相同 |
+| 4 | WAA proof,binding 为 `` 与 contents 各 Part(按 `_.$n` 取文本/Base64/Drive ID,Upload 取空)以空格连接 |
+| 5 | 选项数组 `[null,null,"<自定义指令>",null,null,2]`(`2` 为默认 React 框架) |
+| 6 | `models/<基础模型 ID>` |
+| 7 | 思考配置 `[1,null,null,]` |
+| 8 | 续接游标整数(首轮与新对话为 `null`) |
+| 9 | 每个请求新生成的大写 UUID v4(`runId`) |
+| 13 | 续接上下文 `["", ]`(首轮与新对话省略) |
+
+响应为单次流式正文,每条消息为 `[步骤列表, trajectoryId, cursorStr, null, [interactionId, cursorStr]]`,末尾含 `step[11]=null, status=1` 游标哨兵帧。服务完整读完消息流与 EOF,避免向服务端发 `RST_STREAM(CANCEL)`。
+
+### CodeAssistantOffline(`legacy`)
```json
[[[[[null,"What is 6*7?"]],"user"]],"",null,null,null,1,null,"models/gemini-3.8-flash","",null,null,"",null,[2,null,2],null,1,null,null,[1,null,null,3],null,null,null,null,null,null,null,null,null,""]
@@ -430,27 +488,28 @@ WAA binding 与 Playground `GenerateContent` 相同:contents 各 Part 依次
| RPC | 正文 |
| --- | --- |
+| `Log` | `[[["",[[null,,,,,]],"",[<元数据>,[["metadata.json","",null]]]]]]`(每轮成功/取消/失败均在后台发送) |
| `SaveApplet` | `["",<元数据>]` |
| `StoreRecentApplet` | `[[[<秒>,<纳秒>],null,<应用引用>,"<标题>","<描述>"]]` |
| `GenerateCodeAssistantSuggestionChips` | `[<对话>,"","<标题>","<描述>",null,""]` |
-- `SaveApplet` 的元数据取打开或新建应用时读到的元数据并补齐到 11 项,field 6 为应用 ID、field 8 为 `null`
+- `SaveApplet` 的元数据取打开或新建应用时读到的元数据并补齐到 11 项,field 6 为应用 ID、field 7 与 field 8 清空为 `null`
- `GenerateCodeAssistantSuggestionChips` 的对话为请求的对话加本轮回复中各轮的非思考正文,每轮为 `[[[null,"<正文>"]...],"user"|"model"]`;proof 写入 field 2,binding 为这些正文以空格连接
+- 同一账户的下一轮 `-build` 请求发出前,如上一轮后置伴随任务仍在运行,先取消并等待其收尾,避免后置写操作与下一轮生成并发重叠
其余伴随请求的正文见“打开应用”。
### 取消
-```json
-["",""]
-```
+- `agency`:`AppletGenerationService/CancelAgentTask`,正文 `["","",]`(携带 `Priority: u=0` 与 `X-AIStudio-G1-Tier`),随后补发 `ListAppletSecrets`
+- `legacy`:`MakerSuiteService/CancelCodeAssistantOfflineGeneration`,正文 `["",""]`
-- 任务流正文关闭时结束请求,包括正常读完、客户端断开与停止序列截断;回复完整结束时写入续接位置并发送回复后的伴随请求,否则删除本轮续接的续接位置;生成服务停止时尚未发出的伴随请求不再发送
-- 已取得任务 ID、流没有正常解码完成且任务没有以失败步骤结束时,在后台以独立的 1 分钟期限发送一次 `CancelCodeAssistantOfflineGeneration`;任务已在上游结束时上游返回 400 `FAILED_PRECONDITION`,视为已停止;其他失败以 WARN 记录 “Build 写代码助手取消任务失败”,字段为 `account`、`method`、`applet` 与 `error`
+- 任务流正文关闭时结束请求,包括正常读完、客户端断开与停止序列截断;回复完整结束时写入续接位置并发送回复后的伴随请求,否则删除本轮续接的续接位置;每轮无论成功、取消或失败都在后台发送 `MakerSuiteService/Log`;生成服务停止时尚未发出的伴随请求不再发送
+- 已启动任务、流没有正常解码完成且任务没有以失败步骤结束时,在后台以独立的 1 分钟期限发送取消请求;任务已在上游结束(`FAILED_PRECONDITION` 或 `NOT_FOUND`)视为已停止;其他失败以 WARN 记录 “Build 写代码助手取消任务失败”,字段为 `account`、`method`、`applet` 与 `error`
## 6. 任务流
-响应根数组的 field 1 是消息列表,之后可带 google.rpc 状态 `[code, message, details?]`。下例为一次完整的纯问答,消息 1 是用户轮回显,消息 2 是完成的模型轮:
+响应根数组的 field 1 是消息列表,之后可带 google.rpc 状态 `[code, message, details?]`。下例为 `legacy` 的一次完整纯问答,消息 1 是用户轮回显,消息 2 是完成的模型轮:
```json
[[
@@ -459,7 +518,7 @@ WAA binding 与 Playground `GenerateContent` 相同:contents 各 Part 依次
]]
```
-消息为 `[null, null, [步骤...], trajectory ID]`。每条消息带若干步骤的当前快照,同一条消息可以同时含用户轮回显与模型轮。步骤字段:
+`legacy` 的消息为 `[null, null, [步骤...], trajectory ID]`,`agency` 的消息为 `[[步骤...], trajectory ID, 游标, 是否还有后续分段, [交互 ID, 游标]]`,两者的步骤字段相同。每条消息带若干步骤的当前快照,同一条消息可以同时含用户轮回显与模型轮。步骤字段:
| field | 内容 |
| ---: | --- |
@@ -479,8 +538,8 @@ Part 的 field 2 为文本,field 13 为 `1` 或 `true` 时是思考。只修
解码:
-1. 消息列表中每出现一个完整元素立即解码;消息 field 3 为 `null` 时跳过
-2. 每个步骤读取序号与状态,二者缺失或类型不符时返回带路径的协议错误。field 6 非空时:
+1. 消息列表中每出现一个完整元素立即解码;消息的步骤列表为 `null` 时跳过
+2. 每个步骤读取序号与状态,缺失或类型不符时返回带路径的协议错误;`agency` 的步骤可以没有序号,其中状态为 `1`、没有对话轮与工具动作的是流末尾的游标帧,跳过。field 6 非空时:
- 状态为 `3` 的步骤跳过
- 其余步骤在本轮已输出函数调用时,回复在调用处结束
- 否则返回上游错误 “生成步骤失败: <消息>”,详情中与消息不同的文字以 `;` 接在后面,带额度标记时为 HTTP 429
@@ -503,11 +562,11 @@ Part 的 field 2 为文本,field 13 为 `1` 或 `true` 时是思考。只修
- `ask_question` 的问题为说明中交回函数调用的那句时不输出;此时本轮还没有输出函数调用且没有待闭合的调用代码块,则记为 `malformed_function_call`
- 请求声明了函数且本轮还没有输出函数调用时,步骤执行了 `search_web` 与 `ask_question` 以外的工作区内置工具,则停止读取该任务后续步骤
8. 状态为 `1` 的步骤含模型轮时,回复记为已完成。本轮在以下情况结束,之后不再读取后续消息与流尾状态:
- - 消息中最后一个步骤状态为 `1`、含非思考正文且 field 10 为空:本轮回复结束
+ - `legacy` 的消息中最后一个步骤状态为 `1`、含非思考正文且 field 10 为空:本轮回复结束;`agency` 读到游标帧与流结束
- 输出函数调用之后模型继续输出非空白正文、调用了被禁止的工作区内置工具、或发出交回函数调用的 `ask_question` 而没有函数调用:本轮任务在该步骤处结束,任务流关闭后取消生成任务
- 输出函数调用之后的步骤失败:本轮回复同样在调用处结束;任务已经结束,不再取消
9. 消息列表结束后读取流尾状态:code 0 为成功,其他 code 按“错误正文与状态码”的表换算 HTTP 状态。上游有时在模型步骤仍为状态 `2` 时正常结束消息列表:
- - 此时以同一任务 ID 与应用再请求一次 `StreamCodeAssistantOfflineGeneration`;已完成的任务立即返回状态为 `1` 的最终快照与用量,按同一组规则继续解码,已输出的正文与函数调用不重复输出
+ - 此时重连任务流一次:`legacy` 以同一任务 ID 与应用再请求 `StreamCodeAssistantOfflineGeneration`,`agency` 以同一 trajectory、最新游标与空的对话轮再请求 `StreamRunAgentTask`;`agency` 的消息标明还有后续分段时同样重连,最多 3 次。已完成的任务立即返回状态为 `1` 的最终快照与用量,按同一组规则继续解码,已输出的正文与函数调用不重复输出
- 重新打开的任务流仍在模型步骤完成前结束时,已解出函数调用或写出正文则以已有内容结束本轮,任务流关闭后取消生成任务
- 这种情况下本轮不写入续接位置,下一轮开启新 trajectory 并转录历史
10. 本轮回复结束或流关闭时回复已完成:依次输出暂缓的文本、记录的搜索 grounding、用量之和,再以 `stop` 结束(无法解码的 `function_calls` 块或调用了被禁止的工作区内置工具且没有解出函数调用时为 `malformed_function_call`);回复没有完成、也没有函数调用与正文时返回协议错误 “流结束前没有完成的模型回复”
@@ -560,36 +619,34 @@ HTTP 非 200 响应解码为协议错误,保留 HTTP 状态、google.rpc code
| 上游 RPC 或附件上传返回非 200 | 换号与冷却 |
| 流尾状态非 0 | 换号与冷却 |
| 伴随请求失败 | WARN 日志 |
-| 步骤失败 | HTTP 502 或 429 |
+| 步骤失败 | HTTP 502、429 或 403 |
| 应用 ID、任务 ID、trajectory ID 缺失 | 协议错误,HTTP 502 |
| 流结构不符 | 协议错误,HTTP 502 |
| 流关闭时没有完成的回复、函数调用与正文 | 协议错误,HTTP 502 |
-- 上游 RPC 指应用与云项目 RPC、`CodeAssistantOffline` 与任务流。非 200 响应与流尾状态按“错误正文与状态码”解码与换算,冷却 scope 为 `-build` 模型 ID;首个语义事件之后的错误以流内 error 结束
-- `CodeAssistantOffline` 返回 404 时,先按“对话与应用”重新打开或新建应用
+- 上游 RPC 指应用与云项目 RPC、`StreamRunAgentTask`、`CodeAssistantOffline` 与任务流。非 200 响应与流尾状态按“错误正文与状态码”解码与换算,冷却 scope 为 `-build` 模型 ID;首个语义事件之后的错误以流内 error 结束
+- `StreamRunAgentTask` 或 `CodeAssistantOffline` 返回 404 时,先按“对话与应用”重新打开或新建应用
- 伴随请求失败只记录日志,本轮回复照常返回
-- 步骤失败指步骤 field 6 非空、状态不是 `3` 且本轮还没有输出函数调用:返回 HTTP 502,消息为 “生成步骤失败: <上游消息>”,按 5xx 处理
+- 步骤失败指步骤 field 6 非空、状态不是 `3` 且本轮还没有输出函数调用:默认返回 HTTP 502,消息为 “生成步骤失败: <上游消息>”,按 5xx 处理;`agency` 流中出现先发通用失败帧、后续帧(`step[11]=null`)带 `detail[5]=="ACCOUNT_VERIFICATION_REQUIRED"` 与验证链接时,合并两帧并映射为 HTTP 403 / google.rpc code 7(`Metadata["link"]` 保留验证页地址),按账户需要验证处理而不报 502
- 步骤失败带额度标记时为 HTTP 429:通用额度按短期限额冷却,每用户额度按无恢复时间的套餐限额递增冷却
## 8. 实现位置
| 路径 | 职责 |
| --- | --- |
-| `internal/aistudio/assistant.go` | 写代码助手请求 |
-| `internal/aistudio/assistant_stream.go` | 写代码助手任务流解码 |
-| `internal/aistudio/assistant_applet.go` | 写代码助手应用 RPC |
-| `internal/aistudio/assistant_session.go` | 应用与续接位置 |
+| `internal/aistudio/assistant.go` | 写代码助手的目录条目派生、附件改写、双协议请求编码、协议选择、提交目标、追加用户轮与取消 |
+| `internal/aistudio/assistant_stream.go` | 写代码助手 `agency`/`legacy` 任务流解码(含函数调用代码块、提问与网页搜索步骤)与验证错误映射 |
+| `internal/aistudio/assistant_applet.go` | 账户应用的打开、新建、云项目与 API key、应用 RPC 的 proof、每轮 `Log` 与后置伴随让位 |
+| `internal/aistudio/assistant_session.go` | 账户运行状态中的应用与续接位置(含 `cursor`、`interaction_id`、`protocol`)、对话所在账户 |
+| `internal/camoufoxnative/page_flags.go` | 官网页面 `TSDtV` 布尔标志 `45831005` 官方结构解析 |
+| `internal/aistudio/runtime_native.go` | Build 受保护生成 RPC 的 `RunProof` 与 `Priority: u=0` |
| `internal/aistudio/transport_http.go` | 写代码助手附件上传 |
| `internal/aistudio/models.go` | 能力码 48 与 `-build` 条目追加 |
| `internal/aistudio/channel.go` | `assistant` 通道与单账户串行 |
-| `internal/aistudio/service.go` | binding 与 proof field |
+| `internal/aistudio/service.go` | binding、proof field 与热更新协议模式 |
| `internal/aistudio/upload.go` | 保留内联附件 |
-| `internal/app/runtime.go` | 对话所在账户优先 |
-
-- `assistant.go`:写代码助手的目录条目派生、附件改写、`CodeAssistantOffline` 编码、提交目标、追加用户轮与取消
-- `assistant_stream.go`:写代码助手任务流的解码,含函数调用代码块、提问与网页搜索步骤
-- `assistant_applet.go`:账户应用的打开、新建、云项目与 API key、伴随请求与应用 RPC 的 proof
-- `assistant_session.go`:账户运行状态中的应用与 trajectory 续接位置、对话所在账户
+| `internal/app/runtime.go` | 对话所在账户优先与 `BUILD_CHAT_PROTOCOL` 热配置传递 |
+| `internal/config/config.go` | `BUILD_CHAT_PROTOCOL` 解析与校验 |
## 9. Build 应用代理通道(已停用)
diff --git a/docs/development.md b/docs/development.md
index 92df2bdc..d9a60ccb 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -371,6 +371,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等
| `GENERATE_CONTENT_ACCOUNTS` | 迁移模型改走 GenerateContent 的账户 | 空 |
| `BUILD_NATIVE_NONSTREAM` | Build 非流式优先原生单次调用 | `true` |
| `BUILD_CHAT_MODELS` | 提供 `-build` 对话模型 | `true` |
+| `BUILD_CHAT_PROTOCOL` | `-build` 对话模型使用的上游协议 | `auto` |
| `NONSTREAM_KEEPALIVE` | 非流式请求保活 | `true` |
| `FAKE_STREAM` | 假流式输出 | `false` |
| `YOUTUBE_LINKS` | YouTube 链接作为视频发送 | `false` |
@@ -414,6 +415,7 @@ Camoufox 运行中与服务的 WebDriver BiDi 连接断开时,服务最多等
- `GENERATE_CONTENT_ACCOUNTS`:逗号分隔的账户 ID;模型目录 field 79 为 kind `2` 且 background 为真(`interaction_model` 与 `interaction_task`)的模型在这些账户上改走 `GenerateContent`,其余模型与账户不变;保存后立即生效
- `BUILD_NATIVE_NONSTREAM`:启用 Build 通道时,非流式请求优先选择 Build 原生单次调用
- `BUILD_CHAT_MODELS`:为 `false` 时公开目录不列出 `-build` 条目,`-build` 模型的请求返回 404;管理端目录照常列出;保存后立即生效
+- `BUILD_CHAT_PROTOCOL`:`-build` 对话模型使用的上游协议,取值 `auto`(默认,按账户页面启动数据 `TSDtV` 标志 `45831005` 自适应选择,缺省走 `legacy` 并告警一次)、`agency`(固定走 `AppletGenerationService/StreamRunAgentTask`)或 `legacy`(固定走 `MakerSuiteService/CodeAssistantOffline`);无效值提示并按 `auto` 运行,出错不回退到另一套协议;保存后下一次请求生效
- `NONSTREAM_KEEPALIVE`:非流式请求等待结果期间每 10 秒写出一个换行
- `FAKE_STREAM`:流式请求按非流式取得完整结果后再以流式输出
- `YOUTUBE_LINKS`:用户消息文本中的 YouTube 链接作为视频外部媒体发送
@@ -760,6 +762,7 @@ Worker 容量由热池目标、活动上限和单账户并发共同约束。
| Gemini | `GET /v1beta/models`、`GET /v1beta/models/{model}`、`POST /v1beta/models/{model}:generateContent`、`:streamGenerateContent`、`:countTokens`、`:embedContent`、`:batchEmbedContents`、`:predictLongRunning`、`GET /v1beta/operations/{id}` |
| Gemini Files | `POST /upload/v1beta/files`、`GET /v1beta/files`、`GET/DELETE /v1beta/files/{file}` |
| Realtime | `GET /v1/live`、`GET /v1/robotics/stream` |
+| Gemini Live | `GET /ws/google.ai.generativelanguage.<版本>.GenerativeService.BidiGenerateContent` |
管理端路由:
@@ -874,7 +877,7 @@ API 试用页位于 `web/src/playground/`,路由与官网相同(`/prompts/ne
Gemini 端点返回的语音 `audio/L16` 在页面封装为 WAV。
-日志页保留最近 2000 条事件,按请求与运行阶段合并后先显示最近 200 行。关闭自动滚动时,当前首行保持固定,新日志追加在末尾。请求详情与阶段步骤在首次展开时渲染。
+日志页保留最近 10000 条事件,按请求与运行阶段合并后先显示最近 200 行。关闭自动滚动时,当前首行保持固定,新日志追加在末尾。请求详情与阶段步骤在首次展开时渲染。
## 5. 协议实现
diff --git a/docs/protocol.md b/docs/protocol.md
index 0bc41cec..fb94d0b9 100644
--- a/docs/protocol.md
+++ b/docs/protocol.md
@@ -25,7 +25,7 @@ MakerSuite 请求使用以下公共头:
| `x-goog-api-key` | AI Studio 首页或当前官网请求动态值 |
| `x-goog-authuser` | 当前账户官网请求 |
| `x-aistudio-visit-id` | 首页初始化或当前官网请求 |
-| `x-aistudio-g1-tier` | `GetAiStudioBenefitTier` 返回值映射为 `TIER0`、`TIER1` 或 `TIER2` |
+| `x-aistudio-g1-tier` | Pro 与 Ultra 账户由 `GetAiStudioBenefitTier` 返回值映射为 `TIER1` 或 `TIER2`,Free 与 Plus 账户不带 |
| `x-goog-ext-519733851-bin` | 当前官网请求动态值;SpiderMonkey WAA 后端由 `GetLoggingContext` 编码 |
| `authorization` | 三段 SAPISID 签名 |
| `cookie` | 当前账户对目标 RPC 可见的 Cookie |
@@ -135,7 +135,7 @@ Google 对部分账户强制设备绑定会话。OAuthMultilogin 响应的 `devi
| `refresh_url` | `/RotateBoundCookies` |
| 绑定的 Cookie | `__Secure-1PSIDTS`、`__Secure-3PSIDTS`、`__Secure-1PSIDRTS`、`__Secure-3PSIDRTS` |
-会话以同一把设备绑定密钥刷新,不刷新时签发约 2 小时后失效。服务在 Worker 启动、普通 RPC、受保护 RPC 与 Live 建连之前检查绑定 Cookie,最早到期的一项剩余不足 2 分钟时按 Chromium `RegistrationFetcher` 刷新:
+会话以同一把设备绑定密钥刷新:每次签发的 `__Secure-1PSIDRTS` 与 `__Secure-3PSIDRTS` 有效期为 600 秒(10 分钟),不刷新时会话在约 2 小时后失效。服务在 Worker 启动、普通 RPC、受保护 RPC、Live 建连与页面重新载入之前,以及常驻 Worker 运行期间每 30 秒在后台检查绑定 Cookie,最早到期的一项剩余不足 2 分钟时按 Chromium `RegistrationFetcher` 刷新:
1. `POST` 刷新地址并带 `Sec-Secure-Session-Id`,服务端返回 `403` 与 `Secure-Session-Challenge`
2. 以设备密钥签发 header 为 `{"alg":"ES256","typ":"dbsc+jwt"}`、payload 为 `{"jti":""}` 的 JWT,放入 `Secure-Session-Response` 重发
@@ -317,7 +317,7 @@ resource value 为 `{kind?,name?,mime?,size?,purpose?,created_at,video?:{model,s
| 0 | Free | 无 |
| 1 | Pro | `X-AIStudio-G1-Tier: TIER1` |
| 2 | Ultra | `X-AIStudio-G1-Tier: TIER2` |
-| 3 | Plus | `X-AIStudio-G1-Tier: TIER0` |
+| 3 | Plus | 无 |
官网为 `GenerateContent`、`CountTokens`、Interaction、Code Assistant 与 `StreamExtractVideoFrames` 注入该 header。模型 field 83 描述访问方式:`1` 为付费 API key,`3` 为 Pro/Ultra 订阅,`4` 为 Ultra 订阅。公开模型目录合并全部账户的实时 `ListModels` 记录;账户调度使用 AccessModes、BenefitTier 与成功调用历史选择具体账户。
@@ -388,7 +388,7 @@ snapshot 的底层输入是四槽数组,首槽承载 binding:
[{content: sha256(bindingPrompt)}, undefined, undefined, undefined]
```
-返回值是 `!` 开头的 proof。`GenerateContent`、`CreateInteractionStream`、`CreateInteraction` 与 `GetInteractionStream` 写入 field 5,Build 代理写入 field 3,Build 写代码助手 `CodeAssistantOffline` 写入 field 2,Bidi 的每个客户端 wire 写入 field 6;原请求的其他槽位保持不变。GenerateContent 按 contents 和 parts 原顺序以单个空格连接。
+返回值是 `!` 开头的 proof。`GenerateContent`、`CreateInteractionStream`、`CreateInteraction` 与 `GetInteractionStream` 写入 field 5,Build 代理写入 field 3,Build 写代码助手 `StreamRunAgentTask` 写入 field 4(binding 为 ` <文本或附件连接>`)、`CodeAssistantOffline` 写入 field 2,Bidi 的每个客户端 wire 写入 field 6;原请求的其他槽位保持不变。GenerateContent 按 contents 和 parts 原顺序以单个空格连接。
`Waa/Ping` 请求和成功响应:
@@ -428,7 +428,9 @@ field 1 是 `request_key`,field 2 是 `botguard_response`。正确 proof、损
| 22 | 23 | 模型阶段码:`1` UNSTABLE_EXPERIMENTAL、`2` EXPERIMENTAL、`3` PREVIEW、`4` STABLE、`5` LEGACY、`6` DEPRECATED、`7` RETIRED |
| 56 | 57 | 模型别名 |
| 64 | 65 | 主能力码 |
+| 65 | 66 | Live voice 列表 |
| 66 | 67 | TTS voice 列表 |
+| 67 | 68 | 实时翻译与转录的语言列表,每行 `[语言代码, 显示名]` |
| 70 | 71 | 视频配置 |
| 71 | 72 | thinking 默认配置 |
| 74 | 75 | 次能力码 |
@@ -438,6 +440,7 @@ field 1 是 `request_key`,field 2 是 `botguard_response`。正确 proof、损
| 78 | 79 | Interaction 配置:索引 2 为后台任务,索引 3 类型 `1` 为 agent、`2` 为模型 |
| 81 | 82 | 官网新建对话时默认开启的设置与工具的能力码 |
| 82 | 83 | 模型访问方式 |
+| 88 | 89 | Live 默认设置 `[默认 voice, null, null, 用途列表]` |
能力码映射:
@@ -480,6 +483,20 @@ field 1 是 `request_key`,field 2 是 `botguard_response`。正确 proof、损
每个主能力码都保留为 `capability_code_`,同时为上表中的已知码增加语义键;次能力码保留为 `secondary_capability_code_`;field 82 中默认开启的码保留为 `default_capability_code_`;field 79 的 kind 为 `1`(agent)或 `2`(模型)时带 `interactions_api`,按官网 `_.Ol`、`_.Pl`、`Rl`、`_.Sl` 换算为 `interaction_agent` / `interaction_model` 与 `interaction_stream`(非后台) / `interaction_task`(后台),其余未知 kind 走 `GenerateContent`。
+Live 模型的设置由主能力码决定:
+
+| 主能力码 | 设置 |
+| ---: | --- |
+| 39 | `enable_affective_dialog` |
+| 40 | `proactive_audio` |
+| 72 | `proactive_video` |
+| 100 | 会话中更新系统指令 |
+| 101 | 会话中更新工具 |
+| 46 与 56 都没有 | `turn_coverage` |
+
+- 模型没有对应能力码时,带上该设置或发送对应的会话中更新返回参数错误
+- 默认 voice 取 field 89 的第一项,没有时对话模型取 Live voice 列表的第一个,实时翻译模型不选 voice
+
图片与视频选项使用枚举码:
| 类型 | 码值映射 |
@@ -1537,10 +1554,12 @@ Live 纯文本与实时音乐使用模型 scope,Live 音频/图像和 Robotics
| 1 | 2 | generation configuration |
| 2 | 3 | 系统指令 `[[[null,""]]]`,setup 带 `system_instruction` 时写入 |
| 3 | 4 | tools;函数声明为一个 Tool,`google_search` 为 Tool `[null,null,null,[]]` |
+| 5 | 6 | RealtimeInputConfig `[null,null,null,turnCoverage]`,turn coverage:`1` 只含活动、`2` 含全部输入、`3` 含音频活动与全部视频;未设置时省略 |
| 6 | 7 | `[sessionToken]`;无 token 时 Live 对话与 Robotics 为 `[]`,实时翻译与转录省略 |
| 7 | 8 | 上下文窗口压缩 `[trigger_tokens,[target_tokens]]`,默认 `[104857,[52428]]`;实时翻译与转录省略 |
| 9 | 10 | 输入音频转录参数;空数组,实时转录的语言写在子索引 `7` |
| 10 | 11 | 固定空数组 |
+| 11 | 12 | ProactivityConfig `[proactiveAudio, proactiveVideo]`,开启的项为 `1`,只开 video 时为 `[null,1]`;都没有开启时省略 |
| 15 | 16 | timezone `[null,null,null,null,[zone]]` |
Live 对话与 Robotics 的 configuration 使用 18 槽数组:
@@ -1548,11 +1567,12 @@ Live 对话与 Robotics 的 configuration 使用 18 槽数组:
| JSON 索引 | 内容 |
| ---: | --- |
| 14 | 输出 modalities;TEXT=`[1]`、AUDIO=`[3]` |
-| 15 | Live voice `[[[""]]]`,默认 `Zephyr` |
+| 15 | Live voice `[[[""]]]`,默认取目录 field 89;`voice_` 或 `voicekey_` 开头的自定义声音为 `[[null,null,null,null,""]]` |
| 16 | thinking `[1,null,null,level]`;Live 取 setup `thinking_level`,省略时取模型目录的默认档位;Robotics 固定 High=`3` |
| 17 | MediaResolution:low=`1`、medium=`2`(默认)、high=`3` |
+| 19 | enable_affective_dialog,开启时为 `1`,数组延长到 20 槽;未开启时省略 |
-实时翻译模型不接受 MediaResolution,configuration 使用 31 槽:索引 13 为 `0`、14 为 `[3]`、30 为 TranslationConfig `[echoTargetLanguage 0/1, targetLanguageCode]`。实时转录模型只接受 TEXT 输出,configuration 为 `[null×14,[1]]`。两者均不带 voice 与 thinking。
+实时翻译模型不接受 MediaResolution,configuration 使用 31 槽:索引 13 为 `0`、14 为 `[3]`、30 为 TranslationConfig `[echoTargetLanguage 0/1, targetLanguageCode]`;选了 voice 时索引 15 为 `[[[""]],""]`,默认不选。实时转录模型只接受 TEXT 输出,configuration 为 `[null×14,[1]]`,不带 voice。两者均不带 thinking。
上游在 serverContent 索引 5、6 返回输入与翻译文本,实时转录在索引 10 返回当前累计的临时输入转写,映射为 `interim_input_transcription`,音频结束后在索引 5 返回最终输入转写。
@@ -1586,6 +1606,8 @@ Live 对话与 Robotics 的 configuration 使用 18 槽数组:
| `image` | index 2 / field 3 | realtime input index 3 保存 `[mime,base64]` |
| `media_end` | index 2 / field 3 | realtime input index 2 为 `1` |
| `tool_response` | index 3 / field 4 | 子消息 index 1 保存 repeated `[name,Struct,id,willContinue?]`,`will_continue` 为真时 index 3 为 `1` |
+| `client_content` | index 1 / field 2 | 子消息 index 0 保存 repeated turn `[parts,role?]`,part 为 `[null,text]`;index 1 为 `1` 表示 turn complete |
+| `context_update` | index 8 / field 9 | 子消息 index 0 为工具更新(`[tools]`,空数组 `[]` 清空工具,缺省表示不更新),index 2 为系统指令 `[[[null,text]]]` |
setup 与每个后续客户端 wire 都在发送前把 fresh WAA proof 写入外层 index `5` / field `6`。snapshot binding 输入:
@@ -1594,6 +1616,8 @@ setup 与每个后续客户端 wire 都在发送前把 fresh WAA proof 写入外
| setup | `models/`,随后依次追加系统指令与按声明顺序的每个 `name + " " + description`,各段以单个空格连接 |
| text、audio、image、media end | 空字符串 |
| tool response | 第一条 function response 的 call ID |
+| client content | 各 turn 的文本以单个空格连接 |
+| context update | 系统指令与按声明顺序的每个 `name + " " + description`,各段以单个空格连接 |
服务端业务 message 索引:
@@ -1618,9 +1642,27 @@ setup 与每个后续客户端 wire 都在发送前把 fresh WAA proof 写入外
| message index `4` 的子索引 `0` | tool cancellation,值为 repeated call ID |
| session resumption 子索引 `0/1` | token 与 resumable |
-- 对象状态错误形状为 `{"__sm__":{"status":[[[code,message]]]}}`
+- 对象状态错误形状为 `{"__sm__":{"status":[[[code,message]]]}}`,code 为 google.rpc.Code,不在下表中的 code 按协议证据错误结束
- 字符串 payload `"noop"`、`"close"`、`"stop"` 分别表示空操作、正常关闭与错误停止
+状态 code 换算的 HTTP 状态:
+
+| code | HTTP 状态 |
+| --- | ---: |
+| 3、9、11 | 400 |
+| 16 | 401 |
+| 7 | 403 |
+| 5 | 404 |
+| 6、10 | 409 |
+| 8 | 429 |
+| 2、13、15 | 500 |
+| 12 | 501 |
+| 14 | 503 |
+| 4 | 504 |
+
+- 没有输入约 2 分钟后上游以 code 10 与 `Session closed due to client inactivity.` 结束会话
+- 实时翻译会话持续约 10 分钟时上游以 code 14 与 `The service is currently unavailable.` 结束会话
+
## 7. 公开端点、状态映射与实现
| 协议 | 端点 |
@@ -1645,9 +1687,10 @@ setup 与每个后续客户端 wire 都在发送前把 fresh WAA proof 写入外
| OpenAI 与 Anthropic 文件 | `POST /v1/files`、`GET /v1/files`、`GET /v1/files/{id}`、`GET /v1/files/{id}/content`、`DELETE /v1/files/{id}` |
| OpenAI 转录与翻译 | `POST /v1/audio/transcriptions`、`POST /v1/audio/translations` |
| 实时 WebSocket | `GET /v1/live`、`GET /v1/robotics/stream` |
+| Gemini Live | `GET /ws/google.ai.generativelanguage.<版本>.GenerativeService.BidiGenerateContent`,版本为 `v1beta`、`v1alpha` 或 `v1` |
| Gemini Interactions | `POST /v1beta/interactions`、`GET /v1beta/interactions/{id}`、`DELETE /v1beta/interactions/{id}`、`POST /v1beta/interactions/{id}/cancel`,`/v1` 前缀相同 |
| Gemini 文件 | `POST /upload/v1beta/files`、`GET /v1beta/files`、`GET /v1beta/files/{id}`、`DELETE /v1beta/files/{id}` |
-| Gemini 声音 | `GET /v1beta/voices`、`POST /v1beta/voices`、`GET /v1beta/voices/{id}`、`DELETE /v1beta/voices/{id}` |
+| Gemini 声音 | `GET /v1beta/voices`、`POST /v1beta/voices`、`POST /v1beta/voices:improvePrompt`、`GET /v1beta/voices/{id}`、`DELETE /v1beta/voices/{id}` |
动态路由的注册形状如下,端点表中的 `{id}` 表示对应资源标识:
@@ -1819,7 +1862,7 @@ GET/DELETE /v1beta/files/{file}
| `AdminStatus` | `state`、`running`、`ready`、`version`、`active_requests`、`accounts`、`camoufox`、`chrome_import`、可选 `transition`、可选 `transition_since`、`time` |
| `AdminAccountCounts` | `total`、`ready`、`busy`、`cooldown`、`auth_required` |
| `AdminCamoufox` | `ready`、`preparing`、可选 `download`(`received`、`total`)、可选 `error` |
-| `AdminAccount` | `id`、`label`、`enabled`、`state`、`proxy`、`egress`、`locale`、`timezone`、`models`、`benefit_tier`、`message`、`active_requests`、可选 `pairing_renewed_at`、可选 `transition`、可选 `transition_step`、可选 `transition_index`、可选 `transition_total`、可选 `transition_since`、可选 `catalog_error` |
+| `AdminAccount` | `id`、`label`、`enabled`、`state`、`proxy`、`egress`、`locale`、`timezone`、`models`、`callable_models`、`benefit_tier`、`message`、`active_requests`、可选 `pairing_renewed_at`、可选 `transition`、可选 `transition_step`、可选 `transition_index`、可选 `transition_total`、可选 `transition_since`、可选 `catalog_error` |
| `PromptSummary` | `id`、`title`、`model`、`description`、`created_at`、`updated_at`、可选 `turns`、`tokens` |
| `Prompt` | `PromptSummary` 的字段与 `data` |
| `SystemInstructionPreset` | `id`、`title`、`text` |
@@ -1855,7 +1898,7 @@ GET/DELETE /v1beta/files/{file}
- `AdminStatus.transition` 是生成服务进行中的启动或停止步骤:启动为 `probe_proxies`(检测代理池)、`wait_camoufox`(等待 Camoufox 下载)、`wait_catalog`(等待首个账户读取模型目录)、`start_prewarm`(开始预热 Worker),停止为 `cancel_requests`(停止在途请求)、`wait_catalog_stop`(等待模型目录同步停止)、`close_workers`(关闭 Worker);`transition_since` 是进入该步骤的时刻,步骤变化时推送 `status` 事件;`transition` 为停止步骤时清理还在进行,与 `state` 无关;`time` 是生成这份状态的服务端时刻,管理页以它与本机时钟的差换算各阶段的已用时间
- `AdminStatus.state` 为 `STOPPED`、`LAUNCHING` 或 `RUNNING`;`running` 只在 `RUNNING` 为 true;`ready` 要求 `RUNNING` 且至少一个账户处于 ready 或 busy;`version` 来自构建信息;`active_requests` 是当前进程请求注册表数量;`camoufox.ready` 表示本机已有所需版本的 Camoufox,下载进行时 `camoufox.download` 给出已收与总字节,续传时已收字节包含已下载部分,总字节未知时为 0
- `chrome_import` 表示当前构建能否从本机 Chrome 导入账户(Windows amd64 为 true),管理页据此显示 Chrome 导入
-- `AdminAccount.message` 保存当前状态原因,`models` 是该账户实时目录 ID,`egress` 是账户实际使用的出口代理(账户固定代理或代理池绑定的代理,都没有时为空),管理页按它分组显示账户出口
+- `AdminAccount.message` 保存当前状态原因,`models` 是该账户实时目录 ID,`callable_models` 是该账户按选号的同一判定可以调用的模型 ID(按账户权益与方法、`MODEL_ACCOUNTS` 绑定的账户、`MODEL_CHANNELS` 限定的通道与已启用的通道判断,不看账户的启用、状态与冷却,没有目录时为空数组),管理页的号池额度按它计数,`egress` 是账户实际使用的出口代理(账户固定代理或代理池绑定的代理,都没有时为空),管理页按它分组显示账户出口
- `until` 与 `started_at` 使用 RFC 3339 JSON time
`GET /api/usage` 的参数:
@@ -2229,18 +2272,18 @@ Gemini `GET /v1beta/models` 返回 `{"models":[...]}`,单模型路由直接返
字段为 `name`、`baseModelId`、`displayName`、`description`、`supportedGenerationMethods`、`inputTokenLimit`、`outputTokenLimit`、可选 `temperature`、`maxTemperature`、`topP`、`topK`、`modelStage`、`thinking`、`thinkingLevels`、`defaultThinkingLevel`、`capabilities`、`capabilityOptions`、`accessModes`、`paid`、`channels`:
- `baseModelId` 为模型 ID
-- `supportedGenerationMethods` 为上游目录中该模型的方法里本服务提供的 `generateContent`、`countTokens`、`createCachedContent`、`embedContent`、`batchEmbedContents`、`predict`、`predictLongRunning`,按上游顺序
+- `supportedGenerationMethods` 为上游目录中该模型的方法里本服务提供的 `generateContent`、`countTokens`、`createCachedContent`、`embedContent`、`batchEmbedContents`、`predict`、`predictLongRunning`、`createDecision`、`bidiGenerateContent`,按上游顺序;只有 `bidiGenerateContent` 的 Live 模型列出它,调用入口是标准 Live 端点
- `modelStage` 为 ListModels field 23 或 Build 目录给出的模型阶段
生成服务未进入 `RUNNING` 且还没有任何账户目录时,模型列表与单模型查询返回 503,与生成请求相同。
`GET /v1/models/{model}` 与 `GET /v1beta/models/{model}` 接受 `models/` 前缀;这两个模型查询入口以及生成、计数、视频、转录与 Bidi 同时接受 canonical ID 和 `capability_options.aliases` 中的 alias;alias 在调度和发送上游前换成对应的 canonical ID。
-管理模型中的 `description`、token limits、capabilities、capability options、access modes 与 false `paid` 使用 `omitempty`;OpenAI 和 Gemini 响应始终包含身份、methods 与 token limits,并在 map/slice 非空或 `paid=true` 时增加对应扩展字段。
+管理模型中的 `description`、token limits、capabilities、capability options、access modes、false `paid` 与空的 `unavailable` 使用 `omitempty`;OpenAI 和 Gemini 响应始终包含身份、methods 与 token limits,并在 map/slice 非空或 `paid=true` 时增加对应扩展字段。
管理目录合并全部账户的上游实时模型集合,顺序沿用各账户 `ListModels` 的上游顺序:只出现在后一个账户目录中的模型排在它在该目录中的前一个模型之后,没有前一个已知模型时排在该目录首个已知模型之前,该目录没有已知模型时排在末尾;在此顺序上依次排列有可用通道的普通模型、agent(`interaction_agent`,如 Antigravity 与 Deep Research,不论有无可用通道)与没有可用通道的普通模型。
-公开目录保留当前公开协议承载其调用方法、且已启用通道可以提供的模型;启用 Build 通道时同时包含 Build 独有的可生成模型,`channels` 列出可调用该模型的通道,见 [Build 通道](build.md)。启用账户的权益都不满足 AccessModes 的模型同样列出,不含 `channels`。短期冷却和忙碌状态由请求调度处理。
+公开目录保留当前公开协议承载其调用方法、且已启用通道可以提供的模型;启用 Build 通道时同时包含 Build 独有的可生成模型,`channels` 列出可调用该模型的通道,见 [Build 通道](build.md)。启用账户的订阅权益都不满足 AccessModes 的模型同样列出,不含 `channels`。本服务调用不了的模型不列入公开目录:`access_modes` 非空且取值都是 1(只对付费 API key 开放)的模型,与没有任何方法的模型;管理目录照常列出它们,`unavailable` 为 `paid_api_key` 或 `no_methods`,不含 `channels`,排在最后。短期冷却和忙碌状态由请求调度处理。
主要请求格式:
@@ -2937,20 +2980,21 @@ delta 联合类型为 `text_delta{text}`、`citations_delta{citation}`、`thinki
### Gemini 声音
-`/v1beta/voices` 与 Gemini API VoicesService 同形,字段为 snake_case。官网语音页的 MakerSuite `CreateVoice`、`ListVoices`、`GetVoice` 与 `DeleteVoice` 需要 Gemini API 付费层级的 API key,Google AI 方案账户不带 API key 调用时返回 400 `INVALID_ARGUMENT`;服务自己保存 prompted 声音,在预置音色上以风格提示生成语音:
+`/v1beta/voices` 与 Gemini API VoicesService 同形,字段为 snake_case。官网语音页的 MakerSuite `CreateVoice`、`ListVoices`、`GetVoice` 与 `DeleteVoice` 需要 Gemini API 付费层级的 API key,Google AI 方案账户不带 API key 调用时返回 400 `INVALID_ARGUMENT`;服务自己保存 prompted 与 replicated 声音,在预置音色上以风格提示生成语音:
| 操作 | 行为 |
| --- | --- |
-| 创建 | `voice.type` 为 `prompted`,`prompted.input` 必填,`store` 省略或为 `true` |
+| 创建 | `voice.type` 为 `prompted` 或 `replicated`;prompted 的 `prompted.input` 必填,`store` 省略或为 `true`,`voice.base_voice`(服务扩展字段)指定 Remix 的基础预置音色名或已保存的自定义声音 ID,省略时按描述挑选音色 |
| 挑选音色 | `gemini-flash-lite-latest` 从 Voice Design 模型的目录音色中排出最贴近描述的 3 个互不相同的音色,同一模型与描述的创建依次取下一个,排名保留到服务重启 |
| 试听 | 以描述为 SpeechMetadata style,在该音色上朗读文本模型按人设写的一句台词,`sample_audio` 为 24 kHz WAV |
| 保存 | `runtime/voices/.json` 与 `.wav`,ID 为 `voice_` 加 16 位十六进制 |
| 列出 | 自定义声音(最新的在前)后接 Voice Design 模型的目录音色(生成服务未启动时只有自定义声音),按 `language_code`、`region_code`、`accent`、`gender`、`pitch`、`persona`、`context`、`type` 与 `search` 筛选,`page_size` 默认 50、最多 1000 |
| 读取与删除 | `GET` 返回带 `sample_audio` 的声音,声音不存在时返回 404 `NOT_FOUND` |
-| 复刻 | `type` 为 `replicated` 时返回 400 `FAILED_PRECONDITION` |
+| 复刻 | `replicated.source_audio` 与 `replicated.consent_audio` 必填(`data` 为 Base64,`mime_type` 如 `audio/wav`);`gemini-flash-lite-latest` 听取样本录音,选出最接近的预置音色并写出英文描述,之后与 prompted 声音相同,试听台词为 `Hi there! I am your newly replicated voice ready for text-to-speech.`,`type` 为 `replicated`;确认录音只检查存在 |
+| 改写描述 | `POST /v1beta/voices:improvePrompt`,请求 `{"input":"<描述>"}`,响应 `{"input":"<改写后的描述>"}`,文本模型没有返回正文时原样返回描述 |
- Voice Design 模型为请求的 `voice.model`,省略时为目录中第一个带 `speech_metadata` 与 `speech_route` 能力的模型
-- 自定义声音的 `base_voice` 是生成时使用的预置音色
+- 自定义声音的 `base_voice` 是生成时使用的预置音色;Remix 指定的基础是自定义声音时,沿用它的预置音色,新描述写在它的风格之后
- Gemini `voiceConfig.voice` 或 `prebuiltVoiceConfig.voiceName`、OpenAI Speech `voice` 与 Interactions `speech_config` 的 `voice` 引用自定义声音(可带 `voices/` 前缀)时,请求改写为它的预置音色,描述写在对应台词的 style 之前;多说话人请求只改写 speaker 与该说话人相同的台词;未保存的 `voice_...` 与 `voicekey_...` 写入 VoiceConfig field 5 发给上游
### Gemini Interactions
@@ -3768,6 +3812,50 @@ duration、aspect ratio 与 resolution 的取值:
- 生成失败时 Gemini operation 为 `done` 并带 `error:{code,message,status}`,OpenAI 对象 status 为 `failed` 并带 `error:{"code":"video_generation_failed","message"}`
- 服务重启时尚未完成的任务为已结束且没有结果,说明为 `服务重启前任务没有生成完成`
+### 标准 Live 端点
+
+`GET /ws/google.ai.generativelanguage.<版本>.GenerativeService.BidiGenerateContent` 是 Gemini API 的 Live WebSocket,官方 SDK 把基础地址换成本服务即可连接;路径以 `//ws/` 开头时(JS SDK 以带尾斜杠的基础地址拼出)先去掉多出的斜杠。API key 的来源同 `/v1beta`。会话、账户选择与换号同 `/v1/live`,Live 模型由目录的 `bidiGenerateContent` 方法选账户。
+
+客户端帧按 proto3 JSON 解码,字段名接受驼峰与下划线两种写法,每帧只有一个消息字段,首帧为 `setup`。服务端消息以 WebSocket 二进制帧发送。客户端消息:
+
+| 消息 | 内容 |
+| --- | --- |
+| `setup` | 换成 `/v1/live` 的 setup,字段对应见下表 |
+| `clientContent` | `turns` 的文本 part 与 `turnComplete` |
+| `realtimeInput` | `text`;`audio`、`video` 与 `mediaChunks` 中的 `audio/pcm`(单声道,采样率取 `rate` 参数,省略为 16 kHz,其他采样率重采样到 16 kHz)与图片(`image/jpeg` 原样发送,`image/png`、`image/webp` 转成 JPEG);`audioStreamEnd` |
+| `toolResponse` | `functionResponses` 的 `id`、`name`、`response`、`willContinue` |
+| `contextUpdate` | `systemInstruction` 与 `tools` |
+
+| setup 字段 | `/v1/live` setup |
+| --- | --- |
+| `model` | `model`,去掉 `models/` 前缀 |
+| `generationConfig.responseModalities` | `output_modalities` |
+| `generationConfig.speechConfig.voiceConfig` | `voice`,取 `prebuiltVoiceConfig.voiceName` 或 `voice` |
+| `generationConfig.speechConfig.languageCode` | 与 `translationConfig` 同时出现时随目标语言发送 |
+| `generationConfig.mediaResolution`、`thinkingConfig.thinkingLevel` | `media_resolution`、`thinking_level` |
+| `generationConfig.enableAffectiveDialog` | `enable_affective_dialog` |
+| `generationConfig.translationConfig` | `translation` |
+| `systemInstruction` | `system_instruction`,文本 part 以换行连接 |
+| `tools` | `tools` 与 `google_search`,只含 `functionDeclarations` 与 `googleSearch` |
+| `realtimeInputConfig.turnCoverage` | `turn_coverage` |
+| `proactivity` | `proactive_audio`、`proactive_video` |
+| `sessionResumption.handle` | `session_token` |
+| `contextWindowCompression` | `context_window_compression`,`slidingWindow.targetTokens` 为 `target_tokens` |
+| `inputAudioTranscription` | 输入转写;`languageCodes`、`customVocabulary` 与 `mode: SMART` 对应 `transcription` |
+| `outputAudioTranscription` | 请求输出转写事件 |
+
+- AI Studio 的 Live 不提供的 `speechConfig.voiceConfig.replicatedVoiceConfig`、不带 `translationConfig` 的 `speechConfig.languageCode`、`realtimeInputConfig.automaticActivityDetection`、`activityHandling` 与 `realtimeInput.activityStart`、`activityEnd`,以参数错误结束连接,原因为 `AI Studio Live does not provide <字段>`
+- `systemInstruction` 与 `clientContent.turns` 只取文本 part,含其他 part 时以参数错误结束连接;`tools` 中 `functionDeclarations` 与 `googleSearch` 之外的工具同样以参数错误结束连接
+- 服务端消息为 `setupComplete`、`serverContent`(`modelTurn` 的文本与 `inlineData` part、`inputTranscription`、`outputTranscription`、`interimInputTranscription`、`generationComplete`、`turnComplete`、`interrupted`)、`toolCall`(`functionCalls` 的 `id`、`name`、`args`)、`toolCallCancellation`(`ids`)与请求了 `sessionResumption` 时的 `sessionResumptionUpdate`(`newHandle`、`resumable`);`inputTranscription` 与 `outputTranscription` 只在 setup 请求了对应转写时发送
+- 会话结束与出错都以 WebSocket 关闭帧表示,关闭码与官方 Live API 一致,原因为英文错误文本,超过 123 字节时保留放得下的完整句子:
+
+| 结束原因 | 关闭码 |
+| --- | ---: |
+| 正常结束 | 1000 |
+| 请求无效,含模型不支持的设置(HTTP 400 类) | 1007 |
+| 认证、权限,模型不存在或没有 `bidiGenerateContent` 方法(HTTP 401、403、404 类) | 1008 |
+| 其他错误 | 1011 |
+
### Live 与 Robotics 公开帧
连接升级后 10 秒内发送 setup:
@@ -3785,7 +3873,11 @@ duration、aspect ratio 与 resolution 的取值:
"media_resolution": "medium",
"thinking_level": "minimal",
"context_window_compression": {"trigger_tokens": 104857, "target_tokens": 52428},
- "google_search": false
+ "google_search": false,
+ "proactive_audio": false,
+ "proactive_video": false,
+ "enable_affective_dialog": false,
+ "turn_coverage": "only_activity"
}
```
@@ -3808,19 +3900,24 @@ setup 的生成设置:
| 字段 | 取值 | 上游位置 |
| --- | --- | --- |
| `system_instruction` | 文本 | setup field 3 |
-| `voice` | 声音名,默认 `Zephyr` | configuration 索引 15 |
+| `voice` | 声音名,默认取模型目录的默认 voice,实时翻译模型默认不选 | configuration 索引 15 |
| `media_resolution` | `low`、`medium`、`high`,默认 `medium` | configuration 索引 17 |
| `thinking_level` | `minimal`、`low`、`medium`、`high` | configuration 索引 16 |
-| `context_window_compression` | `{trigger_tokens,target_tokens}` | setup field 8 |
+| `context_window_compression` | `{trigger_tokens,target_tokens}`,缺省的一项取默认值 | setup field 8 |
| `google_search` | boolean | setup field 4 的 Google Search Tool |
-
-- 普通 Live 对话模型接受全部六项
-- 实时翻译模型只接受其中的 `system_instruction`,实时转录模型六项都不接受;带上不接受的项时返回 `invalid_request`
-- Robotics 与实时音乐模型不接受这六项,带上时返回 `invalid_request`
+| `proactive_audio` | boolean | setup field 12 的 `proactiveAudio` |
+| `proactive_video` | boolean | setup field 12 的 `proactiveVideo` |
+| `enable_affective_dialog` | boolean | configuration 索引 19 |
+| `turn_coverage` | `only_activity`、`all_input`、`audio_activity_and_all_video` | setup field 6 |
+
+- 普通 Live 对话模型接受全部十项
+- 实时翻译模型只接受其中的 `system_instruction` 与 `voice`,实时转录模型十项都不接受;带上不接受的项时返回 `invalid_request`
+- Robotics 与实时音乐模型不接受这十项,带上时返回 `invalid_request`
+- `proactive_audio`、`proactive_video`、`enable_affective_dialog` 与 `turn_coverage` 还要求模型目录带有对应的能力码,见 [ListModels](#listmodels)
- 系统指令按生成请求的系统提示规则改写后发送,并参与 setup 的 binding
- 上下文达到 `trigger_tokens` 时,上游把上下文缩减到 `target_tokens`
-setup 之后的客户端对象统一字段为 `type`、可选 `text`、`mime_type`、Base64 `data`、`tool_responses`、`weighted_prompts`、`music_config`、`playback_control`。各帧字段:
+setup 之后的客户端对象统一字段为 `type`、可选 `text`、`mime_type`、Base64 `data`、`tool_responses`、`system_instruction`、`tools`、`google_search`、`weighted_prompts`、`music_config`、`playback_control`。各帧字段:
| type | 字段 |
| --- | --- |
@@ -3829,6 +3926,7 @@ setup 之后的客户端对象统一字段为 `type`、可选 `text`、`mime_typ
| `image` | `mime_type:"image/jpeg"`、`data` |
| `media_end` | 无附加字段 |
| `tool_response` | `tool_responses:[{id,name,content,will_continue?}]` |
+| `context_update` | 可选 `system_instruction`、`tools`、`google_search` |
| `music_prompts` | `weighted_prompts:[{text,weight}]` |
| `music_config` | `music_config` 对象,字段同 Gemini API `LiveMusicGenerationConfig` |
| `playback` | `playback_control:"play"\|"pause"\|"stop"\|"reset_context"` |
@@ -3838,6 +3936,7 @@ setup 之后的客户端对象统一字段为 `type`、可选 `text`、`mime_typ
- `audio` 与 `image` 省略 `mime_type` 时分别使用 `audio/pcm` 与 `image/jpeg`
- `music_config` 的键可用 snake_case 或 camelCase
- 实时音乐会话只接受 `music_prompts`、`music_config`、`playback` 与 `close`,Live 与 Robotics 会话不接受这三种帧
+- `context_update` 在会话进行中更新系统指令与工具:缺省的字段不更新,`tools` 与 `google_search` 整体替换工具,`tools` 为空数组且 `google_search` 为假时清空工具;系统指令与工具的更新分别要求模型目录带有能力码 100 与 101
- `tool_response` 批量发送函数结果,保留调用的 `id` 与 `name`
- setup 的函数声明可带 `behavior`:`NON_BLOCKING` 的函数在模型继续对话时异步执行;对它的调用回复 `will_continue: true` 的中间结果后,同一调用还能继续回复,最后一次回复省略 `will_continue`
diff --git a/go.mod b/go.mod
index de2c169e..7acebb1d 100644
--- a/go.mod
+++ b/go.mod
@@ -5,13 +5,12 @@ go 1.27.4
require (
github.com/HugoSmits86/nativewebp v1.3.0
github.com/Mag1cFall/fhttp v0.7.3-chrome.1
- github.com/Mag1cFall/go-mp3 v0.1.1
github.com/Mag1cFall/go-sentencepiece v0.7.1
github.com/bogdanfinn/fhttp v0.7.3
github.com/bogdanfinn/tls-client v1.18.1
github.com/bogdanfinn/utls v1.8.2-barnius
github.com/brainplusplus/go-browserforge v0.1.0
- github.com/dlclark/regexp2/v2 v2.13.3
+ github.com/dlclark/regexp2/v2 v2.14.0
github.com/go-ego/gocc v0.10.0
github.com/godbus/dbus/v5 v5.2.4
github.com/gofrs/flock v0.13.2
@@ -21,16 +20,17 @@ require (
github.com/mattn/go-sqlite3 v1.14.53
github.com/mewkiz/flac v1.0.14
github.com/minio/selfupdate v0.6.0
- github.com/modelcontextprotocol/go-sdk v1.8.0
+ github.com/modelcontextprotocol/go-sdk v1.9.0
github.com/nationallibraryofnorway/whatwg-url v0.9.1
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
- github.com/shirou/gopsutil/v4 v4.26.10
+ github.com/shirou/gopsutil/v4 v4.26.11
github.com/thesyncim/gopus v0.2.11
github.com/tphakala/go-aac v0.7.2
+ github.com/tphakala/go-mp3 v0.4.0
github.com/vearutop/statigz v1.5.0
github.com/wailsapp/wails/v3 v3.1.0
- github.com/zaf/g711 v1.4.0
- golang.org/x/crypto/x509roots/fallback v0.0.0-20261123192653-4dc4fb521066
+ github.com/zaf/g711/v2 v2.0.1
+ golang.org/x/crypto/x509roots/fallback v0.0.0-20261202032733-168022f7de66
golang.org/x/image v0.48.0
golang.org/x/mod v0.43.0
golang.org/x/net v0.63.0
@@ -48,7 +48,7 @@ require (
github.com/bogdanfinn/quic-go-utls v1.0.13-utls // indirect
github.com/bogdanfinn/websocket v1.5.9-barnius // indirect
github.com/coder/websocket v1.8.14 // indirect
- github.com/ebitengine/purego v0.11.2 // indirect
+ github.com/ebitengine/purego v0.11.3 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/icza/bitio v1.1.0 // indirect
@@ -56,14 +56,14 @@ require (
github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d // indirect
github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 // indirect
github.com/molecule-man/go-brrr v1.2.0 // indirect
- github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect
+ github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
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/tphakala/simd v1.16.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
diff --git a/go.sum b/go.sum
index e526926e..14a70d11 100644
--- a/go.sum
+++ b/go.sum
@@ -4,8 +4,6 @@ github.com/HugoSmits86/nativewebp v1.3.0 h1:n1egtEzSV4KwFtealr7dzdYq1wI/uj/bOQ/Q
github.com/HugoSmits86/nativewebp v1.3.0/go.mod h1:YNQuWenlVmSUUASVNhTDwf4d7FwYQGbGhklC8p72Vr8=
github.com/Mag1cFall/fhttp v0.7.3-chrome.1 h1:POdoJg7im2sh3Z3xCbS1LjAfjAc3IllxpdeMWHi/IXk=
github.com/Mag1cFall/fhttp v0.7.3-chrome.1/go.mod h1:iIc18VAMMj/anflfuD2SB3OSx9jveuAUwnnM+pMt/uk=
-github.com/Mag1cFall/go-mp3 v0.1.1 h1:r/wBscYGXWpGdEhCQCcrHI36EDbNx6rtio2yv/Y547Y=
-github.com/Mag1cFall/go-mp3 v0.1.1/go.mod h1:/vhuC+guK5mKVhCBE8ZQSocH0FmHXM244FT7239cSlY=
github.com/Mag1cFall/go-sentencepiece v0.7.1 h1:Evzu4bQYge6F2tv40wMqr9MazbtbvoPbSD/eLl2gJEA=
github.com/Mag1cFall/go-sentencepiece v0.7.1/go.mod h1:5xb9a9oAB7EQ/J/47DTrj+BSrGoJIcXZ9CB5y27Nehw=
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
@@ -32,10 +30,10 @@ github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
-github.com/dlclark/regexp2/v2 v2.13.3 h1:yaOp65mbYbiTPk4kYd3MLa35486bjjHC4PYxaojrRCY=
-github.com/dlclark/regexp2/v2 v2.13.3/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
-github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
-github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
+github.com/dlclark/regexp2/v2 v2.14.0 h1:aNc0ATkJdvROJjOLZmGUZMQQVgP9sMvdnlRdMICP2Ug=
+github.com/dlclark/regexp2/v2 v2.14.0/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
+github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg=
+github.com/ebitengine/purego v0.11.3/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-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
@@ -74,14 +72,14 @@ github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 h1:h8O1byDZ1uk6RUXMhj1
github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985/go.mod h1:uiPmbdUbdt1NkGApKl7htQjZ8S7XaGUAVulJUJ9v6q4=
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM=
-github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
-github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
+github.com/modelcontextprotocol/go-sdk v1.9.0 h1:XVjBrIMg82x7ff2bqwSPgRThLp4TC1lGTX74Ofaie1g=
+github.com/modelcontextprotocol/go-sdk v1.9.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/molecule-man/go-brrr v1.2.0 h1:dOJU45BC3Gc2WXoxAW0rgCAgVuu2gruAOGncfieA0Jw=
github.com/molecule-man/go-brrr v1.2.0/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
github.com/nationallibraryofnorway/whatwg-url v0.9.1 h1:kGyhz2uSi70VS1JxgSZwZjpmrV8bM5PercNlxhMlls8=
github.com/nationallibraryofnorway/whatwg-url v0.9.1/go.mod h1:3KSm5/kiby6KExnnCXZ1Vmdwc+pLZokAdtJavchDKwg=
-github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 h1:jL3a8soXdzuTCcRnKhOmtcsVOObdDTFf4O2B403HPRU=
-github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
+github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 h1:XA01Vk/wv9YikCi1V51yRzIHPMT5of9+cMpZoZvDn/M=
+github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
@@ -90,8 +88,8 @@ github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
-github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg=
-github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk=
+github.com/shirou/gopsutil/v4 v4.26.11 h1:o1ZqIGUDTc3L0t245IEnQI3Yso8EVFunN/Kb2DpqTsc=
+github.com/shirou/gopsutil/v4 v4.26.11/go.mod h1:hBBe7kP+fLoN6mB78ZXDHZ2sYFI25yHyrErDVCvNb2M=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
@@ -104,8 +102,10 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
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/tphakala/go-mp3 v0.4.0 h1:HkmzzKnAbE1HHHXCnt+oz8i3qgvv/lLSXdfaSgBKye4=
+github.com/tphakala/go-mp3 v0.4.0/go.mod h1:kWWdy4PJWiDvIFLCfN8i5V4wNptfKBceterqvmf10sk=
+github.com/tphakala/simd v1.16.0 h1:dHw1NIuN56pjKsbi3uYdXQMYaGgT7brYXkdn3tsWDKQ=
+github.com/tphakala/simd v1.16.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=
@@ -120,8 +120,8 @@ github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zI
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
-github.com/zaf/g711 v1.4.0 h1:XZYkjjiAg9QTBnHqEg37m2I9q3IIDv5JRYXs2N8ma7c=
-github.com/zaf/g711 v1.4.0/go.mod h1:eCDXt3dSp/kYYAoooba7ukD/Q75jvAaS4WOMr0l1Roo=
+github.com/zaf/g711/v2 v2.0.1 h1:VKHirJS63JdOgZItZOyb/Cc+QOumc1E6MX/YiJQN5VQ=
+github.com/zaf/g711/v2 v2.0.1/go.mod h1:RiY+uagVf3Ni8T6eKnIFZW2C+Mg/kkqvrstUuIzJc6Y=
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
@@ -131,8 +131,8 @@ golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWP
golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
-golang.org/x/crypto/x509roots/fallback v0.0.0-20261123192653-4dc4fb521066 h1:IkSTNrk5HNulTzFHeCzJ5t3UnzLJkSIPaU7nmNI37Uk=
-golang.org/x/crypto/x509roots/fallback v0.0.0-20261123192653-4dc4fb521066/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
+golang.org/x/crypto/x509roots/fallback v0.0.0-20261202032733-168022f7de66 h1:B5O+ZrbXJqndUalalrU78YvRvS3/pxSyQQQFck2MNGQ=
+golang.org/x/crypto/x509roots/fallback v0.0.0-20261202032733-168022f7de66/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
diff --git a/internal/aistudio/accounts.go b/internal/aistudio/accounts.go
index bbf31b3d..51b59bb5 100644
--- a/internal/aistudio/accounts.go
+++ b/internal/aistudio/accounts.go
@@ -84,6 +84,21 @@ var (
ErrResourceNotFound = errors.New("资源账户映射不存在")
)
+// modelMethodError 表示实时目录中有该模型,但它没有提供请求的方法,按 ErrModelNotFound 处理
+type modelMethodError struct {
+ Model string
+ Method string
+}
+
+func (e *modelMethodError) Error() string {
+ return fmt.Sprintf("模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法", e.Model, e.Method)
+}
+
+// Is 让 modelMethodError 与 ErrModelNotFound 等价
+func (e *modelMethodError) Is(target error) bool {
+ return target == ErrModelNotFound
+}
+
// AllCoolingError 表示请求的全部候选账户都在冷却且不会很快恢复
type AllCoolingError struct {
ModelID string
@@ -309,7 +324,7 @@ type Account struct {
leaseLock *flock.Flock
storageMu sync.Mutex
runtimeMu sync.Mutex
- persistenceLocked bool
+ persistenceLocked atomic.Bool
authGeneration uint64
authCheckedAt time.Time
modelAccessGeneration uint64
@@ -383,6 +398,8 @@ type AccountStatus struct {
DeviceBoundSession bool `json:"device_bound_session,omitempty"`
// MigratedModels 是账户目录中被迁移到任务接口(ListModels field 79 为后台任务与模型目标)的模型 ID
MigratedModels []string `json:"-"`
+ // CallableModels 是账户按选号的同一判定可以调用的模型 ID,只有 AdminStatus 填写
+ CallableModels []string `json:"-"`
}
// AccountTransition 是账户正在进行的后台操作
@@ -440,9 +457,10 @@ type AccountSelection struct {
// IgnoreQuotaCooldown 为 true 时套餐限额、每日限额与权限拒绝冷却中的账户照常参与选号,拒绝记录有效期内拒绝过不大于 RequestSize 的请求的账户除外,余量多的账户优先
IgnoreQuotaCooldown bool
// RequestSize 是请求输入正文的字节数,0 表示未知
- RequestSize int64
- anyTier bool
- anyState bool
+ RequestSize int64
+ anyTier bool
+ anyState bool
+ accountModel *Model
}
const preferredBootstrapModelID = "gemini-flash-latest"
@@ -739,12 +757,19 @@ func (s *AccountStore) Load() ([]*Account, error) {
err error
}
results := make([]loaded, len(directories))
- catalogs := &catalogParses{entries: make(map[catalogCacheKey]catalogCacheParse)}
+ catalogs := newCatalogParses()
+ var next atomic.Int64
var group sync.WaitGroup
- for index, directory := range directories {
+ for range min(len(directories), max(runtime.GOMAXPROCS(0), 8)) {
group.Go(func() {
- account, err := loadAccount(directory, catalogs)
- results[index] = loaded{account, err}
+ for {
+ index := int(next.Add(1)) - 1
+ if index >= len(directories) {
+ return
+ }
+ account, err := loadAccount(directories[index], catalogs)
+ results[index] = loaded{account, err}
+ }
})
}
group.Wait()
@@ -874,10 +899,7 @@ func (s *AccountStore) Delete(account *Account) error {
}
return fmt.Errorf("读取账户目录: %w", err)
}
- account.storageMu.Lock()
- lockedByPool := account.persistenceLocked
- account.storageMu.Unlock()
- if lockedByPool {
+ if account.persistenceLocked.Load() {
if err := os.RemoveAll(directory); err != nil {
return fmt.Errorf("删除账户目录: %w", err)
}
@@ -1006,43 +1028,48 @@ func (a *Account) SupportsMethod(modelID string, method string) bool {
}
func accountSupportsSelection(account *Account, selection AccountSelection) bool {
- modelID := strings.TrimPrefix(strings.TrimSpace(selection.ModelID), "models/")
- if modelID == "" {
- return true
- }
- for _, model := range account.Models {
- if !modelMatchesID(model, modelID) {
- continue
- }
- if !selection.anyTier && !modelAllowedByTier(model, account.BenefitTier) {
- return false
+ model := selection.accountModel
+ if model == nil {
+ modelID := strings.TrimPrefix(strings.TrimSpace(selection.ModelID), "models/")
+ if modelID == "" {
+ return true
}
- if strings.TrimSpace(selection.Method) != "" && !hasMethod(model, selection.Method) {
- return false
+ for index := range account.Models {
+ if modelMatchesID(account.Models[index], modelID) {
+ model = &account.Models[index]
+ break
+ }
}
- return strings.TrimSpace(selection.Capability) == "" || model.Capabilities[selection.Capability]
}
- return false
+ return model != nil && (selection.anyTier || modelAllowedByTier(*model, account.BenefitTier)) &&
+ (strings.TrimSpace(selection.Method) == "" || hasMethod(*model, selection.Method)) &&
+ (strings.TrimSpace(selection.Capability) == "" || model.Capabilities[selection.Capability])
}
-// CatalogModels 返回完整目录,每项带有启用账户可以调用的通道,按 callableFirst 排列
+// CatalogModels 返回完整目录,每项带有启用账户可以调用的通道,本服务调用不了的模型标明原因且没有通道,按 callableFirst 排列
func (p *AccountPool) CatalogModels(models []Model) []Model {
p.mu.Lock()
defer p.mu.Unlock()
catalog := make([]Model, len(models))
for index, model := range models {
- model.Channels = p.modelChannelsLocked(model, false)
+ model.Channels = nil
+ if model.Unavailable = modelUnavailableReason(model); model.Unavailable == "" {
+ model.Channels = p.modelChannelsLocked(model, false)
+ }
catalog[index] = model
}
return callableFirst(catalog)
}
-// PublicModels 返回已启用通道可以提供的目录项,只因账户权益不足而无法调用的模型同样列出且通道为空,按 callableFirst 排列
+// PublicModels 返回已启用通道可以提供的目录项,只因账户订阅权益不足而无法调用的模型同样列出且通道为空,本服务调用不了的模型不列出,按 callableFirst 排列
func (p *AccountPool) PublicModels(models []Model) []Model {
p.mu.Lock()
defer p.mu.Unlock()
public := make([]Model, 0, len(models))
for _, model := range models {
+ if modelUnavailableReason(model) != "" {
+ continue
+ }
model.Channels = p.modelChannelsLocked(model, false)
if len(model.Channels) == 0 && len(p.modelChannelsLocked(model, true)) == 0 {
continue
@@ -1052,12 +1079,17 @@ func (p *AccountPool) PublicModels(models []Model) []Model {
return callableFirst(public)
}
-// callableFirst 保持原顺序依次排列有通道的普通模型、agent 与没有通道的普通模型
+// callableFirst 保持原顺序依次排列有通道的普通模型、agent、没有通道的普通模型与本服务调用不了的模型,没有方法的模型 Methods 为空切片而不是 nil,各出口输出 []
func callableFirst(models []Model) []Model {
ordered := make([]Model, 0, len(models))
- var agents, restricted []Model
+ var agents, restricted, unavailable []Model
for _, model := range models {
+ if model.Methods == nil {
+ model.Methods = []string{}
+ }
switch {
+ case model.Unavailable != "":
+ unavailable = append(unavailable, model)
case interactionRouting(model, GenerationDefaults{}, ChannelPlayground).IsAgent():
agents = append(agents, model)
case len(model.Channels) == 0:
@@ -1066,7 +1098,7 @@ func callableFirst(models []Model) []Model {
ordered = append(ordered, model)
}
}
- return append(append(ordered, agents...), restricted...)
+ return append(append(append(ordered, agents...), restricted...), unavailable...)
}
// MissingModel 判断已载入的实时目录中没有该模型,请求会以 ErrModelNotFound 失败
@@ -1154,6 +1186,17 @@ func (p *AccountPool) Account(accountID string) (*Account, error) {
return account, nil
}
+// EffectiveProxy 在池锁内返回账户固定代理、代理池绑定或全局代理
+func (p *AccountPool) EffectiveProxy(accountID string, globalProxy string) (string, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ account := p.byID[strings.TrimSpace(accountID)]
+ if account == nil {
+ return "", fmt.Errorf("%w: %s", ErrAccountNotFound, accountID)
+ }
+ return account.EffectiveProxy(globalProxy), nil
+}
+
// isCurrentAccount 判断 account 是否仍为池中该 ID 当前有效的账户实例
func (p *AccountPool) isCurrentAccount(account *Account) bool {
p.mu.Lock()
@@ -1164,10 +1207,7 @@ func (p *AccountPool) isCurrentAccount(account *Account) bool {
// Add 将新账户加入当前调度池
func (p *AccountPool) Add(account *Account) (resultErr error) {
if account.ConfigPath != "" {
- account.storageMu.Lock()
- lockedExternally := account.persistenceLocked
- account.storageMu.Unlock()
- if !lockedExternally {
+ if !account.persistenceLocked.Load() {
leaseLock, err := acquireAccountFileLease(account.StoragePath)
if errors.Is(err, ErrAccountLeased) {
return fmt.Errorf("%w: %s", ErrAccountLeased, account.ID)
@@ -1270,13 +1310,9 @@ func (p *AccountPool) Remove(accountID string, deleteDirectory func(*Account) er
p.mu.Unlock()
return nil, err
}
- account.storageMu.Lock()
- account.persistenceLocked = true
- account.storageMu.Unlock()
+ account.persistenceLocked.Store(true)
deleteErr := deleteDirectory(account)
- account.storageMu.Lock()
- account.persistenceLocked = false
- account.storageMu.Unlock()
+ account.persistenceLocked.Store(false)
var releaseErr error
if runtimeLock != nil {
releaseErr = runtimeLock.Unlock()
@@ -1668,7 +1704,7 @@ func (p *AccountPool) validateSelectionLocked(selection AccountSelection) error
return fmt.Errorf("%w: %s", ErrModelNotFound, modelID)
}
if selection.Method != "" && !p.hasModelMethodLocked(modelID, selection.Method) {
- return fmt.Errorf("%w: 模型 %s 不支持 %s", ErrModelNotFound, modelID, selection.Method)
+ return &modelMethodError{Model: modelID, Method: selection.Method}
}
if selection.Capability != "" && !p.hasModelCapabilityLocked(modelID, selection.Capability) {
return fmt.Errorf("%w: 模型 %s 不支持 %s", ErrModelNotFound, modelID, selection.Capability)
@@ -2004,10 +2040,9 @@ func (p *AccountPool) applyEnabledLocked(account *Account) {
p.notifyLocked()
}
-// SetNote 写回账户备注并立即生效,不等待账户上的在途请求
-func (p *AccountPool) SetNote(accountID string, note string) (*Account, error) {
+// updateAccountConfig 在账户存储锁内按 mutate 改写账户配置并写回磁盘,成功后在池锁内调用 applyLocked 更新内存中的配置
+func (p *AccountPool) updateAccountConfig(accountID string, mutate func(*AccountConfig) error, applyLocked func(*Account)) (*Account, error) {
accountID = strings.TrimSpace(accountID)
- note = strings.TrimSpace(note)
p.mu.Lock()
account := p.byID[accountID]
p.mu.Unlock()
@@ -2019,8 +2054,7 @@ func (p *AccountPool) SetNote(accountID string, note string) (*Account, error) {
p.mu.Lock()
value := account.Config
p.mu.Unlock()
- value.Note = note
- if err := value.Validate(); err != nil {
+ if err := mutate(&value); err != nil {
return nil, err
}
if err := writeAccountConfig(account.ConfigPath, value); err != nil {
@@ -2028,33 +2062,30 @@ func (p *AccountPool) SetNote(accountID string, note string) (*Account, error) {
}
p.mu.Lock()
defer p.mu.Unlock()
- account.Config.Note = note
+ applyLocked(account)
return account, nil
}
+// SetNote 写回账户备注并立即生效,不等待账户上的在途请求
+func (p *AccountPool) SetNote(accountID string, note string) (*Account, error) {
+ note = strings.TrimSpace(note)
+ return p.updateAccountConfig(accountID, func(cfg *AccountConfig) error {
+ cfg.Note = note
+ return cfg.Validate()
+ }, func(account *Account) {
+ account.Config.Note = note
+ })
+}
+
// SetEnabled 写回账户启用状态并立即生效,不等待账户上的在途请求
func (p *AccountPool) SetEnabled(accountID string, enabled bool) (*Account, error) {
- accountID = strings.TrimSpace(accountID)
- 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.Enabled = enabled
- if err := writeAccountConfig(account.ConfigPath, value); err != nil {
- return nil, err
- }
- p.mu.Lock()
- defer p.mu.Unlock()
- account.Config.Enabled = enabled
- p.applyEnabledLocked(account)
- return account, nil
+ return p.updateAccountConfig(accountID, func(cfg *AccountConfig) error {
+ cfg.Enabled = enabled
+ return nil
+ }, func(account *Account) {
+ account.Config.Enabled = enabled
+ p.applyEnabledLocked(account)
+ })
}
// SetTransition 记录停用收尾、目录同步或账户保存进行到的步骤,operation 为空表示结束
@@ -2676,6 +2707,38 @@ func (p *AccountPool) SeedUsage(seed AccountUsageSeed) {
}
}
+// accountGenerateCoverage 返回账户目录中可调用 generateContent 的模型数,与逐个模型调用 SupportsMethod 的结果相同
+func accountGenerateCoverage(account *Account) int {
+ // verdict 记录按目录顺序第一个能决定结果的模型对其 ID 与别名的判定,1 为支持,-1 为不支持,没有记录表示还没有决定
+ verdict := make(map[string]int8, len(account.Models))
+ record := func(key string, result int8) {
+ if _, decided := verdict[key]; !decided {
+ verdict[key] = result
+ }
+ }
+ for i := range account.Models {
+ model := &account.Models[i]
+ result := int8(-1)
+ if modelAllowedByTier(*model, account.BenefitTier) {
+ if !hasMethod(*model, "generateContent") {
+ continue
+ }
+ result = 1
+ }
+ record(model.ID, result)
+ for _, alias := range model.CapabilityOptions["aliases"] {
+ record(alias, result)
+ }
+ }
+ coverage := 0
+ for i := range account.Models {
+ if verdict[strings.TrimPrefix(strings.TrimSpace(account.Models[i].ID), "models/")] == 1 {
+ coverage++
+ }
+ }
+ return coverage
+}
+
// PreferWarmPool 按权益分层轮选初始热账户,round-robin 优先尚无或较少热账户的权益层,同层按覆盖度、当日用量少与最久未用优先,fill-first 时 ACCOUNT_ORDER 列出的账户在前
func (p *AccountPool) PreferWarmPool(accountIDs []string, warm []string) []string {
type warmCandidate struct {
@@ -2699,12 +2762,7 @@ func (p *AccountPool) PreferWarmPool(accountIDs []string, warm []string) []strin
if account == nil {
continue
}
- coverage := 0
- for _, model := range account.Models {
- if account.SupportsMethod(model.ID, "generateContent") {
- coverage++
- }
- }
+ coverage := accountGenerateCoverage(account)
requests := int64(0)
if account.quotaDayStart.Equal(today) {
requests = account.quotaDayRequests
@@ -3083,6 +3141,21 @@ func (p *AccountPool) unbindResourceContext(ctx context.Context, resourceID stri
return err
}
+// unbindResourcesContext 在单次运行状态事务中批量解除同一账户下的多个资源绑定
+func (p *AccountPool) unbindResourcesContext(ctx context.Context, accountID string, resourceIDs []string) error {
+ _, err := p.updateRuntimeContext(ctx, accountID, func(_ *Account, runtimeState *accountRuntimeState) (bool, func(*Account), error) {
+ changed := false
+ for _, resourceID := range resourceIDs {
+ if _, exists := runtimeState.Resources[resourceID]; exists {
+ delete(runtimeState.Resources, resourceID)
+ changed = true
+ }
+ }
+ return changed, nil, nil
+ })
+ return err
+}
+
// MarkAuthRequired 将账户标记为需要重新登录
func (p *AccountPool) MarkAuthRequired(accountID string, reason string) error {
return p.setAccountState(accountID, AccountAuthRequired, reason)
@@ -3184,11 +3257,42 @@ func (p *AccountPool) MarkReady(accountID string) error {
// Status 返回账户池的脱敏状态
func (p *AccountPool) Status() []AccountStatus {
+ return p.status("", false)
+}
+
+// AdminStatus 返回账户池的脱敏状态,每个账户带有按选号的同一判定可以调用的模型,供管理端显示
+func (p *AccountPool) AdminStatus() []AccountStatus {
+ return p.status("", true)
+}
+
+// AdminAccountStatus 返回单个账户的脱敏状态,带有按选号的同一判定可以调用的模型,供管理端单账户接口使用
+func (p *AccountPool) AdminAccountStatus(accountID string) (AccountStatus, bool) {
+ statuses := p.status(accountID, true)
+ if len(statuses) == 0 {
+ return AccountStatus{}, false
+ }
+ return statuses[0], true
+}
+
+// status 返回账户池的脱敏状态,filterID 非空时只返回该账户,withCallable 为 true 时填写目标账户的 CallableModels
+func (p *AccountPool) status(filterID string, withCallable bool) []AccountStatus {
p.mu.Lock()
defer p.mu.Unlock()
+ targets := p.accounts
+ if filterID != "" {
+ account := p.byID[filterID]
+ if account == nil {
+ return nil
+ }
+ targets = []*Account{account}
+ }
now := time.Now()
- statuses := make([]AccountStatus, 0, len(p.accounts))
- for _, account := range p.accounts {
+ var callable map[string][]string
+ if withCallable {
+ callable = p.callableModelsLocked(targets)
+ }
+ statuses := make([]AccountStatus, 0, len(targets))
+ for _, account := range targets {
state := account.State
_, active := accountCooldown(account, "", now)
if !account.Config.Enabled {
@@ -3254,6 +3358,7 @@ func (p *AccountPool) Status() []AccountStatus {
VerificationRequired: state == AccountRestricted && verificationRestriction(account.runtime.Restricted),
DeviceBoundSession: account.StorageState.DeviceBoundSession(),
MigratedModels: migrated,
+ CallableModels: callable[account.ID],
}
if !account.LastUsed.IsZero() {
status.LastUsed = timePointer(account.LastUsed)
@@ -3312,7 +3417,7 @@ func (p *AccountPool) classifyCandidatesLocked(
return AccountCandidateGroups{}, fmt.Errorf("%w: %s", ErrModelNotFound, modelID)
}
if selection.Method != "" && !p.hasModelMethodLocked(modelID, selection.Method) {
- return AccountCandidateGroups{}, fmt.Errorf("%w: 模型 %s 不支持 %s", ErrModelNotFound, modelID, selection.Method)
+ return AccountCandidateGroups{}, &modelMethodError{Model: modelID, Method: selection.Method}
}
if err := p.modelAccessErrorLocked(selection); err != nil {
return AccountCandidateGroups{}, err
@@ -3871,25 +3976,55 @@ type accountCatalogCache struct {
HiddenDiscovered bool `json:"hidden_discovered,omitempty"`
}
-// catalogCacheKey 是目录缓存的权益等级与 ListModels 响应原文
+// catalogCacheKey 是目录缓存的权益等级与 ListModels 响应原文的摘要
type catalogCacheKey struct {
- tier BenefitTier
- source string
+ tier BenefitTier
+ sum [sha256.Size]byte
}
-// catalogCacheParse 是一份目录缓存的解析结果与目录指纹
+// catalogCacheParse 是一份目录缓存的解析结果与目录指纹,once 保证同一键在一次载入中只解析一次
type catalogCacheParse struct {
+ once sync.Once
catalog modelCatalog
fingerprint string
+ ok bool
}
// catalogParses 是一次载入中各账户共用的目录缓存解析结果
type catalogParses struct {
mu sync.Mutex
- entries map[catalogCacheKey]catalogCacheParse
+ entries map[catalogCacheKey]*catalogCacheParse
+}
+
+// newCatalogParses 创建一次载入用的目录缓存解析结果表
+func newCatalogParses() *catalogParses {
+ return &catalogParses{entries: make(map[catalogCacheKey]*catalogCacheParse)}
+}
+
+// parse 返回键对应的解析结果,同一键并发调用时只有一个调用解析 listModels
+func (c *catalogParses) parse(key catalogCacheKey, listModels json.RawMessage) *catalogCacheParse {
+ c.mu.Lock()
+ parsed := c.entries[key]
+ if parsed == nil {
+ parsed = &catalogCacheParse{}
+ c.entries[key] = parsed
+ }
+ c.mu.Unlock()
+ parsed.once.Do(func() {
+ catalog, err := parseModelCatalog(bytes.NewReader(listModels))
+ if err != nil {
+ return
+ }
+ fingerprint, err := accountCatalogFingerprint(key.tier, catalog.models)
+ if err != nil {
+ return
+ }
+ parsed.catalog, parsed.fingerprint, parsed.ok = catalog, fingerprint, true
+ })
+ return parsed
}
-// readCatalogCache 读取 catalog.json,返回加入官网隐藏模型后的 ListModels 目录与缓存内容,内容与 runtime-state 的目录指纹不一致或无法读取时返回空目录与空缓存;catalogs 中已有同一权益等级与原文的解析结果时直接沿用,catalogs 不为 nil 时保存本次解析结果
+// readCatalogCache 读取 catalog.json,返回加入官网隐藏模型后的 ListModels 目录与缓存内容,内容与 runtime-state 的目录指纹不一致或无法读取时返回空目录与空缓存;catalogs 中同一权益等级与原文的 ListModels 只解析一次,nil 时只用于本次调用
func readCatalogCache(filePath string, runtimeState accountRuntimeState, catalogs *catalogParses) (modelCatalog, accountCatalogCache) {
data, err := os.ReadFile(filePath)
if err != nil {
@@ -3899,31 +4034,11 @@ func readCatalogCache(filePath string, runtimeState accountRuntimeState, catalog
if err := json.Unmarshal(data, &cache); err != nil || len(cache.ListModels) == 0 {
return modelCatalog{}, accountCatalogCache{}
}
- key := catalogCacheKey{tier: runtimeState.BenefitTier, source: string(cache.ListModels)}
- var parsed catalogCacheParse
- ok := false
- if catalogs != nil {
- catalogs.mu.Lock()
- parsed, ok = catalogs.entries[key]
- catalogs.mu.Unlock()
- }
- if !ok {
- catalog, err := parseModelCatalog(bytes.NewReader(cache.ListModels))
- if err != nil {
- return modelCatalog{}, accountCatalogCache{}
- }
- fingerprint, err := accountCatalogFingerprint(runtimeState.BenefitTier, catalog.models)
- if err != nil {
- return modelCatalog{}, accountCatalogCache{}
- }
- parsed = catalogCacheParse{catalog: catalog, fingerprint: fingerprint}
- if catalogs != nil {
- catalogs.mu.Lock()
- catalogs.entries[key] = parsed
- catalogs.mu.Unlock()
- }
+ if catalogs == nil {
+ catalogs = newCatalogParses()
}
- if parsed.fingerprint != runtimeState.CatalogFingerprint {
+ parsed := catalogs.parse(catalogCacheKey{tier: runtimeState.BenefitTier, sum: sha256.Sum256(cache.ListModels)}, cache.ListModels)
+ if !parsed.ok || parsed.fingerprint != runtimeState.CatalogFingerprint {
return modelCatalog{}, accountCatalogCache{}
}
return parsed.catalog.withHidden(cache.HiddenModels), cache
@@ -4641,18 +4756,14 @@ func acquireAccountPublishLease(account *Account, validate bool) (*AccountPublis
return nil, err
}
}
- account.storageMu.Lock()
- account.persistenceLocked = true
- account.storageMu.Unlock()
+ account.persistenceLocked.Store(true)
return &AccountPublishLease{account: account, requestLock: requestLock, runtimeLock: runtimeLock}, nil
}
// Release 结束新账户运行时发布窗口
func (lease *AccountPublishLease) Release() error {
lease.once.Do(func() {
- lease.account.storageMu.Lock()
- lease.account.persistenceLocked = false
- lease.account.storageMu.Unlock()
+ lease.account.persistenceLocked.Store(false)
if lease.runtimeLock != nil {
lease.err = lease.runtimeLock.Unlock()
}
@@ -4836,11 +4947,7 @@ func cloneCooldowns(cooldowns map[string]CooldownState) map[string]CooldownState
if len(cooldowns) == 0 {
return nil
}
- result := make(map[string]CooldownState, len(cooldowns))
- for key, cooldown := range cooldowns {
- result[key] = cooldown
- }
- return result
+ return maps.Clone(cooldowns)
}
func fileExists(filePath string) bool {
diff --git a/internal/aistudio/assistant.go b/internal/aistudio/assistant.go
index f093d544..ef805f6d 100644
--- a/internal/aistudio/assistant.go
+++ b/internal/aistudio/assistant.go
@@ -4,6 +4,7 @@ import (
"cmp"
"context"
"crypto/sha256"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -23,14 +24,25 @@ import (
const (
// assistantModelSuffix 是 Build 写代码助手模型 ID 的后缀
assistantModelSuffix = "-build"
- // assistantOfflineMethod 是提交写代码助手生成任务的受保护 RPC
+ // assistantStreamMethod 是 agency 协议提交并流式读取写代码助手任务的受保护 RPC(AppletGenerationService)
+ assistantStreamMethod = "StreamRunAgentTask"
+ // assistantCancelMethod 是 agency 协议取消写代码助手任务的 RPC(AppletGenerationService)
+ assistantCancelMethod = "CancelAgentTask"
+ // assistantOfflineMethod 是 legacy 协议提交写代码助手任务的受保护 RPC(MakerSuiteService)
assistantOfflineMethod = "CodeAssistantOffline"
- // assistantStreamMethod 是读取写代码助手生成任务的流式 RPC
- assistantStreamMethod = "StreamCodeAssistantOfflineGeneration"
+ // assistantLegacyStreamMethod 是 legacy 协议流式读取写代码助手任务的 RPC(MakerSuiteService)
+ assistantLegacyStreamMethod = "StreamCodeAssistantOfflineGeneration"
+ // assistantLegacyCancelMethod 是 legacy 协议取消写代码助手任务的 RPC(MakerSuiteService)
+ assistantLegacyCancelMethod = "CancelCodeAssistantOfflineGeneration"
+ // assistantProtocolAgency 与 assistantProtocolLegacy 是 Build 写代码助手实际采用的两套上游协议标识
+ assistantProtocolAgency = "agency"
+ assistantProtocolLegacy = "legacy"
// assistantUploadMethod 是写代码助手附件上传在错误中的名称
assistantUploadMethod = "Upload"
- // assistantProofField 是 CodeAssistantOffline 的 WAA proof 字段
- assistantProofField = 2
+ // assistantProofField 是 StreamRunAgentTask 的 WAA proof 字段(1-based field 4)
+ assistantProofField = 4
+ // assistantLegacyProofField 是 CodeAssistantOffline 的 WAA proof 字段(1-based field 2)
+ assistantLegacyProofField = 2
// assistantDefaultThinkingLevel 是 Build 对话默认的 high 思考强度
assistantDefaultThinkingLevel = 3
// assistantCleanupTimeout 是取消未完成任务与发送回复后伴随请求的期限
@@ -129,7 +141,7 @@ type AssistantUploader interface {
// assistantModelEntry 由可在 Build 写代码助手中选用的目录模型派生 -build 条目
func assistantModelEntry(base modelEntry) modelEntry {
- model := cloneModels([]Model{base.model})[0]
+ model := cloneModel(base.model)
model.ID = base.model.ID + assistantModelSuffix
model.Name = base.model.Name + " (Build)"
model.Methods = nil
@@ -178,46 +190,137 @@ func assistantBaseModelID(modelID string) string {
// assistantThinkingLevel 按请求的思考强度或预算选择 Build 对话的 thinking level,未指定时为 high
func assistantThinkingLevel(config GenerationConfig, defaults GenerationDefaults) (int64, error) {
level := int64(assistantDefaultThinkingLevel)
- switch normalizedReasoningEffort(config.ReasoningEffort) {
- case "":
- if config.ThinkingBudget != nil {
- level = thinkingLevelForBudget(*config.ThinkingBudget)
- }
- case "minimal", "none":
- level = 4
- case "low":
- level = 1
- case "medium":
- level = 2
- case "high", "xhigh", "extra_high", "max":
- level = 3
- default:
- return 0, fmt.Errorf("reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max")
+ if parsed, ok, err := parseReasoningEffortLevel(normalizedReasoningEffort(config.ReasoningEffort), 3); err != nil {
+ return 0, err
+ } else if ok {
+ level = parsed
+ } else if config.ThinkingBudget != nil {
+ level = thinkingLevelForBudget(*config.ThinkingBudget)
}
return closestSupportedThinkingLevel(level, defaults.ThinkingLevels), nil
}
-// assistantTarget 是 CodeAssistantOffline 提交到的应用与 trajectory:trajectory 为空且 fresh 为假时是新应用的第一段对话,fresh 为真时在应用中开启新 trajectory,否则续接 trajectory
+// assistantTarget 是写代码助手提交到的应用、trajectory、游标与协议模式:
+// newApplet 为真时是新建应用的首轮对话(agency 使用 CreateApplet field 4,无游标);
+// fresh 为真时在已有应用中开启新 trajectory(agency 生成新客户端 UUIDv4 写入 field 2 且无游标,legacy 置 field 22 为 true);
+// 否则续接 trajectory(agency 携带 trajectory、cursor 与 interactionID,legacy 携带 trajectory)
type assistantTarget struct {
- applet string
- trajectory string
- fresh bool
+ applet string
+ trajectory string
+ cursor int64
+ interactionID string
+ newApplet bool
+ fresh bool
+ agency bool
}
// created 表示提交到新应用的第一段对话
func (target assistantTarget) created() bool {
- return target.trajectory == "" && !target.fresh
+ return target.newApplet
}
-// EncodeAssistantRequest 编码写代码助手一轮的 CodeAssistantOffline 请求
-// field 2 由 WAA proof 写入,各字段依据见 docs/build.md 的“CodeAssistantOffline”一节
+// SetBuildChatProtocol 设置后续 -build 请求采用的协议策略(auto、agency 或 legacy)
+func (c *Client) SetBuildChatProtocol(mode string) {
+ if c == nil || c.assistants == nil {
+ return
+ }
+ c.assistants.setProtocol(mode)
+}
+
+// resolveAssistantProtocol 按 BUILD_CHAT_PROTOCOL 与账户页面启动数据中的标志 45831005 决定本轮是否采用 agency 协议:设置为 auto 时标志为 true 用 agency,false 或缺失用 legacy
+// 账户的协议或依据变化时写一条服务日志,auto 下标志缺失时为告警;auto 下页面启动数据读取失败且账户还没有读到过标志时返回该错误
+func (c *Client) resolveAssistantProtocol(ctx context.Context, accountID string) (bool, error) {
+ var agency bool
+ var basis string
+ switch c.assistants.getProtocol() {
+ case assistantProtocolAgency:
+ agency, basis = true, "setting=agency"
+ case assistantProtocolLegacy:
+ basis = "setting=legacy"
+ default:
+ var pageErr error
+ if c.pages != nil {
+ page, err := c.pages.PageCatalog(ctx, accountID, false)
+ if pageErr = err; err == nil {
+ c.assistants.setBuildAgencyFlag(accountID, page.BuildAgency)
+ }
+ }
+ switch flag := c.assistants.buildAgencyFlag(accountID); {
+ case flag == nil && pageErr != nil:
+ return false, pageErr
+ case flag == nil:
+ basis = "flag=missing"
+ case *flag:
+ agency, basis = true, "flag=true"
+ default:
+ basis = "flag=false"
+ }
+ }
+ proto := assistantProtocolLegacy
+ if agency {
+ proto = assistantProtocolAgency
+ }
+ if c.assistants.markProtocolLogged(accountID, proto+"|"+basis) {
+ if basis == "flag=missing" {
+ slog.Warn("页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency", "account", accountID, "protocol", proto, "basis", basis)
+ } else {
+ slog.Info("Build 写代码助手协议已选定", "account", accountID, "protocol", proto, "basis", basis)
+ }
+ }
+ return agency, nil
+}
+
+// EncodeAssistantRequest 编码写代码助手 agency 协议一轮的 StreamRunAgentTask 请求
+// field 4 由 WAA proof 写入;contents 为空且带 trajectory 时用于同一任务的断流重连
func EncodeAssistantRequest(request GenerateRequest, defaults GenerationDefaults, target assistantTarget, requestID string) ([]byte, int, error) {
- contents, err := encodeContents(request.Contents)
+ contents := []any{}
+ if len(request.Contents) > 0 {
+ var err error
+ contents, err = encodeContents(request.Contents)
+ if err != nil {
+ return nil, 0, err
+ }
+ } else if target.trajectory == "" || target.fresh {
+ return nil, 0, fmt.Errorf("StreamRunAgentTask contents 不能为空")
+ }
+ level, err := assistantThinkingLevel(request.Config, defaults)
if err != nil {
return nil, 0, err
}
- if len(contents) == 0 {
- return nil, 0, fmt.Errorf("CodeAssistantOffline contents 不能为空")
+ options := make([]any, 6)
+ if system := SystemText(request.System); system != "" {
+ options[2] = system
+ }
+ options[5] = int64(2)
+ hasResumePair := !target.fresh && target.cursor > 0 && target.interactionID != ""
+ size := 9
+ if hasResumePair {
+ size = 13
+ }
+ wire := make([]any, size)
+ wire[0] = target.applet
+ if target.trajectory != "" && (!target.newApplet || target.trajectory != target.applet) {
+ wire[1] = target.trajectory
+ }
+ wire[2] = contents
+ wire[4] = options
+ wire[5] = wireModelName(assistantBaseModelID(request.Model))
+ wire[6] = []any{int64(1), nil, nil, level}
+ if !target.fresh && target.cursor > 0 {
+ wire[7] = target.cursor
+ }
+ wire[8] = requestID
+ if hasResumePair {
+ wire[12] = []any{target.interactionID, target.cursor}
+ }
+ return marshalWAAArray(wire, assistantProofField)
+}
+
+// EncodeLegacyAssistantRequest 编码写代码助手 legacy 协议一轮的 CodeAssistantOffline 请求(29 元数组,field 2 为 WAA proof)
+func EncodeLegacyAssistantRequest(request GenerateRequest, defaults GenerationDefaults, target assistantTarget, requestID string) ([]byte, int, error) {
+ contents, err := encodeContents(request.Contents)
+ if err != nil {
+ return nil, 0, err
}
level, err := assistantThinkingLevel(request.Config, defaults)
if err != nil {
@@ -238,13 +341,49 @@ func EncodeAssistantRequest(request GenerateRequest, defaults GenerationDefaults
}
if target.fresh {
wire[22] = int64(1)
- } else if target.trajectory != "" {
+ } else if !target.created() && target.trajectory != "" {
wire[20] = target.trajectory
}
wire[15] = int64(1)
wire[18] = []any{int64(1), nil, nil, level}
wire[28] = requestID
- return marshalWAAArray(wire, assistantProofField)
+ return marshalWAAArray(wire, assistantLegacyProofField)
+}
+
+// assistantAgentBinding 返回官网 StreamRunAgentTask 的 WAA proof 绑定原文:
+// 将 contents 中各 Part(文本、内联 base64、Drive 文件 ID、上传附件为空串)以单个空格连接;
+// 非空时返回 " ",为空时返回 ""
+func assistantAgentBinding(applet string, contents []Content) string {
+ values := make([]string, 0)
+ for _, content := range contents {
+ for _, part := range content.Parts {
+ switch {
+ case part.Text != "":
+ values = append(values, part.Text)
+ case part.InlineData != nil:
+ values = append(values, base64.StdEncoding.EncodeToString(part.InlineData.Data))
+ case part.File != nil:
+ values = append(values, part.File.ID)
+ default:
+ values = append(values, "")
+ }
+ }
+ }
+ parts := strings.Join(values, " ")
+ if parts == "" {
+ return applet
+ }
+ return applet + " " + parts
+}
+
+// applyAssistantBenefitTier 为写代码助手的生成与取消请求写入账户权益请求头
+func (c *Client) applyAssistantBenefitTier(accountID string, header http.Header) {
+ c.tierMu.RLock()
+ tier := c.tiers[strings.TrimSpace(accountID)]
+ c.tierMu.RUnlock()
+ if value := tier.RequestHeaderValue(); value != "" {
+ header.Set("X-AIStudio-G1-Tier", value)
+ }
}
// assistantContext 返回请求的系统提示词与函数声明 JSON,tool choice 为 none 时没有函数声明
@@ -504,10 +643,12 @@ func assistantPromptText(contents []Content) string {
}
// prepareAssistantTurn 决定本轮提交到的 trajectory 并改写请求:对话续接得上账户应用中保存的 trajectory 时只提交续接位置之后的轮次,否则在应用中开启新 trajectory,账户没有应用或应用已被删除时照官网新建应用;附件与说明文件的上传和新建应用、开启新 trajectory 的请求同时进行
-func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease, request GenerateRequest, links []turnLink, apiKey string) (assistantTurn, error) {
+func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease, request GenerateRequest, links []turnLink, apiKey string, agency bool) (assistantTurn, error) {
applet := lease.assistantAppletID()
+ var opened assistantOpenedApplet
if applet != "" {
- if _, err := c.openAssistantApplet(ctx, lease, applet, request.Model); errors.Is(err, errAssistantAppletGone) {
+ var err error
+ if opened, err = c.openAssistantApplet(ctx, lease, applet, request.Model, agency); errors.Is(err, errAssistantAppletGone) {
applet = ""
} else if err != nil {
return assistantTurn{}, err
@@ -518,6 +659,9 @@ func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease,
if applet != "" {
trajectory, start = lease.findAssistantTrajectory(apiKey, links)
}
+ if trajectory != nil && !canContinueAssistantTrajectory(trajectory, opened, agency) {
+ trajectory, start = nil, 0
+ }
prepared, groups, context, err := planAssistantTurn(request, links, trajectory, start)
if err != nil {
return assistantTurn{}, fmt.Errorf("%w: %v", ErrInvalidArgument, err)
@@ -529,14 +673,24 @@ func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease,
uploaded.Go(func() { prepared.Contents, uploadErr = c.uploadAssistantAttachments(ctx, request.AccountID, contents) })
switch {
case applet == "":
- applet, err = c.createAssistantApplet(ctx, lease, request.Model, assistantPromptText(contents))
- turn.target = assistantTarget{applet: applet}
+ var initialTrajectory string
+ applet, initialTrajectory, err = c.createAssistantApplet(ctx, lease, request.Model, assistantPromptText(contents))
+ turn.target = assistantTarget{applet: applet, trajectory: initialTrajectory, newApplet: true, agency: agency}
case trajectory != nil:
- turn.target = assistantTarget{applet: applet, trajectory: trajectory.ID}
+ cursor, interactionID := trajectory.Cursor, trajectory.InteractionID
+ if cursor == 0 && opened.trajectory == trajectory.ID && opened.cursor > 0 {
+ cursor, interactionID = opened.cursor, opened.interactionID
+ }
+ turn.target = assistantTarget{applet: applet, trajectory: trajectory.ID, cursor: cursor, interactionID: interactionID, agency: agency}
turn.previous = trajectory.Tip
default:
c.startAssistantTrajectory(ctx, request.AccountID, applet)
- turn.target = assistantTarget{applet: applet, fresh: true}
+ newTraj := ""
+ if agency {
+ // 已有应用中的新 trajectory 由客户端生成大写 UUIDv4 写入 field 2
+ newTraj = strings.ToUpper(uuid.NewString())
+ }
+ turn.target = assistantTarget{applet: applet, trajectory: newTraj, fresh: true, agency: agency}
}
uploaded.Wait()
if err = cmp.Or(err, uploadErr); err != nil {
@@ -546,19 +700,48 @@ func (c *Client) prepareAssistantTurn(ctx context.Context, lease *AccountLease,
return turn, nil
}
-// sendAssistant 在账户的 Build 应用中提交本轮并返回任务流
-// 回复完整结束时保存 trajectory 的续接位置,否则取消未完成的任务并放弃续接位置
-// 续接、重答与应用重建的规则见 docs/build.md 的“对话与应用”“RPC 顺序”与“写代码助手错误处理”各节
-func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, entry modelEntry) (*RPCResponse, func(io.Reader, func(Event) error) error, error) {
- reason := ""
- if request.Unary {
- reason = "Build 写代码助手使用服务端流,收集完成后返回"
+// canContinueAssistantTrajectory 判断已保存的 trajectory 能否在当前协议下直接续接,不能时在同一应用内新开 trajectory 并转录历史
+// legacy 切到 agency 要求 trajectory 或 LoadHistory 已回填有效游标,agency 切到 legacy 不续接
+func canContinueAssistantTrajectory(trajectory *assistantTrajectory, opened assistantOpenedApplet, agency bool) bool {
+ if trajectory == nil {
+ return false
+ }
+ if agency {
+ if trajectory.Protocol == assistantProtocolAgency {
+ return true
+ }
+ return trajectory.Cursor > 0 || (opened.trajectory == trajectory.ID && opened.cursor > 0)
}
- reportUpstreamMode(ctx, assistantOfflineMethod, "stream", 0, reason)
+ return trajectory.Protocol != assistantProtocolAgency
+}
+
+// assistantGeneration 是 legacy CodeAssistantOffline 返回的任务与所在 trajectory
+type assistantGeneration struct {
+ task string
+ trajectory string
+}
+
+// sendAssistant 按账户选定的协议(agency 走 StreamRunAgentTask,legacy 走 CodeAssistantOffline)提交本轮并返回任务流
+// 回复完整结束时保存 trajectory 的续接位置与游标,否则取消未完成的任务并放弃续接位置,每轮结束异步发送 MakerSuiteService/Log
+func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, entry modelEntry) (*RPCResponse, func(io.Reader, func(Event) error) error, error) {
lease, ok := AccountLeaseFromContext(ctx)
if !ok {
return nil, nil, fmt.Errorf("Build 写代码助手请求缺少账户租约")
}
+ agency, err := c.resolveAssistantProtocol(ctx, request.AccountID)
+ if err != nil {
+ return nil, nil, err
+ }
+ rpcMethod := assistantOfflineMethod
+ if agency {
+ rpcMethod = assistantStreamMethod
+ }
+ reason := ""
+ if request.Unary {
+ reason = "Build 写代码助手使用服务端流,收集完成后返回"
+ }
+ reportUpstreamMode(ctx, rpcMethod, "stream", 0, reason)
+ c.assistants.yieldPostTurn(ctx, request.AccountID)
var functions []string
if request.Tools.ToolConfig.Mode != "none" {
for _, function := range request.Tools.Functions {
@@ -569,21 +752,25 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
historyDigest := assistantHistoryDigest(request.Contents)
links := turnLinks(request.Contents)
request.Contents = assistantSearches.restore(apiKey, request.Contents)
- cleanup := &assistantCleanup{client: c, ctx: context.WithoutCancel(ctx), lease: lease, release: lease.Retain()}
- var streamBody []byte
+ cleanup := &assistantCleanup{client: c, ctx: context.WithoutCancel(ctx), lease: lease, agency: agency, startedAt: time.Now(), release: lease.Retain()}
var stream *RPCResponse
+ var legacyStreamBody []byte
for recreated := false; ; recreated = true {
- turn, err := c.prepareAssistantTurn(ctx, lease, request, links, apiKey)
+ turn, err := c.prepareAssistantTurn(ctx, lease, request, links, apiKey, agency)
if err != nil {
cleanup.run()
return nil, nil, err
}
cleanup.turn = turn
- var generation assistantGeneration
- generation, streamBody, stream, err = c.openAssistantGeneration(ctx, turn.request, entry, turn.target)
- cleanup.generation.Store(&generation)
+ runID := strings.ToUpper(uuid.NewString())
+ var legacyGen assistantGeneration
+ if agency {
+ stream, err = c.openAssistantAgencyGeneration(ctx, turn.request, entry, turn.target, runID)
+ } else {
+ legacyGen, legacyStreamBody, stream, err = c.openAssistantLegacyGeneration(ctx, turn.request, entry, turn.target, runID)
+ }
var failure *RPCError
- if err != nil && !recreated && generation.task == "" && !turn.target.created() && errors.As(err, &failure) && failure.StatusCode == http.StatusNotFound {
+ if err != nil && !recreated && legacyGen.task == "" && !turn.target.created() && errors.As(err, &failure) && failure.StatusCode == http.StatusNotFound {
// 应用或 trajectory 已不存在:重新打开应用,应用已删除时新建,续接的 trajectory 不再续接
c.assistants.forget(request.AccountID)
if turn.previous == "" {
@@ -594,9 +781,17 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
}
}
if err != nil {
+ if legacyGen.task != "" {
+ cleanup.beginLegacyRun(runID, legacyGen)
+ }
cleanup.run()
return nil, nil, err
}
+ if agency {
+ cleanup.beginRun(runID, turn.target)
+ } else {
+ cleanup.beginLegacyRun(runID, legacyGen)
+ }
break
}
turn := cleanup.turn
@@ -613,20 +808,48 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
}
stream.Body = &assistantStreamBody{ReadCloser: stream.Body, cleanup: cleanup}
return stream, func(source io.Reader, emit func(Event) error) error {
- newDecoder := func(streamBody []byte) *AssistantStreamDecoder {
- return &AssistantStreamDecoder{Functions: functions, Reopen: func() (io.ReadCloser, error) {
- reopened, err := c.do(ctx, assistantStreamMethod, request.AccountID, request.ID, streamBody, true)
- if err != nil {
- return nil, err
+ newDecoder := func(baseReq GenerateRequest, streamBody []byte) *AssistantStreamDecoder {
+ if !agency {
+ return &AssistantStreamDecoder{
+ Legacy: true,
+ Functions: functions,
+ Reopen: func() (io.ReadCloser, error) {
+ reopened, err := c.do(ctx, assistantLegacyStreamMethod, request.AccountID, request.ID, streamBody, true)
+ if err != nil {
+ return nil, err
+ }
+ return reopened.Body, nil
+ },
}
- return reopened.Body, nil
- }}
+ }
+ return &AssistantStreamDecoder{
+ Functions: functions,
+ OnMeta: func(trajectory string, cursor int64, interactionID string, cancelStep *int64) {
+ cleanup.updateMeta(trajectory, cursor, interactionID, cancelStep)
+ },
+ Reopen: func() (io.ReadCloser, error) {
+ runID, traj, cursor, interactionID := cleanup.snapshotResume()
+ if traj == "" {
+ return nil, fmt.Errorf("StreamRunAgentTask 重连缺少 trajectory ID")
+ }
+ reopenReq := baseReq
+ reopenReq.Contents = nil
+ reopened, err := c.openAssistantAgencyGeneration(ctx, reopenReq, entry, assistantTarget{
+ applet: turn.target.applet, trajectory: traj, cursor: cursor, interactionID: interactionID, agency: true,
+ }, runID)
+ if err != nil {
+ return nil, err
+ }
+ return reopened.Body, nil
+ },
+ }
}
var answer strings.Builder
var reply []Part
var usage *Usage
var finish *Event
record := func(event Event) error {
+ cleanup.markFirstEvent()
switch event.Kind {
case EventText:
answer.WriteString(event.Text)
@@ -646,7 +869,7 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
}
return emit(event)
}
- decoder := newDecoder(streamBody)
+ decoder := newDecoder(turn.request, legacyStreamBody)
err := DecodeAssistantStream(source, decoder, record)
// searches 是之前各任务完成的 search_web
var searches []string
@@ -668,26 +891,58 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
searches = append(searches, decoder.searches...)
followUp := turn.request
followUp.Contents = []Content{{Role: RoleUser, Parts: []Part{{Text: prompt}}}}
- current := cleanup.generation.Load()
- next, nextBody, follow, openErr := c.openAssistantGeneration(ctx, followUp, entry, assistantTarget{applet: turn.target.applet, trajectory: current.trajectory})
- cleanup.generation.Store(&next)
- decoder = newDecoder(nextBody)
- if err = openErr; err != nil {
- break
+ _, traj, cursor, interactionID := cleanup.snapshotResume()
+ nextTarget := assistantTarget{applet: turn.target.applet, trajectory: traj, cursor: cursor, interactionID: interactionID, agency: agency}
+ nextRunID := strings.ToUpper(uuid.NewString())
+ var follow *RPCResponse
+ var nextStreamBody []byte
+ if agency {
+ var openErr error
+ follow, openErr = c.openAssistantAgencyGeneration(ctx, followUp, entry, nextTarget, nextRunID)
+ if err = openErr; err != nil {
+ break
+ }
+ cleanup.beginRun(nextRunID, nextTarget)
+ } else {
+ var nextGen assistantGeneration
+ var openErr error
+ nextGen, nextStreamBody, follow, openErr = c.openAssistantLegacyGeneration(ctx, followUp, entry, nextTarget, nextRunID)
+ if err = openErr; err != nil {
+ if nextGen.task != "" {
+ cleanup.beginLegacyRun(nextRunID, nextGen)
+ }
+ break
+ }
+ cleanup.beginLegacyRun(nextRunID, nextGen)
}
+ decoder = newDecoder(followUp, nextStreamBody)
err = errors.Join(DecodeAssistantStream(follow.Body, decoder, record), follow.Body.Close())
}
cleanup.completed.Store(decoder.failed || err == nil && decoder.finished && !decoder.stopped)
if err != nil {
+ cleanup.setError(err)
return err
}
assistantSearches.store(apiKey, historyDigest, answer.String(), append(searches, decoder.searches...))
if decoder.finished && !decoder.stopped && !decoder.malformed && !decoder.invalidTool {
- cleanup.record.Store(&assistantTrajectory{
- Tip: assistantTip(apiKey, turnLinkDigest(links[len(links)-1].digest, true, reply)), ID: cleanup.generation.Load().trajectory, HistoryGroups: turn.historyGroups, Context: turn.context,
- })
+ _, traj, cursor, interactionID := cleanup.snapshotResume()
+ proto := assistantProtocolLegacy
+ if agency {
+ proto = assistantProtocolAgency
+ }
history := append(slices.Clone(request.Contents), Content{Role: RoleAssistant, Parts: []Part{{Text: answer.String()}}})
cleanup.history.Store(&history)
+ if traj != "" {
+ cleanup.record.Store(&assistantTrajectory{
+ Tip: assistantTip(apiKey, turnLinkDigest(links[len(links)-1].digest, true, reply)),
+ ID: traj,
+ Cursor: cursor,
+ InteractionID: interactionID,
+ Protocol: proto,
+ HistoryGroups: turn.historyGroups,
+ Context: turn.context,
+ })
+ }
}
if !decoder.called && (decoder.malformed || decoder.invalidTool) {
if finish == nil {
@@ -702,21 +957,48 @@ func (c *Client) sendAssistant(ctx context.Context, request GenerateRequest, ent
}, nil
}
-// assistantGeneration 是 CodeAssistantOffline 返回的任务与所在 trajectory
-type assistantGeneration struct {
- task string
- trajectory string
+// openAssistantAgencyGeneration 经 AppletGenerationService/StreamRunAgentTask 以受保护流式 RPC 提交请求并返回任务流
+func (c *Client) openAssistantAgencyGeneration(ctx context.Context, request GenerateRequest, entry modelEntry, target assistantTarget, runID string) (*RPCResponse, error) {
+ body, proofAt, err := EncodeAssistantRequest(request, entry.defaults, target, runID)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err)
+ }
+ transport, ok := c.protected.(AppletProtectedTransport)
+ if !ok {
+ return nil, fmt.Errorf("AI Studio 受保护传输不支持 Build 写代码助手请求")
+ }
+ rpc := newRPCRequest(assistantStreamMethod, request.AccountID, request.ID, body, true)
+ rpc.URL = appletGenerationRPCBase + assistantStreamMethod
+ rpc.ProofAt = proofAt
+ c.applyAssistantBenefitTier(request.AccountID, rpc.Header)
+ page := ""
+ if len(request.Contents) > 0 {
+ page = contentsText(request.Contents[len(request.Contents)-1:])
+ }
+ response, err := transport.DoProtectedApplet(ctx, AppletProtectedRequest{
+ Model: request.Model,
+ Binding: assistantAgentBinding(target.applet, request.Contents),
+ ProofField: assistantProofField,
+ PagePrompt: page,
+ }, rpc)
+ if err == nil {
+ response, err = validateRPCResponse(assistantStreamMethod, response)
+ }
+ if err != nil {
+ return nil, fmt.Errorf("发送 AI Studio %s: %w", assistantStreamMethod, err)
+ }
+ return response, nil
}
-// openAssistantGeneration 把请求的对话轮提交到 target 并打开任务流,返回任务、任务流请求正文与任务流;任务流请求的第 4 项为应用 ID
-func (c *Client) openAssistantGeneration(ctx context.Context, request GenerateRequest, entry modelEntry, target assistantTarget) (assistantGeneration, []byte, *RPCResponse, error) {
- body, proofAt, err := EncodeAssistantRequest(request, entry.defaults, target, strings.ToUpper(uuid.NewString()))
+// openAssistantLegacyGeneration 经 MakerSuiteService/CodeAssistantOffline 提交任务,再经 StreamCodeAssistantOfflineGeneration 打开任务流
+func (c *Client) openAssistantLegacyGeneration(ctx context.Context, request GenerateRequest, entry modelEntry, target assistantTarget, runID string) (assistantGeneration, []byte, *RPCResponse, error) {
+ body, proofAt, err := EncodeLegacyAssistantRequest(request, entry.defaults, target, runID)
if err != nil {
return assistantGeneration{}, nil, nil, fmt.Errorf("%w: %v", ErrInvalidArgument, err)
}
rpc := newRPCRequest(assistantOfflineMethod, request.AccountID, request.ID, body, false)
rpc.ProofAt = proofAt
- c.applyBenefitTier(rpc.Method, request.AccountID, rpc.Header)
+ c.applyAssistantBenefitTier(request.AccountID, rpc.Header)
response, err := c.protected.DoProtected(ctx, request, rpc)
if err == nil {
response, err = validateRPCResponse(assistantOfflineMethod, response)
@@ -725,13 +1007,42 @@ func (c *Client) openAssistantGeneration(ctx context.Context, request GenerateRe
return assistantGeneration{}, nil, nil, fmt.Errorf("发送 AI Studio %s: %w", assistantOfflineMethod, err)
}
generation, err := decodeAssistantGeneration(response.Body)
- response.Body.Close()
+ if closeErr := response.Body.Close(); err == nil && closeErr != nil {
+ err = closeErr
+ }
if err != nil {
return assistantGeneration{}, nil, nil, err
}
- streamBody, _ := json.Marshal([]any{generation.task, nil, nil, target.applet})
- stream, err := c.do(ctx, assistantStreamMethod, request.AccountID, request.ID, streamBody, true)
- return generation, streamBody, stream, err
+ streamBody, err := json.Marshal([]any{generation.task, nil, nil, target.applet})
+ if err != nil {
+ return generation, nil, nil, err
+ }
+ stream, err := c.do(ctx, assistantLegacyStreamMethod, request.AccountID, request.ID, streamBody, true)
+ if err != nil {
+ return generation, nil, nil, err
+ }
+ return generation, streamBody, stream, nil
+}
+
+// decodeAssistantGeneration 读取 legacy CodeAssistantOffline 响应 [任务 ID, trajectory ID]
+func decodeAssistantGeneration(source io.Reader) (assistantGeneration, error) {
+ raw, err := io.ReadAll(source)
+ if err != nil {
+ return assistantGeneration{}, fmt.Errorf("读取 AI Studio %s: %w", assistantOfflineMethod, err)
+ }
+ values, err := rawArray(raw, "$", raw)
+ if err != nil {
+ return assistantGeneration{}, withMethod(err, assistantOfflineMethod)
+ }
+ task, err := rawString(rawAt(values, 0), "$[0]", raw)
+ if err != nil || task == "" {
+ return assistantGeneration{}, &ProtocolEvidenceError{Method: assistantOfflineMethod, Path: "$[0]", Detail: "缺少任务 ID", Raw: cloneRaw(raw)}
+ }
+ trajectory, err := rawString(rawAt(values, 1), "$[1]", raw)
+ if err != nil || trajectory == "" {
+ return assistantGeneration{}, &ProtocolEvidenceError{Method: assistantOfflineMethod, Path: "$[1]", Detail: "缺少 trajectory ID", Raw: cloneRaw(raw)}
+ }
+ return assistantGeneration{task: task, trajectory: trajectory}, nil
}
// assistantSearches 是本进程写代码助手回复的 search_web 结果
@@ -821,6 +1132,14 @@ func (history *assistantSearchHistory) restore(apiKey string, contents []Content
return restored
}
+// assistantAttachmentExtensions 是写代码助手附件文件名按 MIME 取的扩展名,官网上传时保留文件的扩展名
+var assistantAttachmentExtensions = map[string]string{
+ "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif", "image/heic": ".heic", "image/heif": ".heif",
+ "application/pdf": ".pdf", "application/json": ".json", "text/plain": ".txt", "text/markdown": ".md", "text/csv": ".csv", "text/html": ".html",
+ "audio/mpeg": ".mp3", "audio/wav": ".wav", "audio/ogg": ".ogg", "audio/flac": ".flac", "audio/aac": ".aac",
+ "video/mp4": ".mp4", "video/webm": ".webm", "video/quicktime": ".mov",
+}
+
// uploadAssistantAttachments 把对话轮中的内联附件上传为写代码助手的附件引用
func (c *Client) uploadAssistantAttachments(ctx context.Context, accountID string, contents []Content) ([]Content, error) {
rewritten := make([]Content, len(contents))
@@ -842,44 +1161,34 @@ func (c *Client) uploadAssistantAttachments(ctx context.Context, accountID strin
return nil, fmt.Errorf("上传写代码助手附件 %d: %w", count, err)
}
parts[partIndex].InlineData = nil
- parts[partIndex].Upload = &UploadRef{MIME: blob.MIME, Path: path, Name: fmt.Sprintf("attachment-%d", count), Size: int64(len(blob.Data))}
+ parts[partIndex].Upload = &UploadRef{MIME: blob.MIME, Path: path, Name: fmt.Sprintf("attachment-%d%s", count, assistantAttachmentExtensions[blob.MIME]), Size: int64(len(blob.Data))}
}
rewritten[index] = Content{Role: content.Role, Parts: parts}
}
return rewritten, nil
}
-// decodeAssistantGeneration 读取 CodeAssistantOffline 响应 [任务 ID, trajectory ID]
-func decodeAssistantGeneration(source io.Reader) (assistantGeneration, error) {
- raw, err := io.ReadAll(source)
- if err != nil {
- return assistantGeneration{}, fmt.Errorf("读取 AI Studio %s: %w", assistantOfflineMethod, err)
- }
- values, err := rawArray(raw, "$", raw)
- if err != nil {
- return assistantGeneration{}, withMethod(err, assistantOfflineMethod)
- }
- task, err := rawString(rawAt(values, 0), "$[0]", raw)
- if err != nil || task == "" {
- return assistantGeneration{}, &ProtocolEvidenceError{Method: assistantOfflineMethod, Path: "$[0]", Detail: "缺少任务 ID", Raw: cloneRaw(raw)}
- }
- trajectory, err := rawString(rawAt(values, 1), "$[1]", raw)
- if err != nil || trajectory == "" {
- return assistantGeneration{}, &ProtocolEvidenceError{Method: assistantOfflineMethod, Path: "$[1]", Detail: "缺少 trajectory ID", Raw: cloneRaw(raw)}
- }
- return assistantGeneration{task: task, trajectory: trajectory}, nil
-}
-
-// assistantCleanup 在任务流关闭后按本轮是否完整结束保存或放弃 trajectory 的续接位置,取消未完成的任务或发送回复后的伴随请求,完成后归还请求开始时保留的账户租约
+// assistantCleanup 在任务流关闭后按本轮是否完整结束保存或放弃 trajectory 的续接位置,取消未完成的任务、发送每轮 MakerSuiteService/Log 与回复后的伴随请求,完成后归还请求开始时保留的账户租约
type assistantCleanup struct {
client *Client
// ctx 是不随请求取消、带有账户租约的请求上下文
- ctx context.Context
- lease *AccountLease
- turn assistantTurn
- // generation 是 trajectory 中最近提交的任务
- generation atomic.Pointer[assistantGeneration]
- completed atomic.Bool
+ ctx context.Context
+ lease *AccountLease
+ agency bool
+ startedAt time.Time
+ turn assistantTurn
+ // runMu 保护本轮任务的运行标识、legacy 任务 ID、trajectory、游标、取消步骤号与首字/错误记录
+ runMu sync.Mutex
+ started bool
+ runID string
+ legacyTask string
+ trajectory string
+ cursor int64
+ interactionID string
+ cancelStep *int64
+ firstEvent time.Duration
+ errMsg string
+ completed atomic.Bool
// record 是本轮回复完整结束后 trajectory 的续接位置
record atomic.Pointer[assistantTrajectory]
// history 是本轮回复完整结束后包含回复的对话
@@ -888,26 +1197,166 @@ type assistantCleanup struct {
once sync.Once
}
-// cancel 取消 trajectory 中最近提交的任务,正文为 [任务 ID, 应用 ID];任务已在上游结束时上游返回 FAILED_PRECONDITION,同样视为已停止
+// beginRun 记录最新一次 agency StreamRunAgentTask 调用的标识与初始目标
+func (cleanup *assistantCleanup) beginRun(runID string, target assistantTarget) {
+ cleanup.runMu.Lock()
+ defer cleanup.runMu.Unlock()
+ cleanup.started = true
+ cleanup.runID = runID
+ cleanup.legacyTask = ""
+ if target.trajectory != "" {
+ cleanup.trajectory = target.trajectory
+ }
+ if !target.fresh && target.cursor > cleanup.cursor {
+ cleanup.cursor = target.cursor
+ }
+ if !target.fresh && target.interactionID != "" {
+ cleanup.interactionID = target.interactionID
+ }
+ cleanup.cancelStep = nil
+}
+
+// beginLegacyRun 记录最新一次 legacy CodeAssistantOffline 调用的标识、任务 ID 与 trajectory
+func (cleanup *assistantCleanup) beginLegacyRun(runID string, gen assistantGeneration) {
+ cleanup.runMu.Lock()
+ defer cleanup.runMu.Unlock()
+ cleanup.started = gen.task != ""
+ cleanup.runID = runID
+ cleanup.legacyTask = gen.task
+ if gen.trajectory != "" {
+ cleanup.trajectory = gen.trajectory
+ }
+ cleanup.cancelStep = nil
+}
+
+// markFirstEvent 记录本轮首个解码事件到达的耗时(仅记录第一次)
+func (cleanup *assistantCleanup) markFirstEvent() {
+ cleanup.runMu.Lock()
+ if cleanup.firstEvent == 0 {
+ cleanup.firstEvent = max(time.Since(cleanup.startedAt), time.Millisecond)
+ }
+ cleanup.runMu.Unlock()
+}
+
+// setError 记录本轮失败原因,供 MakerSuiteService/Log 闭环上报
+func (cleanup *assistantCleanup) setError(err error) {
+ if err == nil {
+ return
+ }
+ msg := err.Error()
+ var failure *RPCError
+ if errors.As(err, &failure) && failure.Message != "" {
+ msg = failure.Message
+ }
+ cleanup.runMu.Lock()
+ cleanup.errMsg = msg
+ cleanup.runMu.Unlock()
+}
+
+// updateMeta 在流解码收到 trajectory、游标、交互 ID 或取消步骤号时同步更新运行态
+func (cleanup *assistantCleanup) updateMeta(trajectory string, cursor int64, interactionID string, cancelStep *int64) {
+ cleanup.runMu.Lock()
+ defer cleanup.runMu.Unlock()
+ if trajectory != "" {
+ cleanup.trajectory = trajectory
+ }
+ if cursor > cleanup.cursor {
+ cleanup.cursor = cursor
+ }
+ if interactionID != "" {
+ cleanup.interactionID = interactionID
+ }
+ if cancelStep != nil {
+ step := *cancelStep
+ cleanup.cancelStep = &step
+ }
+}
+
+// snapshotResume 返回重连或续接所需的 runID、trajectory、游标与交互 ID
+func (cleanup *assistantCleanup) snapshotResume() (string, string, int64, string) {
+ cleanup.runMu.Lock()
+ defer cleanup.runMu.Unlock()
+ return cleanup.runID, cleanup.trajectory, cleanup.cursor, cleanup.interactionID
+}
+
+// assistantRunSnapshot 是一轮运行在某一时刻的状态
+type assistantRunSnapshot struct {
+ // started 表示任务已启动
+ started bool
+ runID string
+ legacyTask string
+ trajectory string
+ // cancelStep 是取消时回滚到的步骤号
+ cancelStep *int64
+ firstEvent time.Duration
+ errMsg string
+}
+
+// snapshotCancel 返回取消与结束上报所需的运行状态
+func (cleanup *assistantCleanup) snapshotCancel() assistantRunSnapshot {
+ cleanup.runMu.Lock()
+ defer cleanup.runMu.Unlock()
+ var step *int64
+ if cleanup.cancelStep != nil {
+ value := *cleanup.cancelStep
+ step = &value
+ }
+ return assistantRunSnapshot{
+ started: cleanup.started, runID: cleanup.runID, legacyTask: cleanup.legacyTask, trajectory: cleanup.trajectory,
+ cancelStep: step, firstEvent: cleanup.firstEvent, errMsg: cleanup.errMsg,
+ }
+}
+
+// cancel 按协议取消正在运行的任务:agency 发 CancelAgentTask + ListAppletSecrets,legacy 发 CancelCodeAssistantOfflineGeneration;任务已结束或不存在视为已停止
func (cleanup *assistantCleanup) cancel(ctx context.Context) error {
- body, _ := json.Marshal([]any{cleanup.generation.Load().task, cleanup.turn.target.applet})
- response, err := cleanup.client.do(ctx, "CancelCodeAssistantOfflineGeneration", cleanup.lease.Account().ID, "", body, false)
+ run := cleanup.snapshotCancel()
+ accountID := cleanup.lease.Account().ID
+ if !cleanup.agency {
+ if run.legacyTask == "" {
+ return nil
+ }
+ body, _ := json.Marshal([]any{run.legacyTask, cleanup.turn.target.applet})
+ response, err := cleanup.client.do(ctx, assistantLegacyCancelMethod, accountID, "", body, false)
+ if err == nil {
+ _, err = io.Copy(io.Discard, response.Body)
+ err = errors.Join(err, response.Body.Close())
+ }
+ if failure := (*RPCError)(nil); errors.As(err, &failure) && failure.Code == 9 {
+ return nil
+ }
+ return err
+ }
+ if run.trajectory == "" {
+ return nil
+ }
+ payload := []any{cleanup.turn.target.applet, run.trajectory}
+ if run.cancelStep != nil {
+ payload = append(payload, *run.cancelStep)
+ }
+ body, _ := json.Marshal(payload)
+ rpc := newRPCRequest(assistantCancelMethod, accountID, "", body, false)
+ rpc.URL = appletGenerationRPCBase + assistantCancelMethod
+ rpc.Header.Set("Priority", "u=0")
+ cleanup.client.applyAssistantBenefitTier(accountID, rpc.Header)
+ response, err := cleanup.client.send(ctx, rpc)
if err == nil {
_, err = io.Copy(io.Discard, response.Body)
err = errors.Join(err, response.Body.Close())
}
- if failure := (*RPCError)(nil); errors.As(err, &failure) && failure.Code == 9 {
+ cleanup.client.listAssistantSecrets(ctx, accountID, cleanup.turn.target.applet)
+ if failure := (*RPCError)(nil); errors.As(err, &failure) && (failure.Code == 9 || failure.Code == 5) {
return nil
}
return err
}
-// run 执行一次清理:保存或放弃续接位置,未完成的任务与回复后的伴随请求在后台以独立期限发送,之后归还租约;只剩伴随请求时账户立即可接其他 -build 请求
+// run 执行一次清理:保存或放弃续接位置,未完成的任务取消、每轮结束的 MakerSuiteService/Log 与回复后的伴随请求都在后台以独立期限发送,之后归还租约;只剩伴随请求时账户立即可接其他 -build 请求
func (cleanup *assistantCleanup) run() {
cleanup.once.Do(func() {
accountID := cleanup.lease.Account().ID
- generation := cleanup.generation.Load()
- started := generation != nil && generation.task != ""
+ run := cleanup.snapshotCancel()
+ started, runID, firstEvent, errMsg := run.started, run.runID, run.firstEvent, run.errMsg
+ total := time.Since(cleanup.startedAt)
record := cleanup.record.Load()
var err error
switch {
@@ -919,25 +1368,50 @@ func (cleanup *assistantCleanup) run() {
if err != nil {
slog.Warn("保存 Build 写代码助手续接位置失败", "account", accountID, "error", err)
}
- cancel := started && !cleanup.completed.Load()
- if record == nil && !cancel {
+ hasCancelTarget := run.trajectory != ""
+ if !cleanup.agency {
+ hasCancelTarget = run.legacyTask != ""
+ }
+ cancel := started && hasCancelTarget && !cleanup.completed.Load()
+ shouldLog := runID != "" && cleanup.turn.target.applet != ""
+ if record == nil && !cancel && !shouldLog {
cleanup.finish()
return
}
+ ctx, stop := context.WithTimeout(cleanup.ctx, assistantCleanupTimeout)
+ var prevPost, thisPost *assistantPostTurn
if !cancel {
+ prevPost, thisPost = cleanup.client.assistants.startPostTurn(accountID, stop)
cleanup.lease.finishAssistantGeneration()
}
go func() {
defer cleanup.finish()
- ctx, stop := context.WithTimeout(cleanup.ctx, assistantCleanupTimeout)
defer stop()
+ if thisPost != nil {
+ defer cleanup.client.assistants.finishPostTurn(accountID, thisPost)
+ if prevPost != nil {
+ <-prevPost.done
+ }
+ }
if !cancel {
defer afterServiceStop(ctx, stop)()
- cleanup.client.afterAssistantTurn(ctx, accountID, cleanup.turn.request.Model, cleanup.turn.target, *cleanup.history.Load())
+ if shouldLog {
+ cleanup.client.logAssistantTurn(ctx, accountID, cleanup.turn.target, runID, cleanup.turn.request.Contents, firstEvent, total, errMsg)
+ }
+ if record != nil {
+ cleanup.client.afterAssistantTurn(ctx, accountID, cleanup.turn.request.Model, cleanup.turn.target, *cleanup.history.Load())
+ }
return
}
if err := cleanup.cancel(ctx); err != nil {
- slog.Warn("Build 写代码助手取消任务失败", "account", accountID, "method", "CancelCodeAssistantOfflineGeneration", "applet", cleanup.turn.target.applet, "error", err)
+ method := assistantCancelMethod
+ if !cleanup.agency {
+ method = assistantLegacyCancelMethod
+ }
+ slog.Warn("Build 写代码助手取消任务失败", "account", accountID, "method", method, "applet", cleanup.turn.target.applet, "error", err)
+ }
+ if shouldLog {
+ cleanup.client.logAssistantTurn(ctx, accountID, cleanup.turn.target, runID, cleanup.turn.request.Contents, firstEvent, total, "")
}
}()
})
diff --git a/internal/aistudio/assistant_applet.go b/internal/aistudio/assistant_applet.go
index ec4082fb..ade4dc99 100644
--- a/internal/aistudio/assistant_applet.go
+++ b/internal/aistudio/assistant_applet.go
@@ -1,7 +1,9 @@
package aistudio
import (
+ "cmp"
"context"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -9,12 +11,15 @@ import (
"log/slog"
"net/http"
"slices"
+ "strconv"
"strings"
"sync"
"time"
)
const (
+ // appletGenerationRPCBase 是官网 Build agency 生成与取消 RPC 的基础地址
+ appletGenerationRPCBase = "https://alkalimakersuiteapplets.pa.clients6.google.com/$rpc/google.internal.alkali.applications.makersuite.v1.applets.AppletGenerationService/"
// assistantAppletTitle 与 assistantAppletDescription 是官网新建应用时的默认标题与简介
assistantAppletTitle = "Untitled"
assistantAppletDescription = "Generated by Gemini."
@@ -33,17 +38,19 @@ type AppletProtectedTransport interface {
DoProtectedApplet(context.Context, AppletProtectedRequest, RPCRequest) (*RPCResponse, error)
}
-// AppletProtectedRequest 是 Build 应用与云项目 RPC 的 proof 参数:proof 绑定 Binding 的 SHA-256,Digest 非空时直接绑定 Digest
+// AppletProtectedRequest 是 Build 应用、云项目与 agency 生成 RPC 的 proof 参数:proof 绑定 Binding 的 SHA-256,Digest 非空时直接绑定 Digest
type AppletProtectedRequest struct {
Model string
Binding string
Digest string
ProofField int
+ // PagePrompt 不为空时由浏览器页面输入框携带(用于 StreamRunAgentTask),其余应用 RPC 为空
+ PagePrompt string
}
var _ AppletProtectedTransport = (*WorkerProtectedTransport)(nil)
-// DoProtectedApplet 写入 fresh proof 后经账户的 WAA 运行时发送 Build 应用与云项目 RPC,页面输入框为空
+// DoProtectedApplet 写入 fresh proof 后经账户的 WAA 运行时发送 Build 应用、云项目与 agency 生成 RPC
func (t *WorkerProtectedTransport) DoProtectedApplet(ctx context.Context, request AppletProtectedRequest, rpc RPCRequest) (*RPCResponse, error) {
selection := AccountSelection{ModelID: request.Model, Method: "generateContent", AccountID: rpc.AccountID}
proof := ""
@@ -64,12 +71,17 @@ func (t *WorkerProtectedTransport) DoProtectedApplet(ctx context.Context, reques
}
proof = prepared.Proof
}
- return t.doPrepared(ctx, request.Binding, "", proof, selection, rpc)
+ return t.doPrepared(ctx, request.Binding, request.PagePrompt, proof, selection, rpc)
}
// assistantOpenedApplet 是本进程打开过的账户 Build 应用
type assistantOpenedApplet struct {
applet string
+ // trajectory 是 CreateApplet field 4 或 GetApplet field 2 返回的活跃 trajectory ID
+ trajectory string
+ // cursor 与 interactionID 是 LoadCodeAssistantInteractionHistory 返回的最新续接游标
+ cursor int64
+ interactionID string
// metadata 是应用元数据数组:标题、简介、首条提示、框架与能力
metadata []any
// devURL 是应用开发环境地址
@@ -85,14 +97,107 @@ func (opened assistantOpenedApplet) title() (string, string) {
return title, description
}
-// assistantAppletCache 按账户保存本进程打开过的 Build 应用
+// assistantPostTurn 是账户正在后台执行的上一轮后置伴随任务
+type assistantPostTurn struct {
+ cancel context.CancelFunc
+ done chan struct{}
+}
+
+// assistantAppletCache 按账户保存本进程打开过的 Build 应用、页面协议标志、协议切换日志状态与在途后置伴随任务
type assistantAppletCache struct {
- mu sync.Mutex
- accounts map[string]assistantOpenedApplet
+ mu sync.Mutex
+ protocol string
+ accounts map[string]assistantOpenedApplet
+ flags map[string]*bool
+ protocolLogs map[string]string
+ postTurns map[string]*assistantPostTurn
}
func newAssistantAppletCache() *assistantAppletCache {
- return &assistantAppletCache{accounts: make(map[string]assistantOpenedApplet)}
+ return &assistantAppletCache{
+ protocol: "auto",
+ accounts: make(map[string]assistantOpenedApplet),
+ flags: make(map[string]*bool),
+ protocolLogs: make(map[string]string),
+ postTurns: make(map[string]*assistantPostTurn),
+ }
+}
+
+// setProtocol 更新全局 BUILD_CHAT_PROTOCOL 设置(auto、agency 或 legacy)
+func (cache *assistantAppletCache) setProtocol(mode string) {
+ cache.mu.Lock()
+ cache.protocol = mode
+ cache.mu.Unlock()
+}
+
+// getProtocol 返回当前全局 BUILD_CHAT_PROTOCOL 设置
+func (cache *assistantAppletCache) getProtocol() string {
+ cache.mu.Lock()
+ defer cache.mu.Unlock()
+ return cache.protocol
+}
+
+// setBuildAgencyFlag 记录账户最近一次页面载入的标志 45831005 取值,页面中没有该标志时为 nil
+func (cache *assistantAppletCache) setBuildAgencyFlag(accountID string, flag *bool) {
+ cache.mu.Lock()
+ cache.flags[accountID] = flag
+ cache.mu.Unlock()
+}
+
+// buildAgencyFlag 返回账户记录的标志 45831005 取值,没有记录或页面中没有该标志时为 nil
+func (cache *assistantAppletCache) buildAgencyFlag(accountID string) *bool {
+ cache.mu.Lock()
+ defer cache.mu.Unlock()
+ return cache.flags[accountID]
+}
+
+// markProtocolLogged 在账户的协议或依据发生变化时返回 true 并记下最新值
+func (cache *assistantAppletCache) markProtocolLogged(accountID string, key string) bool {
+ cache.mu.Lock()
+ defer cache.mu.Unlock()
+ if cache.protocolLogs[accountID] == key {
+ return false
+ }
+ cache.protocolLogs[accountID] = key
+ return true
+}
+
+// startPostTurn 登记账户新的后置伴随任务,并取消可能仍在运行的上一任务
+func (cache *assistantAppletCache) startPostTurn(accountID string, cancel context.CancelFunc) (*assistantPostTurn, *assistantPostTurn) {
+ next := &assistantPostTurn{cancel: cancel, done: make(chan struct{})}
+ cache.mu.Lock()
+ prev := cache.postTurns[accountID]
+ cache.postTurns[accountID] = next
+ cache.mu.Unlock()
+ if prev != nil {
+ prev.cancel()
+ }
+ return prev, next
+}
+
+// finishPostTurn 在后置伴随任务结束时关闭完成信号并移除当前登记
+func (cache *assistantAppletCache) finishPostTurn(accountID string, turn *assistantPostTurn) {
+ close(turn.done)
+ cache.mu.Lock()
+ if cache.postTurns[accountID] == turn {
+ delete(cache.postTurns, accountID)
+ }
+ cache.mu.Unlock()
+}
+
+// yieldPostTurn 在发起下一轮 Build 生成前让未结束的上一轮后置伴随任务让位退出,避免后置 RPC 与下一轮生成并发重叠
+func (cache *assistantAppletCache) yieldPostTurn(ctx context.Context, accountID string) {
+ cache.mu.Lock()
+ prev := cache.postTurns[accountID]
+ cache.mu.Unlock()
+ if prev == nil {
+ return
+ }
+ prev.cancel()
+ select {
+ case <-prev.done:
+ case <-ctx.Done():
+ }
}
// get 返回账户打开过的应用 applet
@@ -184,10 +289,10 @@ func (c *Client) assistantProtectedRPC(ctx context.Context, accountID string, me
return raw, nil
}
-// assistantCompanion 发送官网页面在同一时刻发出的伴随请求,失败只记入日志
+// assistantCompanion 发送官网页面在同一时刻发出的伴随请求,失败只记入日志,ctx 被取消时不记
func (c *Client) assistantCompanion(ctx context.Context, accountID string, base string, method string, body any) json.RawMessage {
raw, err := c.assistantRPC(ctx, accountID, base, method, body)
- if err != nil {
+ if err != nil && !errors.Is(ctx.Err(), context.Canceled) {
slog.Warn("Build 写代码助手伴随请求失败", "account", accountID, "method", method, "error", err)
}
return raw
@@ -198,7 +303,9 @@ func (c *Client) provisionAssistantApplet(ctx context.Context, accountID string,
raw, err := c.assistantProtectedRPC(ctx, accountID, "ProvisionAndInitializeApplet", []any{applet, int64(1), nil, nil},
AppletProtectedRequest{Model: model, Binding: applet, ProofField: 4})
if err != nil {
- slog.Warn("Build 写代码助手伴随请求失败", "account", accountID, "method", "ProvisionAndInitializeApplet", "error", err)
+ if !errors.Is(ctx.Err(), context.Canceled) {
+ slog.Warn("Build 写代码助手伴随请求失败", "account", accountID, "method", "ProvisionAndInitializeApplet", "error", err)
+ }
return ""
}
var response []any
@@ -221,8 +328,8 @@ func firstString(values []any, index int) string {
return value
}
-// openAssistantApplet 照官网从 My apps 打开账户的应用:读取应用后同时读取快照、对话记录、功能与待处理的对比、记入最近使用、开通开发环境并列出密钥、任务与 trajectory,之后在后台列出文件、读取日志并签发令牌,本进程每个应用只打开一次;应用以 404 报告不存在时返回 errAssistantAppletGone
-func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, applet string, model string) (assistantOpenedApplet, error) {
+// openAssistantApplet 照官网从 My apps 打开账户的应用:读取应用后同时读取快照、对话记录、功能与待处理的对比、开通开发环境并列出密钥与 trajectory(legacy 模式同步列出离线任务),之后在后台记入最近使用、列出文件、读取日志并签发令牌,本进程每个应用只打开一次;应用以 404 报告不存在时返回 errAssistantAppletGone
+func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, applet string, model string, agency bool) (assistantOpenedApplet, error) {
accountID := lease.Account().ID
if opened, ok := c.assistants.get(accountID, applet); ok {
return opened, nil
@@ -240,6 +347,9 @@ func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, a
return assistantOpenedApplet{}, err
}
title, description := opened.title()
+ historyTrajectory := cmp.Or(opened.trajectory, applet)
+ var historyCursor int64
+ var historyInteraction string
var group sync.WaitGroup
group.Go(func() {
snapshot := []any{applet, true}
@@ -248,9 +358,6 @@ func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, a
}
c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "GetCodeAssistantSnapshot", snapshot)
})
- group.Go(func() {
- c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "StoreRecentApplet", []any{[]any{nil, nil, appletReference(applet), title, description, nil, int64(1)}})
- })
group.Go(func() {
if devURL := c.provisionAssistantApplet(ctx, accountID, model, applet); devURL != "" {
opened.devURL = devURL
@@ -264,18 +371,33 @@ func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, a
})
group.Go(func() { c.listAssistantUnsetSecrets(ctx, accountID, applet) })
group.Go(func() {
- c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "LoadCodeAssistantInteractionHistory", []any{applet, int64(100), nil, nil, nil, applet})
+ historyRaw := c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "LoadCodeAssistantInteractionHistory", []any{applet, int64(100), nil, nil, nil, historyTrajectory})
+ historyCursor, historyInteraction = decodeAssistantHistoryCursor(historyRaw)
})
- group.Go(func() { c.listAssistantGenerations(ctx, accountID, applet) })
+ if !agency {
+ group.Go(func() {
+ c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "ListCodeAssistantOfflineGenerations", []any{applet, int64(100)})
+ })
+ }
group.Go(func() { c.listAssistantTrajectories(ctx, accountID, applet) })
group.Go(func() { c.listAssistantSecrets(ctx, accountID, applet) })
group.Wait()
+ opened.cursor, opened.interactionID = historyCursor, historyInteraction
c.assistants.put(accountID, opened)
+ release := lease.Retain()
background, stop := context.WithTimeout(context.WithoutCancel(ctx), assistantCleanupTimeout)
go func() {
+ defer func() {
+ if err := release(); err != nil {
+ slog.Warn("账户租约释放失败", "account", accountID, "error", err)
+ }
+ }()
defer stop()
defer afterServiceStop(background, stop)()
var group sync.WaitGroup
+ group.Go(func() {
+ c.assistantCompanion(background, accountID, MakerSuiteRPCBase, "StoreRecentApplet", []any{[]any{nil, nil, appletReference(applet), title, description, nil, int64(1)}})
+ })
group.Go(func() { c.listAssistantFiles(background, accountID, applet) })
group.Go(func() { c.assistantLogs(background, accountID, applet) })
group.Go(func() { c.mintAssistantToken(background, accountID, applet, opened.devURL) })
@@ -284,6 +406,42 @@ func (c *Client) openAssistantApplet(ctx context.Context, lease *AccountLease, a
return opened, nil
}
+// decodeAssistantHistoryCursor 从 LoadCodeAssistantInteractionHistory 响应提取 field 4 游标与 field 5 交互 ID
+func decodeAssistantHistoryCursor(raw json.RawMessage) (int64, string) {
+ if len(raw) == 0 {
+ return 0, ""
+ }
+ var root []any
+ if json.Unmarshal(raw, &root) != nil {
+ return 0, ""
+ }
+ cursor := parseAssistantCursor(valueAt(root, 3))
+ interactionID := ""
+ if pair, ok := valueAt(root, 4).([]any); ok {
+ interactionID, _ = valueAt(pair, 0).(string)
+ if pairCursor := parseAssistantCursor(valueAt(pair, 1)); pairCursor > cursor {
+ cursor = pairCursor
+ }
+ }
+ return cursor, interactionID
+}
+
+// parseAssistantCursor 把十进制字符串或数字游标解析为正整数,无法解析时为 0
+func parseAssistantCursor(value any) int64 {
+ switch v := value.(type) {
+ case string:
+ n, err := strconv.ParseInt(v, 10, 64)
+ if err == nil && n > 0 {
+ return n
+ }
+ case float64:
+ if v > 0 {
+ return int64(v)
+ }
+ }
+ return 0
+}
+
// assistantLogs 读取应用开发环境缓存的日志并打开日志流,日志流读到 ctx 结束
func (c *Client) assistantLogs(ctx context.Context, accountID string, applet string) {
body := []any{nil, nil, nil, applet}
@@ -293,7 +451,7 @@ func (c *Client) assistantLogs(ctx context.Context, accountID string, applet str
}
}
-// decodeAssistantApplet 读取 GetApplet 或 CreateApplet 响应第 index 项的应用 [应用 ID, 创建时间, 修改时间, 元数据, ...],快照时间在 field 7,开发环境地址在 field 12
+// decodeAssistantApplet 读取 GetApplet 或 CreateApplet 响应第 index 项的应用 [应用 ID, 创建时间, 修改时间, 元数据, ...],快照时间在 field 7,开发环境地址在 field 12;CreateApplet 顶层 field 4 与 GetApplet 顶层 field 2 为活跃 trajectory ID
func decodeAssistantApplet(raw json.RawMessage, method string, index int) (assistantOpenedApplet, error) {
var root []any
if err := json.Unmarshal(raw, &root); err != nil {
@@ -305,7 +463,12 @@ func decodeAssistantApplet(raw json.RawMessage, method string, index int) (assis
if id == "" || len(metadata) < 2 {
return assistantOpenedApplet{}, &ProtocolEvidenceError{Method: method, Path: fmt.Sprintf("$[%d]", index), Detail: "缺少应用 ID 或元数据", Raw: cloneRaw(raw)}
}
- return assistantOpenedApplet{applet: id, metadata: metadata, devURL: firstString(applet, 11), snapshot: valueAt(applet, 6)}, nil
+ trajectoryIndex := 1
+ if index == 1 {
+ trajectoryIndex = 3
+ }
+ trajectory, _ := valueAt(root, trajectoryIndex).(string)
+ return assistantOpenedApplet{applet: id, trajectory: trajectory, metadata: metadata, devURL: firstString(applet, 11), snapshot: valueAt(applet, 6)}, nil
}
// valueAt 返回 values[index],越界时为 nil
@@ -326,11 +489,6 @@ func (c *Client) listAssistantUnsetSecrets(ctx context.Context, accountID string
c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "ListUnsetAppletSecrets", []any{applet})
}
-// listAssistantGenerations 列出应用中进行中的任务
-func (c *Client) listAssistantGenerations(ctx context.Context, accountID string, applet string) {
- c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "ListCodeAssistantOfflineGenerations", []any{nil, nil, []any{int64(1), int64(2)}, []any{applet}})
-}
-
// listAssistantSecrets 列出应用的密钥
func (c *Client) listAssistantSecrets(ctx context.Context, accountID string, applet string) {
c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "ListAppletSecrets", []any{"applets/" + applet, int64(100)})
@@ -348,12 +506,9 @@ func (c *Client) mintAssistantToken(ctx context.Context, accountID string, apple
}
}
-// startAssistantTrajectory 照官网点击新对话列出应用的 trajectory 与进行中的任务
+// startAssistantTrajectory 照官网点击新对话列出应用的 trajectory
func (c *Client) startAssistantTrajectory(ctx context.Context, accountID string, applet string) {
- var group sync.WaitGroup
- group.Go(func() { c.listAssistantTrajectories(ctx, accountID, applet) })
- group.Go(func() { c.listAssistantGenerations(ctx, accountID, applet) })
- group.Wait()
+ c.listAssistantTrajectories(ctx, accountID, applet)
}
// assistantKeyProject 是 ListCloudProjects 中的云项目
@@ -492,13 +647,12 @@ func (c *Client) generateAssistantKey(ctx context.Context, accountID string, mod
return value, nil
}
-// createAssistantApplet 照官网从 Build 首页新建应用:取得账户的 API key 后以首条提示与 key 新建应用,没有 key 时不带 key,记入最近使用并把应用 ID 写入账户运行状态;binding 为默认标题与首条提示以空格连接
-func (c *Client) createAssistantApplet(ctx context.Context, lease *AccountLease, model string, prompt string) (string, error) {
+// createAssistantApplet 照官网从 Build 首页新建应用:取得账户的 API key 后以首条提示与 key 新建应用,没有 key 时不带 key,把应用 ID 写入账户运行状态并在后台记入最近使用,返回应用 ID 与 CreateApplet field 4 返回的初始 trajectory ID;binding 为默认标题与首条提示以空格连接
+func (c *Client) createAssistantApplet(ctx context.Context, lease *AccountLease, model string, prompt string) (string, string, error) {
accountID := lease.Account().ID
- clicked := time.Now()
key, err := c.resolveAssistantKey(ctx, accountID, model)
if err != nil {
- return "", err
+ return "", "", err
}
binding := assistantAppletTitle
if prompt != "" {
@@ -512,19 +666,32 @@ func (c *Client) createAssistantApplet(ctx context.Context, lease *AccountLease,
[]any{nil, []any{assistantAppletTitle, assistantAppletDescription, prompt, nil, "default"}, nil, nil, int64(1), keyField, nil, nil},
AppletProtectedRequest{Model: model, Binding: binding, ProofField: 8})
if err != nil {
- return "", err
+ return "", "", err
}
opened, err := decodeAssistantApplet(raw, "CreateApplet", 1)
if err != nil {
- return "", err
+ return "", "", err
}
if err := lease.setAssistantApplet(opened.applet); err != nil {
- return "", err
+ return "", "", err
}
c.assistants.put(accountID, opened)
- c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "StoreRecentApplet",
- []any{[]any{assistantTimestamp(clicked), nil, appletReference(opened.applet), assistantAppletTitle, assistantAppletDescription}})
- return opened.applet, nil
+ storedAt := time.Now()
+ release := lease.Retain()
+ bgBase := context.WithoutCancel(ctx)
+ go func() {
+ defer func() {
+ if err := release(); err != nil {
+ slog.Warn("账户租约释放失败", "account", accountID, "error", err)
+ }
+ }()
+ bgCtx, stop := context.WithTimeout(bgBase, assistantCleanupTimeout)
+ defer stop()
+ defer afterServiceStop(bgCtx, stop)()
+ c.assistantCompanion(bgCtx, accountID, MakerSuiteRPCBase, "StoreRecentApplet",
+ []any{[]any{assistantTimestamp(storedAt), nil, appletReference(opened.applet), assistantAppletTitle, assistantAppletDescription}})
+ }()
+ return opened.applet, opened.trajectory, nil
}
// afterAssistantCreated 发送新应用第一段对话提交后官网同时发出的密钥与 trajectory 列表请求
@@ -544,11 +711,7 @@ func (c *Client) afterAssistantTurn(ctx context.Context, accountID string, model
}
var group sync.WaitGroup
save := func() {
- metadata := slices.Clone(opened.metadata)
- for len(metadata) < 11 {
- metadata = append(metadata, nil)
- }
- metadata[5], metadata[7] = target.applet, nil
+ metadata := cleanAssistantMetadata(opened.metadata, target.applet)
c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "SaveApplet", []any{target.applet, metadata})
}
if target.created() {
@@ -599,7 +762,69 @@ func (c *Client) suggestAssistantChips(ctx context.Context, accountID string, mo
return
}
if _, err := c.assistantProtectedRPC(ctx, accountID, "GenerateCodeAssistantSuggestionChips", []any{contents, nil, title, description, nil, applet},
- AppletProtectedRequest{Model: model, Binding: strings.Join(texts, " "), ProofField: 2}); err != nil {
+ AppletProtectedRequest{Model: model, Binding: strings.Join(texts, " "), ProofField: 2}); err != nil && !errors.Is(ctx.Err(), context.Canceled) {
slog.Warn("Build 写代码助手伴随请求失败", "account", accountID, "method", "GenerateCodeAssistantSuggestionChips", "error", err)
}
}
+
+// cleanAssistantMetadata 按官网保存与应用日志规范清洗应用元数据:字段 6(metadata[5])写入 applet ID,清空字段 7(metadata[6])与字段 8(metadata[7])
+func cleanAssistantMetadata(source []any, applet string) []any {
+ metadata := slices.Clone(source)
+ for len(metadata) < 11 {
+ metadata = append(metadata, nil)
+ }
+ metadata[5], metadata[6], metadata[7] = applet, nil, nil
+ return metadata
+}
+
+// assistantDuration 返回官网 MakerSuiteService/Log 使用的毫秒精度 [秒, 纳秒] 时长数组
+func assistantDuration(d time.Duration) []any {
+ if d < 0 {
+ d = 0
+ }
+ secs := int64(d / time.Second)
+ nanos := int64((d % time.Second) / time.Millisecond) * int64(time.Millisecond)
+ return []any{secs, nanos}
+}
+
+// logAssistantTurn 按官网每轮结束(成功、取消或失败)在后台发送 MakerSuiteService/Log 闭环日志,携带与本轮生成相同的 runId、首字耗时、总耗时与轮次类型
+func (c *Client) logAssistantTurn(ctx context.Context, accountID string, target assistantTarget, runID string, contents []Content, firstByte time.Duration, total time.Duration, errMsg string) {
+ if runID == "" || target.applet == "" {
+ return
+ }
+ opened, ok := c.assistants.get(accountID, target.applet)
+ if !ok {
+ return
+ }
+ title, description := opened.title()
+ metadata := cleanAssistantMetadata(opened.metadata, target.applet)
+ metaFile, _ := json.MarshalIndent(struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ RequestFramePermissions []string `json:"requestFramePermissions"`
+ MajorCapabilities []string `json:"majorCapabilities"`
+ }{
+ Name: cmp.Or(title, assistantAppletTitle),
+ Description: cmp.Or(description, assistantAppletDescription),
+ RequestFramePermissions: []string{},
+ MajorCapabilities: []string{"MAJOR_CAPABILITY_SERVER_SIDE_GEMINI_API"},
+ }, "", " ")
+ files := []any{[]any{"metadata.json", base64.StdEncoding.EncodeToString(metaFile), nil}}
+ userPrompt := assistantPromptText(contents)
+ userContent := []any{[]any{[]any{nil, userPrompt}}, "user"}
+ var ttft any
+ if firstByte > 0 {
+ ttft = assistantDuration(firstByte)
+ }
+ response := []any{[]any{[]any{[]any{nil, ""}, []any{nil, ""}}, "model"}}
+ if errMsg != "" {
+ response = append(response, nil, []any{errMsg, int64(1)})
+ }
+ turnType := int64(2)
+ if target.created() || target.fresh {
+ turnType = 1
+ }
+ entry := []any{nil, userContent, ttft, assistantDuration(total), response, turnType}
+ payload := []any{[]any{[]any{runID, []any{entry}, target.applet, []any{metadata, files}}}}
+ c.assistantCompanion(ctx, accountID, MakerSuiteRPCBase, "Log", payload)
+}
diff --git a/internal/aistudio/assistant_session.go b/internal/aistudio/assistant_session.go
index fa3cc211..b4c828e7 100644
--- a/internal/aistudio/assistant_session.go
+++ b/internal/aistudio/assistant_session.go
@@ -12,7 +12,7 @@ const assistantTrajectoryLimit = 200
// assistantApplet 是账户的 Build 写代码助手应用与其中可续接的 trajectory
type assistantApplet struct {
- // ID 是应用 ID,也是应用第一段对话的 trajectory ID
+ // ID 是应用 ID
ID string `json:"id"`
// Trajectories 是可续接的 trajectory,最近续接的排在末尾
Trajectories []assistantTrajectory `json:"trajectories,omitempty"`
@@ -24,6 +24,12 @@ type assistantTrajectory struct {
Tip string `json:"tip"`
// ID 是 trajectory ID
ID string `json:"id"`
+ // Cursor 是 StreamRunAgentTask 返回的最新游标,用于续接时的 field 8 与 field 13
+ Cursor int64 `json:"cursor,omitempty"`
+ // InteractionID 是 StreamRunAgentTask 返回的交互 ID,用于续接时的 field 13
+ InteractionID string `json:"interaction_id,omitempty"`
+ // Protocol 是创建或最近续接该 trajectory 所用的协议(agency 或 legacy)
+ Protocol string `json:"protocol,omitempty"`
// HistoryGroups 是开启 trajectory 时转录在自定义指令中的开头分组数
HistoryGroups int `json:"history_groups,omitempty"`
// Context 是 trajectory 中最近一个说明文件的系统提示词与函数声明摘要,trajectory 没有说明文件时为空
diff --git a/internal/aistudio/assistant_stream.go b/internal/aistudio/assistant_stream.go
index f2d1791e..0a74738f 100644
--- a/internal/aistudio/assistant_stream.go
+++ b/internal/aistudio/assistant_stream.go
@@ -9,19 +9,31 @@ import (
"slices"
"strings"
+ "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative"
"github.com/google/uuid"
)
-// AssistantStreamDecoder 把写代码助手的步骤快照解码为增量事件
+// AssistantStreamDecoder 把写代码助手 StreamRunAgentTask 或旧版 StreamCodeAssistantOfflineGeneration 的步骤快照解码为增量事件
type AssistantStreamDecoder struct {
+ // Legacy 为真时解码旧版 StreamCodeAssistantOfflineGeneration 帧(步骤在 msg[2]);为假时解码 agency StreamRunAgentTask 帧(步骤在 msg[0])
+ Legacy bool
// Functions 是请求声明的函数名,不为空时正文中的调用代码块解码为函数调用
Functions []string
- // Reopen 以同一任务重新打开任务流
- Reopen func() (io.ReadCloser, error)
- emitted map[int64][]string
- usage map[int64]Usage
- searched map[int64]bool
- grounding *GroundingMetadata
+ // Reopen 在流分段(hasMore)或回复完成前正常结束时重连同一任务
+ Reopen func() (io.ReadCloser, error)
+ // OnMeta 在 agency 流收到 trajectory、游标、交互 ID 或首个用户步骤号时通知调用方
+ OnMeta func(trajectory string, cursor int64, interactionID string, cancelStep *int64)
+ emitted map[int64][]string
+ usage map[int64]Usage
+ searched map[int64]bool
+ grounding *GroundingMetadata
+ trajectory string
+ cursor int64
+ interactionID string
+ hasMore bool
+ cancelStep *int64
+ // pendingErr 暂存不带详情的泛化失败步骤,以便继续读取紧随其后的详因错误步骤
+ pendingErr *RPCError
// searches 是已完成的 search_web 的查询与摘要,供下一轮补回对话历史
searches []string
// held 是扣下的正文:可能的代码块围栏开头,或尚未结束的调用候选代码块
@@ -36,7 +48,7 @@ type AssistantStreamDecoder struct {
lastStep int64
wroteText bool
finished bool
- // answered 表示最近解码的步骤是已完成、含正文且没有工具动作的模型步骤,即本轮回复结束
+ // answered 仅用于旧版 StreamCodeAssistantOfflineGeneration:表示最近解码的步骤是已完成、含正文且没有工具动作的模型步骤,即本轮回复结束
answered bool
// stopped 表示不再读取本任务后续步骤:函数调用之后模型继续输出正文、上游后续步骤失败,或模型调用了被禁止的工作区工具、交回的提问缺少调用块
stopped bool
@@ -44,16 +56,26 @@ type AssistantStreamDecoder struct {
failed bool
}
-// DecodeAssistantStream 解码 StreamCodeAssistantOfflineGeneration 响应并把事件交给 emit
-// 消息列表在回复完成前正常结束时经 Reopen 重新打开一次任务流继续读取
+// DecodeAssistantStream 解码 StreamRunAgentTask 或 StreamCodeAssistantOfflineGeneration 的响应并把事件交给 emit
+// 响应带 hasMore 或消息列表在回复完成前正常结束时经 Reopen 重连任务流继续读取
// 停止读取与以已有内容结束本轮的条件见 docs/build.md 的“任务流”一节
func DecodeAssistantStream(source io.Reader, decoder *AssistantStreamDecoder, emit func(Event) error) error {
err := decodeAssistantMessages(source, decoder, emit)
- if err == nil && !decoder.finished && !decoder.stopped && decoder.Reopen != nil {
- var reopened io.ReadCloser
- if reopened, err = decoder.Reopen(); err == nil {
- err = errors.Join(decodeAssistantMessages(reopened, decoder, emit), reopened.Close())
+ for reopened := 0; err == nil && !decoder.stopped && decoder.pendingErr == nil && decoder.Reopen != nil; reopened++ {
+ if !decoder.hasMore && (decoder.finished || reopened >= 1) {
+ break
+ }
+ if reopened >= 3 {
+ break
+ }
+ decoder.hasMore = false
+ decoder.answered = false
+ var next io.ReadCloser
+ next, err = decoder.Reopen()
+ if err != nil {
+ break
}
+ err = errors.Join(decodeAssistantMessages(next, decoder, emit), next.Close())
}
if err != nil {
return err
@@ -70,14 +92,23 @@ func DecodeAssistantStream(source io.Reader, decoder *AssistantStreamDecoder, em
return nil
}
+// streamMethod 返回当前解码器对应的上游流式 RPC 名称
+func (d *AssistantStreamDecoder) streamMethod() string {
+ if d.Legacy {
+ return assistantLegacyStreamMethod
+ }
+ return assistantStreamMethod
+}
+
// decodeAssistantMessages 读取一条任务流的消息列表与流尾状态
func decodeAssistantMessages(source io.Reader, decoder *AssistantStreamDecoder, emit func(Event) error) error {
+ method := decoder.streamMethod()
reader := &streamReadRecorder{source: source}
stream := json.NewDecoder(newSparseJSONReader(reader))
stream.UseNumber()
index := 0
fail := func(path string, detail string) error {
- return reader.failure(assistantStreamMethod, index, &ProtocolEvidenceError{Method: assistantStreamMethod, Path: path, Detail: detail})
+ return reader.failure(method, index, &ProtocolEvidenceError{Method: method, Path: path, Detail: detail})
}
if token, err := stream.Token(); err != nil || token != json.Delim('[') {
return fail("$", "根值不是数组")
@@ -112,36 +143,115 @@ func decodeAssistantMessages(source io.Reader, decoder *AssistantStreamDecoder,
if err := stream.Decode(&raw); err != nil {
return fail("$", err.Error())
}
- if err := trailerError(assistantStreamMethod, raw); err != nil {
+ if err := trailerError(method, raw); err != nil {
return err
}
}
+ _, _ = stream.Token()
+ if !decoder.Legacy {
+ _, _ = io.Copy(io.Discard, source)
+ }
}
- return reader.failure(assistantStreamMethod, index, nil)
+ return reader.failure(method, index, nil)
}
-// Decode 解码一条消息 [null, null, [步骤...], trajectory ID]:步骤 field 1 为对话轮、6 为错误(状态为 3 时不终止任务)、10 为工具动作、12 为序号、13 为状态(1 完成、2 进行中、4 失败)、16 为用量
+// notifyMeta 把当前已收到的 trajectory、游标、交互 ID 与取消步骤号通知调用方
+func (d *AssistantStreamDecoder) notifyMeta() {
+ if d.OnMeta != nil {
+ d.OnMeta(d.trajectory, d.cursor, d.interactionID, d.cancelStep)
+ }
+}
+
+// Decode 解码一条任务流消息:
+// agency 模式为 [[步骤...], trajectory ID, 游标字符串, hasMore, [交互 ID, 游标字符串]];
+// legacy 模式为 [null, null, [步骤...], trajectory ID]
func (d *AssistantStreamDecoder) Decode(raw json.RawMessage, path string) ([]Event, error) {
if d.emitted == nil {
d.emitted = make(map[int64][]string)
d.usage = make(map[int64]Usage)
d.searched = make(map[int64]bool)
}
+ method := d.streamMethod()
message, err := rawArray(raw, path, raw)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
+ }
+ stepsIndex := 0
+ if d.Legacy {
+ stepsIndex = 2
+ } else {
+ metaChanged := false
+ if trajRaw := rawAt(message, 1); !isJSONNull(trajRaw) {
+ traj, err := rawString(trajRaw, path+"[1]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if traj != "" && traj != d.trajectory {
+ d.trajectory = traj
+ metaChanged = true
+ }
+ }
+ if cursorRaw := rawAt(message, 2); !isJSONNull(cursorRaw) {
+ cursor, err := rawInt64(cursorRaw, path+"[2]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if cursor > d.cursor {
+ d.cursor = cursor
+ metaChanged = true
+ }
+ }
+ if moreRaw := rawAt(message, 3); !isJSONNull(moreRaw) {
+ more, err := rawBool(moreRaw, path+"[3]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if more {
+ d.hasMore = true
+ }
+ }
+ if pairRaw := rawAt(message, 4); !isJSONNull(pairRaw) {
+ pair, err := rawArray(pairRaw, path+"[4]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if idRaw := rawAt(pair, 0); !isJSONNull(idRaw) {
+ id, err := rawString(idRaw, path+"[4][0]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if id != "" && id != d.interactionID {
+ d.interactionID = id
+ metaChanged = true
+ }
+ }
+ if pairCursorRaw := rawAt(pair, 1); !isJSONNull(pairCursorRaw) {
+ pairCursor, err := rawInt64(pairCursorRaw, path+"[4][1]", raw)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ if pairCursor > d.cursor {
+ d.cursor = pairCursor
+ metaChanged = true
+ }
+ }
+ }
+ if metaChanged {
+ d.notifyMeta()
+ }
}
- stepsRaw := rawAt(message, 2)
+ stepsRaw := rawAt(message, stepsIndex)
if isJSONNull(stepsRaw) {
return nil, nil
}
- steps, err := rawArray(stepsRaw, path+"[2]", raw)
+ stepsPath := fmt.Sprintf("%s[%d]", path, stepsIndex)
+ steps, err := rawArray(stepsRaw, stepsPath, raw)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
var events []Event
for stepIndex, stepRaw := range steps {
- stepPath := fmt.Sprintf("%s[2][%d]", path, stepIndex)
+ stepPath := fmt.Sprintf("%s[%d]", stepsPath, stepIndex)
stepEvents, err := d.decodeStep(stepRaw, stepPath, raw)
if err != nil {
return nil, err
@@ -155,21 +265,29 @@ func (d *AssistantStreamDecoder) Decode(raw json.RawMessage, path string) ([]Eve
}
func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, evidence json.RawMessage) ([]Event, error) {
+ method := d.streamMethod()
d.answered = false
step, err := rawArray(raw, path, evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
- number, err := rawInt64(rawAt(step, 11), path+"[11]", evidence)
- if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ var number int64
+ hasNumber := false
+ if numberRaw := rawAt(step, 11); !isJSONNull(numberRaw) {
+ number, err = rawInt64(numberRaw, path+"[11]", evidence)
+ if err != nil {
+ return nil, withMethod(err, method)
+ }
+ hasNumber = true
+ } else if d.Legacy {
+ return nil, withMethod(&ProtocolEvidenceError{Method: method, Path: path + "[11]", Detail: "缺少步骤序号", Raw: cloneRaw(evidence)}, method)
}
status, err := rawInt64(rawAt(step, 12), path+"[12]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
if failure := rawAt(step, 5); !isJSONNull(failure) {
- failed, err := decodeAssistantFailure(failure, path+"[5]", evidence)
+ failed, hasDetail, err := decodeAssistantFailure(method, failure, path+"[5]", evidence)
if err != nil {
return nil, err
}
@@ -181,10 +299,19 @@ func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, ev
d.stopped = true
return nil, nil
}
- return nil, failed
+ if hasDetail || d.Legacy {
+ d.pendingErr = nil
+ return nil, failed
+ }
+ d.pendingErr = failed
+ return nil, nil
+ }
+ // StreamRunAgentTask 在本轮正常结束时以序号为 null、状态为 1 的空步骤携带最终游标;继续读完流尾 ]] 与 EOF,不提前断流
+ if !d.Legacy && !hasNumber && status == 1 && isJSONNull(rawAt(step, 0)) && isJSONNull(rawAt(step, 9)) {
+ return nil, nil
}
if usageRaw := rawAt(step, 15); !isJSONNull(usageRaw) && status == 1 {
- usage, err := decodeAssistantUsage(usageRaw, path+"[15]", evidence)
+ usage, err := decodeAssistantUsage(method, usageRaw, path+"[15]", evidence)
if err != nil {
return nil, err
}
@@ -196,7 +323,7 @@ func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, ev
if actionRaw := rawAt(step, 9); !isJSONNull(actionRaw) && status == 1 && !d.searched[number] {
action, err := rawArray(actionRaw, path+"[9]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
if err := d.decodeSearch(action, path+"[9]", evidence); err != nil {
return nil, err
@@ -213,25 +340,33 @@ func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, ev
if !isJSONNull(contentsRaw) {
contents, err := rawArray(contentsRaw, path+"[0]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
partOffset := 0
for contentIndex, contentRaw := range contents {
contentPath := fmt.Sprintf("%s[0][%d]", path, contentIndex)
content, err := rawArray(contentRaw, contentPath, evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
role, err := rawString(rawAt(content, 1), contentPath+"[1]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
+ }
+ if role == "user" {
+ if !d.Legacy && d.cancelStep == nil && hasNumber && number > 0 {
+ stepIndex := number - 1
+ d.cancelStep = &stepIndex
+ d.notifyMeta()
+ }
+ continue
}
if role != "model" {
continue
}
parts, err := rawArray(rawAt(content, 0), contentPath+"[0]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
for partIndex, partRaw := range parts {
partEvents, err := d.decodePart(number, partOffset+partIndex, partRaw, fmt.Sprintf("%s[0][%d]", contentPath, partIndex), evidence)
@@ -243,9 +378,11 @@ func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, ev
partOffset += len(parts)
if status == 1 {
d.finished = true
+ if d.Legacy && d.wroteText && !d.called && !d.malformed && !d.invalidTool && isJSONNull(rawAt(step, 9)) {
+ d.answered = true
+ }
}
}
- d.answered = status == 1 && isJSONNull(rawAt(step, 9)) && d.wroteText && d.lastStep == number
}
if invalidAction && len(d.Functions) > 0 && !d.called {
d.invalidTool = true
@@ -257,32 +394,37 @@ func (d *AssistantStreamDecoder) decodeStep(raw json.RawMessage, path string, ev
return events, nil
}
-// decodeAssistantFailure 解码错误步骤 field 6:field 1 为错误文字,field 2 为详情(1 消息、2 调试信息、3 内部错误详情、4 通用额度、5 每用户额度);带额度标记时为 HTTP 429 与协议错误码 8,否则为 HTTP 502
-func decodeAssistantFailure(raw json.RawMessage, path string, evidence json.RawMessage) (*RPCError, error) {
+// decodeAssistantFailure 解码错误步骤 field 6:field 1 为错误文字,field 2 为详情(1 消息、2 调试信息、3 内部错误详情、4 通用额度、5 每用户额度、6 错误原因码、7 键值元数据);
+// 账户验证门控(ACCOUNT_VERIFICATION_REQUIRED 或官网验证提示)映射为 HTTP 403、协议错误码 7,带额度标记时为 HTTP 429 与协议错误码 8,否则为 HTTP 502;第二个返回值表示是否带有详情
+func decodeAssistantFailure(method string, raw json.RawMessage, path string, evidence json.RawMessage) (*RPCError, bool, error) {
values, err := rawArray(raw, path, evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, method)
}
message, err := rawString(rawAt(values, 0), path+"[0]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, method)
+ }
+ failure := &RPCError{Method: method, StatusCode: http.StatusBadGateway, Message: "生成步骤失败: " + message}
+ denied := camoufoxnative.DenialForMessage(message) != nil
+ if denied {
+ failure.StatusCode, failure.Code, failure.Message = http.StatusForbidden, 7, message
}
- failure := &RPCError{Method: assistantStreamMethod, StatusCode: http.StatusBadGateway, Message: "生成步骤失败: " + message}
detailRaw := rawAt(values, 1)
if isJSONNull(detailRaw) {
- return failure, nil
+ return failure, false, nil
}
detail, err := rawArray(detailRaw, path+"[1]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, method)
}
for index := range 3 {
if text := rawAt(detail, index); !isJSONNull(text) {
value, err := rawString(text, fmt.Sprintf("%s[1][%d]", path, index), evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, method)
}
- if value != "" && value != message {
+ if value != "" && value != message && !denied {
failure.Message += ";" + value
}
}
@@ -291,7 +433,7 @@ func decodeAssistantFailure(raw json.RawMessage, path string, evidence json.RawM
if flag := rawAt(detail, index); !isJSONNull(flag) {
quota, err := rawBool(flag, fmt.Sprintf("%s[1][%d]", path, index), evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, method)
}
if quota {
failure.StatusCode, failure.Code = http.StatusTooManyRequests, 8
@@ -301,14 +443,49 @@ func decodeAssistantFailure(raw json.RawMessage, path string, evidence json.RawM
}
}
}
- return failure, nil
+ if reasonRaw := rawAt(detail, 5); !isJSONNull(reasonRaw) {
+ reason, err := rawString(reasonRaw, path+"[1][5]", evidence)
+ if err != nil {
+ return nil, false, withMethod(err, method)
+ }
+ if reason == "ACCOUNT_VERIFICATION_REQUIRED" {
+ failure.StatusCode, failure.Code = http.StatusForbidden, 7
+ if camoufoxnative.DenialForMessage(message) != nil {
+ failure.Message = message
+ } else if message != "" {
+ failure.Message = "Your account must be verified before it can continue using the Gemini API. " + message
+ } else {
+ failure.Message = "Your account must be verified before it can continue using the Gemini API."
+ }
+ }
+ }
+ if metaRaw := rawAt(detail, 6); !isJSONNull(metaRaw) {
+ if entries, err := rawArray(metaRaw, path+"[1][6]", evidence); err == nil {
+ for idx, entryRaw := range entries {
+ entry, err := rawArray(entryRaw, fmt.Sprintf("%s[1][6][%d]", path, idx), evidence)
+ if err != nil {
+ continue
+ }
+ k, kErr := rawString(rawAt(entry, 0), fmt.Sprintf("%s[1][6][%d][0]", path, idx), evidence)
+ v, vErr := rawString(rawAt(entry, 1), fmt.Sprintf("%s[1][6][%d][1]", path, idx), evidence)
+ if kErr == nil && vErr == nil && k != "" {
+ if failure.Metadata == nil {
+ failure.Metadata = map[string]string{}
+ }
+ failure.Metadata[k] = v
+ }
+ }
+ }
+ }
+ return failure, true, nil
}
// decodePart 返回模型 part 文本相对上一次快照新增的部分
func (d *AssistantStreamDecoder) decodePart(step int64, index int, raw json.RawMessage, path string, evidence json.RawMessage) ([]Event, error) {
+ method := d.streamMethod()
part, err := rawArray(raw, path, evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
textRaw := rawAt(part, 1)
if isJSONNull(textRaw) {
@@ -316,13 +493,13 @@ func (d *AssistantStreamDecoder) decodePart(step int64, index int, raw json.RawM
}
text, err := rawString(textRaw, path+"[1]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
thought := false
if thoughtRaw := rawAt(part, 12); !isJSONNull(thoughtRaw) {
thought, err = rawBool(thoughtRaw, path+"[12]", evidence)
if err != nil {
- return nil, withMethod(err, assistantStreamMethod)
+ return nil, withMethod(err, method)
}
}
emitted := d.emitted[step]
@@ -331,7 +508,7 @@ func (d *AssistantStreamDecoder) decodePart(step int64, index int, raw json.RawM
}
previous := emitted[index]
if !strings.HasPrefix(text, previous) {
- return nil, &ProtocolEvidenceError{Method: assistantStreamMethod, Path: path + "[1]", Detail: "步骤正文不是上一次快照的延续", Raw: cloneRaw(raw)}
+ return nil, &ProtocolEvidenceError{Method: method, Path: path + "[1]", Detail: "步骤正文不是上一次快照的延续", Raw: cloneRaw(raw)}
}
emitted[index] = text
d.emitted[step] = emitted
@@ -533,25 +710,25 @@ func (d *AssistantStreamDecoder) decodeQuestion(action []json.RawMessage, path s
}
tool, err := rawArray(toolRaw, path+"[21]", evidence)
if err != nil {
- return nil, false, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, d.streamMethod())
}
pairs, err := rawArray(rawAt(tool, 3), path+"[21][3]", evidence)
if err != nil {
- return nil, false, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, d.streamMethod())
}
arguments := map[string]string{}
for index, pairRaw := range pairs {
pairPath := fmt.Sprintf("%s[21][3][%d]", path, index)
pair, err := rawArray(pairRaw, pairPath, evidence)
if err != nil {
- return nil, false, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, d.streamMethod())
}
name, err := rawString(rawAt(pair, 0), pairPath+"[0]", evidence)
if err != nil {
- return nil, false, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, d.streamMethod())
}
if arguments[name], err = rawString(rawAt(pair, 1), pairPath+"[1]", evidence); err != nil {
- return nil, false, withMethod(err, assistantStreamMethod)
+ return nil, false, withMethod(err, d.streamMethod())
}
}
if arguments["tag"] != assistantQuestionTool {
@@ -562,7 +739,7 @@ func (d *AssistantStreamDecoder) decodeQuestion(action []json.RawMessage, path s
Options []string `json:"options"`
}
if err := json.Unmarshal([]byte(arguments["questions"]), &questions); err != nil {
- return nil, true, &ProtocolEvidenceError{Method: assistantStreamMethod, Path: path + "[21][3]", Detail: "ask_question 的 questions 不是问题列表: " + err.Error(), Raw: cloneRaw(evidence)}
+ return nil, true, &ProtocolEvidenceError{Method: d.streamMethod(), Path: path + "[21][3]", Detail: "ask_question 的 questions 不是问题列表: " + err.Error(), Raw: cloneRaw(evidence)}
}
var text strings.Builder
for _, question := range questions {
@@ -592,11 +769,11 @@ func (d *AssistantStreamDecoder) decodeSearch(action []json.RawMessage, path str
}
search, err := rawArray(searchRaw, path+"[18]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
query, err := rawString(rawAt(search, 0), path+"[18][0]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
if d.grounding == nil {
d.grounding = &GroundingMetadata{}
@@ -605,28 +782,28 @@ func (d *AssistantStreamDecoder) decodeSearch(action []json.RawMessage, path str
if summaryRaw := rawAt(search, 2); !isJSONNull(summaryRaw) {
summary, err := rawString(summaryRaw, path+"[18][2]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
d.searches = append(d.searches, fmt.Sprintf(assistantSearchTranscript, query, summary))
}
if resultsRaw := rawAt(search, 3); !isJSONNull(resultsRaw) {
results, err := rawArray(resultsRaw, path+"[18][3]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
for index, resultRaw := range results {
resultPath := fmt.Sprintf("%s[18][3][%d]", path, index)
result, err := rawArray(resultRaw, resultPath, evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
title, err := rawString(rawAt(result, 0), resultPath+"[0]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
uri, err := rawString(rawAt(result, 1), resultPath+"[1]", evidence)
if err != nil {
- return withMethod(err, assistantStreamMethod)
+ return withMethod(err, d.streamMethod())
}
d.grounding.Chunks = append(d.grounding.Chunks, GroundingChunk{Source: "web", URI: uri, Title: title})
}
@@ -655,8 +832,11 @@ func (d *AssistantStreamDecoder) recorded() []Event {
// End 在本轮回复结束、函数调用之后模型继续输出正文或流结束时返回扣下的正文或函数调用、搜索来源、各步骤用量之和与完成事件
func (d *AssistantStreamDecoder) End() ([]Event, error) {
+ if d.pendingErr != nil {
+ return nil, d.pendingErr
+ }
if !d.finished && !d.stopped && !d.called && !d.wroteText {
- return nil, &ProtocolEvidenceError{Method: assistantStreamMethod, Path: "$", Detail: "流结束前没有完成的模型回复"}
+ return nil, &ProtocolEvidenceError{Method: d.streamMethod(), Path: "$", Detail: "流结束前没有完成的模型回复"}
}
var events []Event
switch {
@@ -674,17 +854,17 @@ func (d *AssistantStreamDecoder) End() ([]Event, error) {
}
// decodeAssistantUsage 解码步骤用量 [未命中缓存的输入, 输出, 缓存命中]
-func decodeAssistantUsage(raw json.RawMessage, path string, evidence json.RawMessage) (Usage, error) {
+func decodeAssistantUsage(method string, raw json.RawMessage, path string, evidence json.RawMessage) (Usage, error) {
values, err := rawArray(raw, path, evidence)
if err != nil {
- return Usage{}, withMethod(err, assistantStreamMethod)
+ return Usage{}, withMethod(err, method)
}
numbers := make([]int64, 3)
for index := range numbers {
if value := rawAt(values, index); !isJSONNull(value) {
numbers[index], err = rawInt64(value, fmt.Sprintf("%s[%d]", path, index), evidence)
if err != nil {
- return Usage{}, withMethod(err, assistantStreamMethod)
+ return Usage{}, withMethod(err, method)
}
}
}
diff --git a/internal/aistudio/benefit.go b/internal/aistudio/benefit.go
index 48eb83aa..26dece4f 100644
--- a/internal/aistudio/benefit.go
+++ b/internal/aistudio/benefit.go
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net/http"
+ "slices"
"strings"
)
@@ -48,7 +49,7 @@ func (tier BenefitTier) String() string {
}
}
-// HeaderValue 返回官网 RPC 使用的权益请求头值
+// HeaderValue 返回账户权益在官网的标识:Plus 为 TIER0,Pro 为 TIER1,Ultra 为 TIER2,其余为空
func (tier BenefitTier) HeaderValue() string {
switch tier {
case BenefitTierPro:
@@ -62,6 +63,14 @@ func (tier BenefitTier) HeaderValue() string {
}
}
+// RequestHeaderValue 返回 RPC 请求的 X-AIStudio-G1-Tier 值,官网只对 Pro 与 Ultra 账户发出该请求头
+func (tier BenefitTier) RequestHeaderValue() string {
+ if tier == BenefitTierPlus {
+ return ""
+ }
+ return tier.HeaderValue()
+}
+
// setBenefitTier 记录账户的权益等级
func (c *Client) setBenefitTier(accountID string, tier BenefitTier) {
c.tierMu.Lock()
@@ -109,7 +118,7 @@ func (c *Client) applyBenefitTier(method string, accountID string, header http.H
c.tierMu.RLock()
tier := c.tiers[strings.TrimSpace(accountID)]
c.tierMu.RUnlock()
- if value := tier.HeaderValue(); value != "" {
+ if value := tier.RequestHeaderValue(); value != "" {
header.Set("X-AIStudio-G1-Tier", value)
}
}
@@ -165,6 +174,25 @@ func NoMoreEligibleAccounts(err error) bool {
return errors.Is(err, ErrNoEligibleAccount) || errors.As(err, &access)
}
+const (
+ // modelUnavailablePaidKey 表示模型只对付费 API key 开放,任何账户的订阅权益都调用不了
+ modelUnavailablePaidKey = "paid_api_key"
+ // modelUnavailableNoMethods 表示上游没有为模型提供任何方法
+ modelUnavailableNoMethods = "no_methods"
+)
+
+// modelUnavailableReason 返回本服务调用不了模型的原因,调用得了时为空
+// access_modes 非空且取值都是 1 的模型只能用付费 API key 调用,官方 API key 不作为上游凭据;含其他取值的模型不判断
+func modelUnavailableReason(model Model) string {
+ switch {
+ case len(model.AccessModes) > 0 && !slices.ContainsFunc(model.AccessModes, func(mode int64) bool { return mode != 1 }):
+ return modelUnavailablePaidKey
+ case len(model.Methods) == 0:
+ return modelUnavailableNoMethods
+ }
+ return ""
+}
+
func modelAllowedByTier(model Model, tier BenefitTier) bool {
if len(model.AccessModes) == 0 {
return true
diff --git a/internal/aistudio/bidi.go b/internal/aistudio/bidi.go
index e6b9059a..51d1dfab 100644
--- a/internal/aistudio/bidi.go
+++ b/internal/aistudio/bidi.go
@@ -6,6 +6,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
+ "net/http"
"strings"
)
@@ -54,7 +55,21 @@ var bidiMediaResolutions = map[string]int64{"low": 1, "medium": 2, "high": 3}
// bidiThinkingLevels 是 Live setup 思考档位的取值与上游编号
var bidiThinkingLevels = map[string]int64{"low": 1, "medium": 2, "high": 3, "minimal": 4}
+// bidiSpeechConfig 编码 SpeechConfig:voice_ 与 voicekey_ 开头的自定义声音写入 VoiceConfig field 5,其余为预置音色,language 非空时写入 field 2
+func bidiSpeechConfig(voice, language string) []any {
+ voice = strings.TrimPrefix(voice, "voices/")
+ config := []any{[]any{[]any{voice}}}
+ if strings.HasPrefix(voice, "voice_") || strings.HasPrefix(voice, "voicekey_") {
+ config = []any{[]any{nil, nil, nil, nil, voice}}
+ }
+ if language != "" {
+ config = append(config, language)
+ }
+ return config
+}
+
// BidiRequest 定义一条双向实时会话
+// 约束:TurnCoverage 取 0(不发送)、1(只含活动)、2(含全部输入)或 3(含音频活动与全部视频)
type BidiRequest struct {
Model string
Mode BidiMode
@@ -69,6 +84,10 @@ type BidiRequest struct {
ThinkingLevel string
ContextWindow *BidiContextWindow
GoogleSearch bool
+ ProactiveAudio bool
+ ProactiveVideo bool
+ AffectiveDialog bool
+ TurnCoverage int64
AccountID string
AllowedAccountIDs []string
SessionToken string
@@ -78,6 +97,8 @@ type BidiRequest struct {
ObserveModelAccessChange func()
ObserveAccountFailure func(string, error)
generationDefaults GenerationDefaults
+ defaultVoice string
+ capabilities map[string]bool
variant bidiVariant
method string
}
@@ -118,8 +139,29 @@ func validateLiveVariant(request BidiRequest) error {
if request.variant != bidiVariantConversation && (len(request.Tools) > 0 || request.GoogleSearch) {
return fmt.Errorf("%w: 模型 %s 不支持 tools", ErrInvalidArgument, request.Model)
}
- if request.variant != bidiVariantConversation && (request.Voice != "" || request.MediaResolution != "" || request.ThinkingLevel != "" || request.ContextWindow != nil) {
- return fmt.Errorf("%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression", ErrInvalidArgument, request.Model)
+ if request.variant != bidiVariantConversation && (request.MediaResolution != "" || request.ThinkingLevel != "" || request.ContextWindow != nil ||
+ request.ProactiveAudio || request.ProactiveVideo || request.AffectiveDialog || request.TurnCoverage != 0) {
+ return fmt.Errorf("%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage", ErrInvalidArgument, request.Model)
+ }
+ if request.variant == bidiVariantTranscription && request.Voice != "" {
+ return fmt.Errorf("%w: 模型 %s 不支持 voice", ErrInvalidArgument, request.Model)
+ }
+ if request.variant == bidiVariantConversation && request.capabilities != nil {
+ // 官网只在目录带有对应能力码的模型上提供这些设置:39 情感对话、40 主动音频、72 主动视频,46 与 56 都没有时才有轮次覆盖范围
+ for _, setting := range []struct {
+ enabled bool
+ name string
+ supported bool
+ }{
+ {request.AffectiveDialog, "enable_affective_dialog", request.capabilities["capability_code_39"]},
+ {request.ProactiveAudio, "proactive_audio", request.capabilities["capability_code_40"]},
+ {request.ProactiveVideo, "proactive_video", request.capabilities["capability_code_72"]},
+ {request.TurnCoverage != 0, "turn_coverage", !request.capabilities["capability_code_46"] && !request.capabilities["capability_code_56"]},
+ } {
+ if setting.enabled && !setting.supported {
+ return fmt.Errorf("%w: 模型 %s 不支持 %s", ErrInvalidArgument, request.Model, setting.name)
+ }
+ }
}
if request.variant == bidiVariantTranscription && request.SystemInstruction != "" {
return fmt.Errorf("%w: 模型 %s 不支持 system_instruction", ErrInvalidArgument, request.Model)
@@ -223,7 +265,7 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
}
switch request.variant {
case bidiVariantTranslation:
- // 官网实时翻译 setup:无声音、思考与 MediaResolution,field 31 为 TranslationConfig
+ // 官网实时翻译 setup:无思考与 MediaResolution,选了音色时 field 16 为带目标语言的 SpeechConfig,field 31 为 TranslationConfig
conversation = false
configuration = make([]any, 31)
configuration[13] = int64(0)
@@ -232,7 +274,12 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
if request.Translation.EchoTargetLanguage {
echo = 1
}
- configuration[30] = []any{echo, strings.TrimSpace(request.Translation.TargetLanguageCode)}
+ target := strings.TrimSpace(request.Translation.TargetLanguageCode)
+ if request.Voice != "" {
+ // 官网翻译模型选了音色时,SpeechConfig 同时写入目标语言
+ configuration[15] = bidiSpeechConfig(request.Voice, target)
+ }
+ configuration[30] = []any{echo, target}
case bidiVariantTranscription:
// 官网实时转录 setup:只输出 TEXT,setup field 10 为输入转录参数
conversation = false
@@ -240,7 +287,9 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
configuration[14] = []any{int64(1)}
default:
configuration[14] = []any{int64(3)}
- configuration[15] = []any{[]any{[]any{cmp.Or(request.Voice, "Zephyr")}}}
+ if voice := cmp.Or(request.Voice, request.defaultVoice); voice != "" {
+ configuration[15] = bidiSpeechConfig(voice, "")
+ }
if request.ThinkingLevel != "" {
configuration[16] = []any{int64(1), nil, nil, bidiThinkingLevels[request.ThinkingLevel]}
} else if request.generationDefaults.ThinkingLevel {
@@ -256,6 +305,10 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
if conversation {
configuration[17] = bidiMediaResolutions[cmp.Or(request.MediaResolution, "medium")]
}
+ if request.AffectiveDialog {
+ // GenerationConfig field 20 为 enable_affective_dialog
+ configuration = append(configuration, nil, int64(1))
+ }
wireModel := wireModelName(model)
setup[0] = wireModel
setup[1] = configuration
@@ -265,25 +318,11 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
setup[2] = []any{[]any{[]any{nil, request.SystemInstruction}}}
bindingParts = append(bindingParts, request.SystemInstruction)
}
- tools := []any{}
- if len(request.Tools) > 0 {
- declarations := make([]any, 0, len(request.Tools))
- for _, declaration := range request.Tools {
- encoded, err := encodeFunctionDeclaration(declaration)
- if err != nil {
- return nil, 0, "", fmt.Errorf("编码 bidi function declaration: %w", err)
- }
- declarations = append(declarations, encoded)
- bindingParts = append(bindingParts, declaration.Name+" "+declaration.Description)
- }
- tool := make([]any, 2)
- tool[1] = declarations
- tools = append(tools, tool)
- }
- if request.GoogleSearch {
- // Tool field 4 为 GoogleSearch
- tools = append(tools, []any{nil, nil, nil, []any{}})
+ tools, toolParts, err := encodeBidiTools(request.Tools, request.GoogleSearch)
+ if err != nil {
+ return nil, 0, "", err
}
+ bindingParts = append(bindingParts, toolParts...)
if len(tools) > 0 {
setup[3] = tools
}
@@ -294,8 +333,9 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
}
if conversation {
window := BidiContextWindow{TriggerTokens: 104857, TargetTokens: 52428}
- if request.ContextWindow != nil {
- window = *request.ContextWindow
+ if custom := request.ContextWindow; custom != nil {
+ window.TriggerTokens = cmp.Or(custom.TriggerTokens, window.TriggerTokens)
+ window.TargetTokens = cmp.Or(custom.TargetTokens, window.TargetTokens)
}
setup[7] = []any{window.TriggerTokens, []any{window.TargetTokens}}
}
@@ -318,6 +358,21 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
setup[9] = transcription
}
setup[10] = []any{}
+ if request.ProactiveAudio || request.ProactiveVideo {
+ // BidiGenerateContentSetup field 12 为 ProactivityConfig,field 1 为 Proactive audio,field 2 为 Proactive video
+ proactivity := []any{nil, int64(1)}
+ if request.ProactiveAudio {
+ proactivity[0] = int64(1)
+ }
+ if !request.ProactiveVideo {
+ proactivity = proactivity[:1]
+ }
+ setup[11] = proactivity
+ }
+ if request.TurnCoverage != 0 {
+ // BidiGenerateContentSetup field 6 为 RealtimeInputConfig,field 4 为 turn coverage
+ setup[5] = []any{nil, nil, nil, request.TurnCoverage}
+ }
if timezone := strings.TrimSpace(runtime.Timezone); timezone != "" {
setup[15] = []any{nil, nil, nil, nil, []any{timezone}}
}
@@ -330,6 +385,31 @@ func EncodeBidiSetupRequest(request BidiRequest, runtime RequestContext) ([]byte
return body, proofAt, strings.Join(bindingParts, " "), nil
}
+// encodeBidiTools 编码 Live 的工具列表,返回工具数组与 WAA 绑定串中各工具的文本
+func encodeBidiTools(declarations []FunctionDeclaration, googleSearch bool) ([]any, []string, error) {
+ tools := []any{}
+ var parts []string
+ if len(declarations) > 0 {
+ encodedDeclarations := make([]any, 0, len(declarations))
+ for _, declaration := range declarations {
+ encoded, err := encodeFunctionDeclaration(declaration)
+ if err != nil {
+ return nil, nil, fmt.Errorf("编码 bidi function declaration: %w", err)
+ }
+ encodedDeclarations = append(encodedDeclarations, encoded)
+ parts = append(parts, declaration.Name+" "+declaration.Description)
+ }
+ tool := make([]any, 2)
+ tool[1] = encodedDeclarations
+ tools = append(tools, tool)
+ }
+ if googleSearch {
+ // Tool field 4 为 GoogleSearch
+ tools = append(tools, []any{nil, nil, nil, []any{}})
+ }
+ return tools, parts, nil
+}
+
// validateBidiText 校验实时文本输入非空
func validateBidiText(text string) error {
if strings.TrimSpace(text) == "" {
@@ -434,6 +514,89 @@ func EncodeBidiToolResponseRequest(results []FunctionResult) ([]byte, int, strin
return body, proofAt, results[0].ID, nil
}
+// BidiTurn 是 clientContent 的一个对话轮,Texts 为其文本片段
+type BidiTurn struct {
+ Role string
+ Texts []string
+}
+
+// BidiContextUpdate 是会话进行中对系统指令与工具的更新
+// 约束:SystemInstruction 为 nil 时系统指令不变;UpdateTools 为 true 时 Tools 与 GoogleSearch 整体替换工具,两者都空即清空工具
+type BidiContextUpdate struct {
+ SystemInstruction *string
+ UpdateTools bool
+ Tools []FunctionDeclaration
+ GoogleSearch bool
+}
+
+// EncodeBidiClientContentRequest 编码官网客户端消息的 clientContent 帧,field 1 为 turns,field 2 为 turn_complete
+func EncodeBidiClientContentRequest(turns []BidiTurn, turnComplete bool) ([]byte, int, string, error) {
+ if len(turns) == 0 && !turnComplete {
+ return nil, 0, "", fmt.Errorf("%w: bidi client_content 不能为空", ErrInvalidArgument)
+ }
+ contents := make([]any, 0, len(turns))
+ var texts []string
+ for _, turn := range turns {
+ parts := make([]any, 0, len(turn.Texts))
+ for _, text := range turn.Texts {
+ parts = append(parts, []any{nil, text})
+ texts = append(texts, text)
+ }
+ content := []any{parts}
+ if turn.Role != "" {
+ content = append(content, turn.Role)
+ }
+ contents = append(contents, content)
+ }
+ clientContent := []any{contents}
+ if turnComplete {
+ clientContent = append(clientContent, int64(1))
+ }
+ wire := make([]any, 6)
+ wire[1] = clientContent
+ body, proofAt, err := marshalWAAArray(wire, bidiProofField)
+ if err != nil {
+ return nil, 0, "", fmt.Errorf("编码 bidi client_content: %w", err)
+ }
+ return body, proofAt, strings.Join(texts, " "), nil
+}
+
+// EncodeBidiContextUpdateRequest 编码官网客户端消息的 contextUpdate 帧,field 1 为工具列表的包装,field 3 为系统指令
+func EncodeBidiContextUpdateRequest(update BidiContextUpdate) ([]byte, int, string, error) {
+ if update.SystemInstruction == nil && !update.UpdateTools {
+ return nil, 0, "", fmt.Errorf("%w: bidi context_update 不能为空", ErrInvalidArgument)
+ }
+ message := make([]any, 3)
+ var bindingParts []string
+ if update.SystemInstruction != nil {
+ text := clientSystemText(*update.SystemInstruction)
+ message[2] = []any{[]any{[]any{nil, text}}}
+ if text != "" {
+ bindingParts = append(bindingParts, text)
+ }
+ }
+ if update.UpdateTools {
+ tools, toolParts, err := encodeBidiTools(update.Tools, update.GoogleSearch)
+ if err != nil {
+ return nil, 0, "", err
+ }
+ // 工具包装带有存在位:空包装表示清空,缺省表示不更新
+ wrapper := []any{}
+ if len(tools) > 0 {
+ wrapper = []any{tools}
+ }
+ message[0] = wrapper
+ bindingParts = append(bindingParts, toolParts...)
+ }
+ wire := make([]any, 9)
+ wire[8] = message
+ body, proofAt, err := marshalWAAArray(wire, bidiProofField)
+ if err != nil {
+ return nil, 0, "", fmt.Errorf("编码 bidi context_update: %w", err)
+ }
+ return body, proofAt, strings.Join(bindingParts, " "), nil
+}
+
// ParseBidiServerPayload 解码一条 WebChannel 业务 payload
func ParseBidiServerPayload(raw json.RawMessage) ([]BidiEvent, error) {
return parseWebChannelPayload(raw, func(message []json.RawMessage, messageRaw json.RawMessage, _ string) ([]BidiEvent, error) {
@@ -481,6 +644,14 @@ func parseWebChannelPayload(raw json.RawMessage, decode func(message []json.RawM
return events, nil
}
+// bidiStatusHTTP 是 WebChannel 状态帧中 google.rpc.Code 错误码对应的 HTTP 状态
+var bidiStatusHTTP = map[int64]int{
+ 2: http.StatusInternalServerError, 3: http.StatusBadRequest, 4: http.StatusGatewayTimeout, 5: http.StatusNotFound,
+ 6: http.StatusConflict, 7: http.StatusForbidden, 8: http.StatusTooManyRequests, 9: http.StatusBadRequest,
+ 10: http.StatusConflict, 11: http.StatusBadRequest, 12: http.StatusNotImplemented, 13: http.StatusInternalServerError,
+ 14: http.StatusServiceUnavailable, 15: http.StatusInternalServerError, 16: http.StatusUnauthorized,
+}
+
func parseBidiStatusPayload(raw json.RawMessage) (BidiEvent, bool, error) {
var root map[string]json.RawMessage
if err := json.Unmarshal(raw, &root); err != nil {
@@ -528,21 +699,8 @@ func parseBidiStatusPayload(raw json.RawMessage) (BidiEvent, bool, error) {
if err != nil {
return BidiEvent{}, true, withBidiMethod(err)
}
- statusCode := 0
- switch code {
- case 3:
- statusCode = 400
- case 5:
- statusCode = 404
- case 7:
- statusCode = 403
- case 8:
- statusCode = 429
- case 13:
- statusCode = 500
- case 16:
- statusCode = 401
- default:
+ statusCode, known := bidiStatusHTTP[code]
+ if !known {
return BidiEvent{}, true, &ProtocolEvidenceError{
Method: "BidiGenerateContent", Path: "$.__sm__.status[0][0][0]",
Detail: fmt.Sprintf("未识别的状态码 %d", code), Raw: cloneRaw(raw),
diff --git a/internal/aistudio/build.go b/internal/aistudio/build.go
index 8fafd869..5d560fe8 100644
--- a/internal/aistudio/build.go
+++ b/internal/aistudio/build.go
@@ -1108,7 +1108,7 @@ func (l *AccountLease) buildModel(modelID string) (Model, bool) {
defer l.pool.mu.Unlock()
for _, model := range l.account.buildModels {
if model.ID == modelID {
- return cloneModels([]Model{model})[0], true
+ return cloneModel(model), true
}
}
return Model{}, false
diff --git a/internal/aistudio/build_bidi.go b/internal/aistudio/build_bidi.go
index 50f63e1c..7e48f3fa 100644
--- a/internal/aistudio/build_bidi.go
+++ b/internal/aistudio/build_bidi.go
@@ -163,12 +163,15 @@ func (s *BidiSession) webChannelURL() string {
// bidiProofField 是 Playground 实时客户端帧中 WAA proof 的字段号
const bidiProofField = 6
-// liveFrame 按会话通道编码 Live 客户端帧:Playground 会话用 playground,Build Live 会话用 build,实时音乐会话返回参数错误
+// liveFrame 按会话通道编码 Live 客户端帧:Playground 会话用 playground,Build Live 会话用 build(为空表示 Build Live 不支持该帧),实时音乐会话返回参数错误
func (s *BidiSession) liveFrame(playground, build func() ([]byte, int, string, error)) ([]byte, int, string, error) {
switch s.buildPath {
case "":
return playground()
case buildLivePath:
+ if build == nil {
+ return nil, 0, "", fmt.Errorf("%w: Build 通道的 Live 会话不支持 client_content 与 context_update", ErrInvalidArgument)
+ }
return build()
default:
return nil, 0, "", fmt.Errorf("%w: 实时音乐会话只接受 music_prompts、music_config 与 playback", ErrInvalidArgument)
diff --git a/internal/aistudio/camoufox_uploader.go b/internal/aistudio/camoufox_uploader.go
new file mode 100644
index 00000000..78e77951
--- /dev/null
+++ b/internal/aistudio/camoufox_uploader.go
@@ -0,0 +1,28 @@
+package aistudio
+
+import (
+ "context"
+ "time"
+)
+
+var _ pageUploader = camoufoxRuntime{}
+
+// driveDenied 判断 Camoufox 页面冷启动时申请 Drive access token 是否返回 401 未授权
+func (runtime camoufoxRuntime) driveDenied(context.Context) bool {
+ _, _, denied := runtime.Worker.DriveAccessToken()
+ return denied
+}
+
+// beforeUpload 返回 Camoufox 页面冷启动时取得、仍在有效期内的 Drive access token,避免附件上传重复发 GenerateAccessToken
+func (runtime camoufoxRuntime) beforeUpload(context.Context, bool) string {
+ token, at, _ := runtime.Worker.DriveAccessToken()
+ if time.Since(at) >= pageTokenLifetime {
+ return ""
+ }
+ return token
+}
+
+func (runtime camoufoxRuntime) inlined(context.Context, bool, []inlineFile, func(context.Context, []byte) ([]byte, error)) {
+}
+
+func (runtime camoufoxRuntime) uploaded(context.Context, []FileRef, pageDrive) {}
diff --git a/internal/aistudio/channel.go b/internal/aistudio/channel.go
index 017049a7..d6083501 100644
--- a/internal/aistudio/channel.go
+++ b/internal/aistudio/channel.go
@@ -152,7 +152,7 @@ func (p *AccountPool) ScopedSelection(ctx context.Context, selection AccountSele
key, _ := ctx.Value(apiKeyContextKey{}).(string)
p.mu.Lock()
keyScope, keyBound := p.apiKeyAccounts[key]
- modelScope, modelBound := p.modelAccounts[strings.TrimPrefix(strings.TrimSpace(selection.ModelID), "models/")]
+ modelScope, modelBound := p.modelScopeLocked(selection.ModelID)
p.mu.Unlock()
if keyBound {
selection.AllowedAccountIDs = narrowedAccounts(selection.AllowedAccountIDs, keyScope)
@@ -163,6 +163,12 @@ func (p *AccountPool) ScopedSelection(ctx context.Context, selection AccountSele
return selection
}
+// modelScopeLocked 返回模型绑定的账户 ID,没有绑定时 bound 为 false,调用方持有 p.mu
+func (p *AccountPool) modelScopeLocked(modelID string) (scope []string, bound bool) {
+ scope, bound = p.modelAccounts[strings.TrimPrefix(strings.TrimSpace(modelID), "models/")]
+ return scope, bound
+}
+
// narrowedAccounts 返回 allowed 中属于 scope 的账户,allowed 为 nil 时返回 scope
func narrowedAccounts(allowed []string, scope []string) []string {
if allowed == nil {
@@ -322,7 +328,12 @@ func (p *AccountPool) channelSupportsLocked(account *Account, channel Channel, s
// accountSupportsAnyChannelLocked 判断账户至少有一个通道支持选择
func (p *AccountPool) accountSupportsAnyChannelLocked(account *Account, selection AccountSelection) bool {
- for _, channel := range p.selectionChannelsLocked(selection) {
+ return p.accountSupportsChannelsLocked(account, p.selectionChannelsLocked(selection), selection)
+}
+
+// accountSupportsChannelsLocked 判断账户在 channels 中至少有一个通道支持选择
+func (p *AccountPool) accountSupportsChannelsLocked(account *Account, channels []Channel, selection AccountSelection) bool {
+ for _, channel := range channels {
if p.channelSupportsLocked(account, channel, selection) {
return true
}
@@ -506,7 +517,7 @@ func (p *AccountPool) buildOnlyModelsLocked() []Model {
if _, exists := seen[model.ID]; exists || p.hasPlaygroundModelLocked(model.ID) {
continue
}
- listed := cloneModels([]Model{model})[0]
+ listed := cloneModel(model)
if !hasMethod(model, "generateContent") {
listed.Methods = buildPublicMethods(model)
} else if !p.buildSupportsModelLocked(account, model.ID, false) {
@@ -587,14 +598,104 @@ func (p *AccountPool) hasBuildModelLocked(modelID string, method string) bool {
return false
}
-// modelChannelsLocked 返回至少一个启用账户可以调用模型的通道,anyTier 为 true 时不检查账户权益
-func (p *AccountPool) modelChannelsLocked(model Model, anyTier bool) []string {
- selection := AccountSelection{ModelID: model.ID, anyTier: anyTier}
- if hasMethod(model, "generateContent") {
+// modelSelection 返回目录按模型方法发起的选择:有 generateContent 的按生成,其余按 Build 代理方法,anyTier 为 true 时不检查账户权益
+func modelSelection(modelID string, methods []string, anyTier bool) AccountSelection {
+ selection := AccountSelection{ModelID: modelID, anyTier: anyTier}
+ if slices.Contains(methods, "generateContent") {
selection.Method = "generateContent"
- } else if index := slices.IndexFunc(buildMethods, func(method string) bool { return hasMethod(model, method) }); index >= 0 {
+ } else if index := slices.IndexFunc(buildMethods, func(method string) bool { return slices.Contains(methods, method) }); index >= 0 {
selection.Method = buildMethods[index]
}
+ return selection
+}
+
+// preferredSelectionMethod 返回 current 与 methods 中按 modelSelection 优先级更高的路由方法
+func preferredSelectionMethod(current string, methods []string) string {
+ if current == "generateContent" || slices.Contains(methods, "generateContent") {
+ return "generateContent"
+ }
+ for _, method := range buildMethods {
+ if current == method || slices.Contains(methods, method) {
+ return method
+ }
+ }
+ return current
+}
+
+// callableModelsLocked 返回 targets 中各账户按选号的同一判定可以调用的模型 ID,按 ID 排序,不看账户的启用、状态与冷却
+// 与选号共用模型绑定的账户、selectionChannelsLocked 与 channelSupportsLocked,启用 Build 通道时同步纳入账户的 Build 目录
+func (p *AccountPool) callableModelsLocked(targets []*Account) map[string][]string {
+ buildEnabled := p.channelEnabledLocked(ChannelBuild)
+ methodByID := make(map[string]string)
+ for _, account := range p.accounts {
+ for _, model := range account.Models {
+ methodByID[model.ID] = preferredSelectionMethod(methodByID[model.ID], model.Methods)
+ }
+ if buildEnabled {
+ for _, model := range account.buildModels {
+ methodByID[model.ID] = preferredSelectionMethod(methodByID[model.ID], model.Methods)
+ }
+ }
+ }
+ type route struct {
+ selection AccountSelection
+ channels []Channel
+ }
+ routes := make(map[string]route, len(methodByID))
+ routeFor := func(id string) route {
+ if cached, ok := routes[id]; ok {
+ return cached
+ }
+ selection := AccountSelection{ModelID: id, Method: methodByID[id]}
+ resolved := route{selection: selection, channels: p.selectionChannelsLocked(selection)}
+ routes[id] = resolved
+ return resolved
+ }
+ callable := make(map[string][]string, len(targets))
+ for _, account := range targets {
+ ids := []string{}
+ var added map[string]struct{}
+ if buildEnabled && len(account.buildModels) > 0 {
+ added = make(map[string]struct{}, len(account.Models)+len(account.buildModels))
+ }
+ for index := range account.Models {
+ model := &account.Models[index]
+ if scope, bound := p.modelScopeLocked(model.ID); modelUnavailableReason(*model) != "" || bound && !slices.Contains(scope, account.ID) {
+ continue
+ }
+ resolved := routeFor(model.ID)
+ resolved.selection.accountModel = model
+ if p.accountSupportsChannelsLocked(account, resolved.channels, resolved.selection) {
+ ids = append(ids, model.ID)
+ if added != nil {
+ added[model.ID] = struct{}{}
+ }
+ }
+ }
+ if added != nil {
+ for _, model := range account.buildModels {
+ if _, ok := added[model.ID]; ok || modelUnavailableReason(model) != "" {
+ continue
+ }
+ if scope, bound := p.modelScopeLocked(model.ID); bound && !slices.Contains(scope, account.ID) {
+ continue
+ }
+ resolved := routeFor(model.ID)
+ if slices.Contains(resolved.channels, ChannelBuild) && p.channelSupportsLocked(account, ChannelBuild, resolved.selection) {
+ ids = append(ids, model.ID)
+ added[model.ID] = struct{}{}
+ }
+ }
+ }
+ slices.Sort(ids)
+ callable[account.ID] = ids
+ }
+ return callable
+}
+
+// modelChannelsLocked 返回至少一个启用账户可以调用模型的通道,anyTier 为 true 时不检查账户权益
+func (p *AccountPool) modelChannelsLocked(model Model, anyTier bool) []string {
+ selection := modelSelection(model.ID, model.Methods, anyTier)
var channels []string
for _, channel := range p.selectionChannelsLocked(selection) {
for _, account := range p.accounts {
diff --git a/internal/aistudio/chinese_rewrite.go b/internal/aistudio/chinese_rewrite.go
index 5356ea26..6211e8f1 100644
--- a/internal/aistudio/chinese_rewrite.go
+++ b/internal/aistudio/chinese_rewrite.go
@@ -10,7 +10,6 @@ import (
)
const (
- userMessageRewriteOff = "off"
userMessageRewriteTraditional = "traditional"
userMessageRewriteMartian = "martian"
)
diff --git a/internal/aistudio/client.go b/internal/aistudio/client.go
index 3e9a82e9..46162737 100644
--- a/internal/aistudio/client.go
+++ b/internal/aistudio/client.go
@@ -99,11 +99,11 @@ type Client struct {
driveCacheMu sync.Mutex
driveTokens map[string]cachedDriveValue
appFolders map[string]cachedDriveValue
- driveTokenFlights map[string]*driveStringFlight
- appFolderFlights map[string]*driveStringFlight
+ driveTokenFlights map[string]*cancellableFlight[string]
+ appFolderFlights map[string]*cancellableFlight[string]
// inlineUploadMu 保护同账户同新附件的在途上传去重表
inlineUploadMu sync.Mutex
- inlineUploads map[inlineUploadFlightKey]*inlineUploadFlight
+ inlineUploads map[inlineUploadFlightKey]*cancellableFlight[FileRef]
}
// cachedDriveValue 保存按账户与认证代次缓存的 Drive 令牌或应用文件夹 ID
@@ -114,13 +114,13 @@ type cachedDriveValue struct {
at time.Time
}
-// driveStringFlight 合并同账户并发的 Drive 令牌或应用文件夹查询,所有等待方取消后立即中止底层调用
-// waiters 由 Client.driveCacheMu 保护
-type driveStringFlight struct {
+// cancellableFlight 合并同键并发请求,所有等待方取消后立即中止底层调用
+// waiters 由所在表的互斥锁保护,Drive 令牌与应用文件夹表为 Client.driveCacheMu,内联附件表为 Client.inlineUploadMu
+type cancellableFlight[V any] struct {
waiters int
cancel context.CancelFunc
done chan struct{}
- value string
+ value V
err error
}
@@ -130,16 +130,6 @@ type inlineUploadFlightKey struct {
key inlineMediaKey
}
-// inlineUploadFlight 合并同账户同新附件的并发上传,所有等待方取消后才中止底层上传
-// waiters 由 Client.inlineUploadMu 保护
-type inlineUploadFlight struct {
- waiters int
- cancel context.CancelFunc
- done chan struct{}
- file FileRef
- err error
-}
-
// NewClient 创建协议客户端
func NewClient(options ClientOptions) *Client {
return &Client{
@@ -157,7 +147,7 @@ func NewClient(options ClientOptions) *Client {
frontend: make(map[string]frontendModels),
driveTokens: make(map[string]cachedDriveValue),
appFolders: make(map[string]cachedDriveValue),
- inlineUploads: make(map[inlineUploadFlightKey]*inlineUploadFlight),
+ inlineUploads: make(map[inlineUploadFlightKey]*cancellableFlight[FileRef]),
}
}
diff --git a/internal/aistudio/decoder.go b/internal/aistudio/decoder.go
index 46b07c67..a64cdc19 100644
--- a/internal/aistudio/decoder.go
+++ b/internal/aistudio/decoder.go
@@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"encoding/json"
+ "encoding/json/jsontext"
"errors"
"fmt"
"io"
@@ -609,6 +610,10 @@ func rawArray(raw json.RawMessage, path string, evidence json.RawMessage) ([]jso
}
func rawString(raw json.RawMessage, path string, evidence json.RawMessage) (string, error) {
+ var buffer [256]byte
+ if unquoted, err := jsontext.AppendUnquote(buffer[:0], bytes.Trim(raw, " \t\r\n")); err == nil {
+ return string(unquoted), nil
+ }
var value string
if err := json.Unmarshal(raw, &value); err != nil {
return "", &ProtocolEvidenceError{Path: path, Detail: "期望字符串", Raw: cloneEvidence(raw, evidence)}
diff --git a/internal/aistudio/event.go b/internal/aistudio/event.go
index 1de526d0..eb34f191 100644
--- a/internal/aistudio/event.go
+++ b/internal/aistudio/event.go
@@ -1,6 +1,7 @@
package aistudio
import (
+ "bytes"
"encoding/base64"
"encoding/binary"
"encoding/json"
@@ -31,6 +32,10 @@ type FrameDecoder struct {
systemRoleTokens int64
// generation 是同一流交错多条生成时保留的第一条生成的标记
generation string
+ // turnTokenRaw、turnToken 与 responseID 是最近一帧的轮次令牌原文及其解码结果,同一流中令牌不变时沿用
+ turnTokenRaw []byte
+ turnToken string
+ responseID string
}
// NewFrameDecoder 创建单次 GenerateContent 的有状态解码器
@@ -81,12 +86,14 @@ func (d *FrameDecoder) decodeValid(raw json.RawMessage) ([]Event, error) {
}
return nil, nil
}
- var generation []json.RawMessage
- if json.Unmarshal(rawAt(frame, 4), &generation) == nil && len(generation) > 0 {
- if d.generation == "" {
- d.generation = string(generation[0])
- } else if string(generation[0]) != d.generation {
- return nil, nil
+ if generationRaw := rawAt(frame, 4); !isJSONNull(generationRaw) {
+ var generation []json.RawMessage
+ if json.Unmarshal(generationRaw, &generation) == nil && len(generation) > 0 {
+ if d.generation == "" {
+ d.generation = string(generation[0])
+ } else if string(generation[0]) != d.generation {
+ return nil, nil
+ }
}
}
candidates, err := splitArray(frame[0], "$[0][][0]", raw, candidateList[:0])
@@ -101,8 +108,17 @@ func (d *FrameDecoder) decodeValid(raw json.RawMessage) ([]Event, error) {
return nil, withMethod(err, "GenerateContent")
}
finishRaw := rawAt(candidate, 1)
- var turnToken string
- _ = json.Unmarshal(rawAt(frame, 7), &turnToken)
+ var turnToken, responseID string
+ if tokenRaw := rawAt(frame, 7); !isJSONNull(tokenRaw) {
+ if !bytes.Equal(tokenRaw, d.turnTokenRaw) {
+ d.turnTokenRaw = append(d.turnTokenRaw[:0], tokenRaw...)
+ d.turnToken, d.responseID = "", ""
+ if token, err := rawString(tokenRaw, "", nil); err == nil {
+ d.turnToken, d.responseID = token, turnResponseID(token)
+ }
+ }
+ turnToken, responseID = d.turnToken, d.responseID
+ }
frameToken := ""
if d.continuable {
_ = json.Unmarshal(rawAt(candidate, 8), &frameToken)
@@ -159,11 +175,13 @@ func (d *FrameDecoder) decodeValid(raw json.RawMessage) ([]Event, error) {
d.continuationRequired = true
d.continuation = d.latestToken
d.finished = true
- return withFrame(events, turnToken, frameUsage), nil
+ return withFrame(events, turnToken, responseID, frameUsage), nil
}
finishReason := decodeFinishReason(finishCode)
var finishMessage string
- _ = json.Unmarshal(rawAt(candidate, 3), &finishMessage)
+ if messageRaw := rawAt(candidate, 3); !isJSONNull(messageRaw) {
+ _ = json.Unmarshal(messageRaw, &finishMessage)
+ }
if !d.finished {
for index := range events {
events[index].FinishFrame = true
@@ -176,12 +194,11 @@ func (d *FrameDecoder) decodeValid(raw json.RawMessage) ([]Event, error) {
d.finished = true
}
}
- return withFrame(events, turnToken, frameUsage), nil
+ return withFrame(events, turnToken, responseID, frameUsage), nil
}
// withFrame 把流帧 field 8 的轮次令牌、令牌中的 responseId 与该帧用量写入该帧的全部事件
-func withFrame(events []Event, token string, usage *Usage) []Event {
- responseID := turnResponseID(token)
+func withFrame(events []Event, token string, responseID string, usage *Usage) []Event {
for index := range events {
events[index].TurnToken = token
events[index].ResponseID = responseID
@@ -246,72 +263,29 @@ func decodePromptFeedback(raw json.RawMessage, evidence json.RawMessage) (*Promp
return &PromptFeedbackError{Reason: decodePromptBlockReason(reason), Message: message, SafetyRatings: ratings, Raw: append(json.RawMessage(nil), raw...)}, nil
}
+var promptBlockReasons = []string{"unspecified", "safety", "other", "blocklist", "prohibited_content", "image_safety"}
+
func decodePromptBlockReason(reason int64) string {
- switch reason {
- case 0:
- return "unspecified"
- case 1:
- return "safety"
- case 2:
- return "other"
- case 3:
- return "blocklist"
- case 4:
- return "prohibited_content"
- case 5:
- return "image_safety"
- default:
- return fmt.Sprintf("provider_%d", reason)
+ if reason >= 0 && int(reason) < len(promptBlockReasons) {
+ return promptBlockReasons[reason]
}
+ return fmt.Sprintf("provider_%d", reason)
+}
+
+var finishReasons = map[int64]string{
+ 0: "unspecified", 1: "stop", 2: "max_tokens", 3: "safety", 4: "recitation",
+ 5: "other", 6: "language", 7: "blocklist", 8: "prohibited_content", 9: "spii",
+ 10: "malformed_function_call", 11: "image_safety", 12: "unexpected_tool_call",
+ 13: "too_many_tool_calls", 14: "image_prohibited_content", 15: "image_other",
+ 16: "no_image", 17: "image_recitation", 18: "missing_thought_signature",
+ 19: "malformed_response", 22: "continuation",
}
func decodeFinishReason(code int64) string {
- switch code {
- case 0:
- return "unspecified"
- case 1:
- return "stop"
- case 2:
- return "max_tokens"
- case 3:
- return "safety"
- case 4:
- return "recitation"
- case 5:
- return "other"
- case 6:
- return "language"
- case 7:
- return "blocklist"
- case 8:
- return "prohibited_content"
- case 9:
- return "spii"
- case 10:
- return "malformed_function_call"
- case 11:
- return "image_safety"
- case 12:
- return "unexpected_tool_call"
- case 13:
- return "too_many_tool_calls"
- case 14:
- return "image_prohibited_content"
- case 15:
- return "image_other"
- case 16:
- return "no_image"
- case 17:
- return "image_recitation"
- case 18:
- return "missing_thought_signature"
- case 19:
- return "malformed_response"
- case 22:
- return "continuation"
- default:
- return fmt.Sprintf("provider_%d", code)
+ if name, ok := finishReasons[code]; ok {
+ return name
}
+ return fmt.Sprintf("provider_%d", code)
}
// End 校验流已经出现正常完成帧
diff --git a/internal/aistudio/generate.go b/internal/aistudio/generate.go
index ec863c2f..92350612 100644
--- a/internal/aistudio/generate.go
+++ b/internal/aistudio/generate.go
@@ -192,26 +192,14 @@ func resolveGenerationSettings(config GenerationConfig, defaults GenerationDefau
effort := normalizedReasoningEffort(config.ReasoningEffort)
hasReasoningEffort := effort != ""
thinkingBudget := config.ThinkingBudget
- switch effort {
- case "":
- case "low":
- thinkingLevel = 1
- case "medium":
- thinkingLevel = 2
- case "high":
- thinkingLevel = 3
- case "xhigh", "extra_high", "max":
- thinkingLevel = 5
- case "minimal":
- thinkingLevel = 4
- case "none":
- thinkingLevel = 4
- if !defaults.ThinkingLevel && defaults.ThinkingBudget && thinkingBudget == nil {
+ if parsed, ok, err := parseReasoningEffortLevel(effort, 5); err != nil {
+ return settings, err
+ } else if ok {
+ thinkingLevel = parsed
+ if effort == "none" && !defaults.ThinkingLevel && defaults.ThinkingBudget && thinkingBudget == nil {
zero := int64(0)
thinkingBudget = &zero
}
- default:
- return settings, fmt.Errorf("reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max")
}
if hasReasoningEffort && defaults.ThinkingLevel {
thinkingLevel = closestSupportedThinkingLevel(thinkingLevel, defaults.ThinkingLevels)
@@ -329,7 +317,7 @@ func encodeGenerationConfig(config GenerationConfig, defaults GenerationDefaults
if settings.responseSchema != nil {
wire[8] = playgroundSchema(settings.responseSchema, true, true)
}
- if !defaults.ImageRoute {
+ if defaults.EnhancedCivicAnswers && !slices.Contains(settings.modalities, int64(3)) {
wire[13] = int64(1)
}
if settings.modalities != nil {
@@ -744,8 +732,15 @@ func speakerSegments(part Part, pattern *regexp.Regexp) []Part {
// validateGenerateRequest 用各账户已载入的模型条目校验请求,任一条目接受即通过,目录未载入时交给生成路径
func (c *Client) validateGenerateRequest(request GenerateRequest) error {
+ normalized := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/")
+ c.catalogMu.RLock()
+ defer c.catalogMu.RUnlock()
var first error
- for _, entry := range c.cachedModelEntries(request.Model) {
+ for _, catalog := range c.catalogs {
+ entry, exists := catalog.lookup(normalized)
+ if !exists {
+ continue
+ }
err := validateGenerateEntry(request, entry)
if err == nil {
return nil
diff --git a/internal/aistudio/hidden_models.go b/internal/aistudio/hidden_models.go
index 1e4838f3..3ac4d660 100644
--- a/internal/aistudio/hidden_models.go
+++ b/internal/aistudio/hidden_models.go
@@ -28,8 +28,14 @@ type frontendModels struct {
var (
// frontendFamilyPattern 匹配推荐模型页配置开头的模型族名与页面类型
frontendFamilyPattern = regexp.MustCompile(`\{id:"([a-z0-9.-]+)",type:"([a-z]+)"`)
- // frontendFamilyNamePattern 匹配推荐模型页按模型名筛选目录的 models/ 名称
- frontendFamilyNamePattern = regexp.MustCompile(`EA:\["models/([a-z0-9.-]+)"`)
+ // frontendModelListVarPattern 匹配前置声明的 models/ 字符串数组变量(如 XGc=["models/gemini-4-hydrogen"])
+ frontendModelListVarPattern = regexp.MustCompile(`(?:^|[^A-Za-z0-9_$])([A-Za-z_$][A-Za-z0-9_$]*)=\[((?:"models/[a-z0-9.-]+"(?:,"models/[a-z0-9.-]+")*))\]`)
+ // frontendInlineModelsPattern 匹配对象内任意属性名对应的 models/ 字符串数组字面量,不依赖压缩后的属性名
+ frontendInlineModelsPattern = regexp.MustCompile(`[A-Za-z_$][A-Za-z0-9_$]*:\[((?:"models/[a-z0-9.-]+"(?:,"models/[a-z0-9.-]+")*))\]`)
+ // frontendPropIdentPattern 匹配对象内引用前置变量的任意属性赋值
+ frontendPropIdentPattern = regexp.MustCompile(`[A-Za-z_$][A-Za-z0-9_$]*:([A-Za-z_$][A-Za-z0-9_$]*)`)
+ // frontendModelItemPattern 从 models/ 字符串数组片段中提取模型名或模型族前缀
+ frontendModelItemPattern = regexp.MustCompile(`"models/([a-z0-9.-]+)"`)
// frontendChatModulePattern 匹配主程序路由表中对话页按需载入的模块 ID
frontendChatModulePattern = regexp.MustCompile(`path:"prompts/new_chat",[^{}]*?\("([A-Za-z0-9_]+)"\)`)
// frontendModelPatterns 匹配推荐模型页路由的 model 查询参数与模型文档链接
@@ -39,16 +45,69 @@ var (
}
)
+// jsObjectSlice 返回 source 中从 start 处 '{' 开始的平衡 JS 对象字面量切片,找不到闭合大括号时返回 nil
+func jsObjectSlice(source []byte, start int) []byte {
+ depth := 0
+ var quote byte
+ for i := start; i < len(source); i++ {
+ ch := source[i]
+ if quote != 0 {
+ if ch == '\\' {
+ i++
+ continue
+ }
+ if ch == quote {
+ quote = 0
+ }
+ continue
+ }
+ switch ch {
+ case '"', '\'', '`':
+ quote = ch
+ case '{':
+ depth++
+ case '}':
+ depth--
+ if depth == 0 {
+ return source[start : i+1]
+ }
+ }
+ }
+ return nil
+}
+
+// extractModelListNames 从 '"models/a","models/b"' 片段提取去掉 models/ 前缀的名称列表
+func extractModelListNames(raw []byte) []string {
+ matches := frontendModelItemPattern.FindAllSubmatch(raw, -1)
+ names := make([]string, 0, len(matches))
+ for _, match := range matches {
+ names = append(names, string(match[1]))
+ }
+ return names
+}
+
// parseFrontendModels 从官网前端主程序读取推荐模型页的模型族与指向的模型 ID
func parseFrontendModels(source []byte) frontendModels {
- named := make(map[string]bool)
- for _, match := range frontendFamilyNamePattern.FindAllSubmatch(source, -1) {
- named[string(match[1])] = true
+ varModels := make(map[string][]string)
+ for _, match := range frontendModelListVarPattern.FindAllSubmatch(source, -1) {
+ varModels[string(match[1])] = extractModelListNames(match[2])
}
parsed := frontendModels{families: make(map[string]string)}
- for _, match := range frontendFamilyPattern.FindAllSubmatch(source, -1) {
- if named[string(match[1])] {
- parsed.families[string(match[1])] = string(match[2])
+ for _, loc := range frontendFamilyPattern.FindAllSubmatchIndex(source, -1) {
+ obj := jsObjectSlice(source, loc[0])
+ if len(obj) == 0 {
+ continue
+ }
+ pageType := string(source[loc[4]:loc[5]])
+ var names []string
+ for _, match := range frontendInlineModelsPattern.FindAllSubmatch(obj, -1) {
+ names = append(names, extractModelListNames(match[1])...)
+ }
+ for _, match := range frontendPropIdentPattern.FindAllSubmatch(obj, -1) {
+ names = append(names, varModels[string(match[1])]...)
+ }
+ for _, name := range names {
+ parsed.families[name] = pageType
}
}
for _, pattern := range frontendModelPatterns {
@@ -169,7 +228,7 @@ func (catalog modelCatalog) withHidden(hidden map[string]string) modelCatalog {
if _, listed := catalog.lookup(modelID); listed || !ok {
continue
}
- model := cloneModels([]Model{template.model})[0]
+ model := cloneModel(template.model)
model.ID, model.Name, model.Description, model.Hidden = modelID, modelID, "", true
model.Details, model.AccessModes, model.Paid = nil, nil, false
delete(model.CapabilityOptions, "aliases")
diff --git a/internal/aistudio/imagen.go b/internal/aistudio/imagen.go
index 48332bc0..a1a38ad8 100644
--- a/internal/aistudio/imagen.go
+++ b/internal/aistudio/imagen.go
@@ -82,7 +82,7 @@ func (t *WorkerProtectedTransport) DoProtectedImage(ctx context.Context, request
// EncodeGenerateImageRequest 编码官网 GenerateImage 数组协议:模型、提示词、proof 位与图片数、反向提示词、宽高比、输出分辨率配置,返回正文与 proof 位在正文中的起始字节
func EncodeGenerateImageRequest(request ImageRequest) ([]byte, int) {
- config := []any{nullableInt(request.SampleCount), nullableString(request.NegativePrompt), nullableString(request.AspectRatio), nullableString(request.ImageSize)}
+ config := []any{nullableInt(request.SampleCount), emptyNil(request.NegativePrompt), emptyNil(request.AspectRatio), emptyNil(request.ImageSize)}
for len(config) > 0 && config[len(config)-1] == nil {
config = config[:len(config)-1]
}
@@ -126,10 +126,3 @@ func nullableInt(value int) any {
}
return value
}
-
-func nullableString(value string) any {
- if value == "" {
- return nil
- }
- return value
-}
diff --git a/internal/aistudio/interaction.go b/internal/aistudio/interaction.go
index 6309c563..e65fc3ce 100644
--- a/internal/aistudio/interaction.go
+++ b/internal/aistudio/interaction.go
@@ -91,6 +91,7 @@ func modelGenerationDefaults(model Model) GenerationDefaults {
DefaultThinkingLevel: 2,
ImageRoute: model.Capabilities["image_route"],
OutputResolution: model.Capabilities["output_resolution"],
+ EnhancedCivicAnswers: model.Capabilities["capability_code_18"],
InteractionStream: model.Capabilities["interaction_stream"],
InteractionTask: model.Capabilities["interaction_task"],
InteractionAgent: model.Capabilities["interaction_agent"],
@@ -766,26 +767,35 @@ func encodeInteractionServerToolResponse(step *ServerToolStep) []any {
return []any{nil, nil, nil, nil, []any{step.ID, nil, nil, nil, nil, []any{entries}}}
}
-// interactionThinkingLevel 按请求的思考强度或预算选择模型支持的 Interaction thinking level,模型没有思考档位能力时与官网一样不发送并返回 0
-func interactionThinkingLevel(config GenerationConfig, defaults GenerationDefaults) (int64, error) {
- level := defaults.DefaultThinkingLevel
- switch normalizedReasoningEffort(config.ReasoningEffort) {
+// parseReasoningEffortLevel 把规范化后的 reasoning effort 映射到内部档位编码,空值返回 ok=false
+func parseReasoningEffortLevel(effort string, xhighLevel int64) (int64, bool, error) {
+ switch effort {
case "":
- if config.ThinkingBudget != nil {
- level = thinkingLevelForBudget(*config.ThinkingBudget)
- }
+ return 0, false, nil
case "minimal", "none":
- level = 4
+ return 4, true, nil
case "low":
- level = 1
+ return 1, true, nil
case "medium":
- level = 2
+ return 2, true, nil
case "high":
- level = 3
+ return 3, true, nil
case "xhigh", "extra_high", "max":
- level = 5
+ return xhighLevel, true, nil
default:
- return 0, fmt.Errorf("reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max")
+ return 0, false, fmt.Errorf("reasoning effort 必须是 none、minimal、low、medium、high、xhigh、extra_high 或 max")
+ }
+}
+
+// interactionThinkingLevel 按请求的思考强度或预算选择模型支持的 Interaction thinking level,模型没有思考档位能力时与官网一样不发送并返回 0
+func interactionThinkingLevel(config GenerationConfig, defaults GenerationDefaults) (int64, error) {
+ level := defaults.DefaultThinkingLevel
+ if parsed, ok, err := parseReasoningEffortLevel(normalizedReasoningEffort(config.ReasoningEffort), 5); err != nil {
+ return 0, err
+ } else if ok {
+ level = parsed
+ } else if config.ThinkingBudget != nil {
+ level = thinkingLevelForBudget(*config.ThinkingBudget)
}
if !defaults.ThinkingLevel {
return 0, nil
@@ -1072,21 +1082,8 @@ func DecodeInteractionStream(method string, source io.Reader, emit func(Event) e
trailing = append(trailing, raw)
}
if len(trailing) > 0 {
- // 流尾 field 2 为 google.rpc.Status:[code, message, details]
- status, err := rawArray(trailing[0], "$[1]", trailing[0])
- if err != nil || len(status) == 0 {
- return &ProtocolEvidenceError{Method: method, Path: "$[1]", Detail: "流尾状态无效", Raw: cloneRaw(trailing[0])}
- }
- code, err := rawInt64(status[0], "$[1][0]", trailing[0])
- if err != nil {
- return withMethod(err, method)
- }
- if code != 0 {
- statusCode := http.StatusBadGateway
- if status, ok := interactionStatusHTTP[code]; ok {
- statusCode = status
- }
- return DecodeRPCError(method, statusCode, trailing[0])
+ if err := trailerError(method, trailing[0]); err != nil {
+ return err
}
}
if !finished {
@@ -1660,7 +1657,7 @@ func (d *interactionStreamDecoder) emitURLContextResult(callID string, itemsRaw
return nil
}
var urls []URLMetadata
- var metadata []map[string]any
+ metadata := make([]map[string]any, 0, len(items))
for _, item := range items {
fields, err := rawArray(item, "$url_results[]", evidence)
if err != nil {
diff --git a/internal/aistudio/models.go b/internal/aistudio/models.go
index 5054bf62..1de4504d 100644
--- a/internal/aistudio/models.go
+++ b/internal/aistudio/models.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "maps"
"strconv"
"strings"
)
@@ -206,6 +207,8 @@ type GenerationDefaults struct {
ImageRoute bool
// OutputResolution 表示支持输出分辨率(官网会带 imageConfig 与扩展槽位)
OutputResolution bool
+ // EnhancedCivicAnswers 表示 ListModels 能力码含 18(官网 GenerateContent 在非音频模态下写 config[13]=1)
+ EnhancedCivicAnswers bool
// InteractionStream 表示官网经 CreateInteractionStream 生成的模型
InteractionStream bool
// InteractionTask 表示官网经 CreateInteraction 创建后台任务、经 GetInteractionStream 读取结果的模型
@@ -376,6 +379,10 @@ func decodeModelRow(raw json.RawMessage, rowIndex int) (modelEntry, error) {
if err != nil {
return modelEntry{}, err
}
+ defaultVoice, err := decodeDefaultVoice(rawAt(row, 88), path+"[88]", raw, liveVoices, capabilities["speech_translation"])
+ if err != nil {
+ return modelEntry{}, err
+ }
id := strings.TrimPrefix(wireName, "models/")
if id == "" {
return modelEntry{}, &ProtocolEvidenceError{Method: "ListModels", Path: path + "[0]", Detail: "模型 ID 为空", Raw: raw}
@@ -386,12 +393,13 @@ func decodeModelRow(raw json.RawMessage, rowIndex int) (modelEntry, error) {
Description: description,
Version: version,
Stage: modelStageName(stageCode),
- Methods: append([]string(nil), methods...),
+ Methods: append([]string{}, methods...),
InputTokenLimit: inputLimit,
OutputTokenLimit: outputLimit,
Capabilities: capabilities,
CapabilityOptions: options,
VoiceDetails: append(voices, liveVoices...),
+ DefaultVoice: defaultVoice,
Languages: languages,
AccessModes: append([]int64(nil), accessModes...),
Paid: paidCode == 2,
@@ -631,6 +639,7 @@ func decodeGenerationDefaults(row []json.RawMessage, path string, evidence json.
Thinking: capabilities["thinking"], ThinkingBudget: capabilities["thinking_budget"],
ThinkingLevel: capabilities["thinking_level"], DefaultThinkingLevel: 2,
ImageRoute: capabilities["image_route"], OutputResolution: capabilities["output_resolution"],
+ EnhancedCivicAnswers: capabilities["capability_code_18"],
InteractionStream: routing.IsStream(), InteractionTask: routing.IsTask(),
InteractionAgent: routing.IsAgent(), InteractionModel: routing.IsModel(),
VideoOutput: capabilities["secondary_capability_code_14"] && capabilities["chat_model"],
@@ -747,20 +756,6 @@ func (c *Client) modelEntry(ctx context.Context, accountID string, modelID strin
return entry, nil
}
-// cachedModelEntries 返回各账户已载入目录中的模型条目,不发起网络请求
-func (c *Client) cachedModelEntries(modelID string) []modelEntry {
- normalized := strings.TrimPrefix(strings.TrimSpace(modelID), "models/")
- c.catalogMu.RLock()
- defer c.catalogMu.RUnlock()
- var entries []modelEntry
- for _, catalog := range c.catalogs {
- if entry, exists := catalog.lookup(normalized); exists {
- entries = append(entries, entry)
- }
- }
- return entries
-}
-
func (catalog modelCatalog) lookup(modelID string) (modelEntry, bool) {
if entry, exists := catalog.entries[modelID]; exists {
return entry, true
@@ -937,6 +932,27 @@ func decodeVoiceDetails(raw json.RawMessage, path string, evidence json.RawMessa
return voices, nil
}
+// decodeDefaultVoice 返回 Live 模型的默认音色:field 89 的第一项,没有时对话模型取 Live 音色列表的第一个,翻译模型默认不选音色;没有 Live 音色的模型返回空
+func decodeDefaultVoice(raw json.RawMessage, path string, evidence json.RawMessage, liveVoices []VoiceDetail, translation bool) (string, error) {
+ if len(liveVoices) == 0 {
+ return "", nil
+ }
+ if !isJSONNull(raw) {
+ defaults, err := rawArray(raw, path, evidence)
+ if err != nil {
+ return "", withMethod(err, "ListModels")
+ }
+ if name := rawAt(defaults, 0); !isJSONNull(name) {
+ value, err := rawString(name, path+"[0]", evidence)
+ return value, withMethod(err, "ListModels")
+ }
+ }
+ if translation {
+ return "", nil
+ }
+ return liveVoices[0].Name, nil
+}
+
// decodeLanguages 解析 ListModels field 68 的 [语言代码, 显示名] 列表
func decodeLanguages(raw json.RawMessage, path string, evidence json.RawMessage) ([]Language, error) {
if isJSONNull(raw) {
@@ -1024,26 +1040,27 @@ func appendOption(options map[string][]string, key string, values []string) {
}
}
+// cloneModel 返回与 model 不共享方法、能力与选项切片和映射的副本
+func cloneModel(model Model) Model {
+ result := model
+ result.Methods = append([]string{}, model.Methods...)
+ result.AccessModes = append([]int64(nil), model.AccessModes...)
+ result.ThinkingLevels = append([]string(nil), model.ThinkingLevels...)
+ result.ToolCompatibility = append([][2]string(nil), model.ToolCompatibility...)
+ result.Capabilities = maps.Clone(model.Capabilities)
+ if model.CapabilityOptions != nil {
+ result.CapabilityOptions = make(map[string][]string, len(model.CapabilityOptions))
+ for key, value := range model.CapabilityOptions {
+ result.CapabilityOptions[key] = append([]string(nil), value...)
+ }
+ }
+ return result
+}
+
func cloneModels(models []Model) []Model {
result := make([]Model, len(models))
for index, model := range models {
- result[index] = model
- result[index].Methods = append([]string(nil), model.Methods...)
- result[index].AccessModes = append([]int64(nil), model.AccessModes...)
- result[index].ThinkingLevels = append([]string(nil), model.ThinkingLevels...)
- result[index].ToolCompatibility = append([][2]string(nil), model.ToolCompatibility...)
- if model.Capabilities != nil {
- result[index].Capabilities = make(map[string]bool, len(model.Capabilities))
- for key, value := range model.Capabilities {
- result[index].Capabilities[key] = value
- }
- }
- if model.CapabilityOptions != nil {
- result[index].CapabilityOptions = make(map[string][]string, len(model.CapabilityOptions))
- for key, value := range model.CapabilityOptions {
- result[index].CapabilityOptions[key] = append([]string(nil), value...)
- }
- }
+ result[index] = cloneModel(model)
}
return result
}
diff --git a/internal/aistudio/page_analytics.go b/internal/aistudio/page_analytics.go
index 9b477a5d..71376bcc 100644
--- a/internal/aistudio/page_analytics.go
+++ b/internal/aistudio/page_analytics.go
@@ -28,6 +28,8 @@ const (
analyticsFlushDelay = 5 * time.Second
// analyticsJoinInterval 是 gtag 经 analytics.google.com 发送命中时再次附带 _gaz=1 的最小间隔
analyticsJoinInterval = 60 * time.Second
+ // analyticsSessionTimeout 是 GA4 同一用户在已授予统计存储(gcs=G111)时复用会话 sid 的超时时长
+ analyticsSessionTimeout = 30 * time.Minute
// analyticsConsentDenied 是 Cookie 提示条拒绝后 gtag 命中的同意状态参数
analyticsConsentDenied = "gcs=G100&gcd=13q3q3l3q5l1&npa=1&dma=0"
// analyticsConsentGranted 是不需要 Cookie 提示条且无本地选择记录时 gtag 命中的同意状态参数
@@ -245,6 +247,7 @@ type analyticsTarget struct {
rcb int
ecid uint32
sid int64
+ sct int
seq int
last time.Time
// gazAt 是上次经 analytics.google.com 发送命中时附带 _gaz=1 的时刻
@@ -278,9 +281,10 @@ type pageAnalytics struct {
// granted 表示 2a.json 返回不需要提示条且账户无本地选择记录,广告与统计存储均为 granted
granted bool
// rewritten 是 GTM 改写主机名后的页面地址
- rewritten string
- cid string
- shared map[int]int64
+ rewritten string
+ cid string
+ firstVisit bool
+ shared map[int]int64
targets []*analyticsTarget
// loaded 表示 GTM 容器与各 gtag 脚本的载入已结束,此后事件只交给已载入的目标
loaded bool
@@ -385,25 +389,46 @@ func (analytics *pageAnalytics) ready(tag analyticsTag, container *tagScript, sc
return
}
now := time.Now()
+ sid := now.Unix()
+ sct := 1
+ firstVisit := true
+ firstTarget := analytics.cid == ""
+ sessionStart := true
+ if analytics.granted {
+ cid, freshVisit, s, count, freshSession := analytics.runtime.session.analyticsIdentity(tag.id, now)
+ if firstTarget {
+ analytics.cid = cid
+ analytics.firstVisit = freshVisit
+ }
+ firstVisit = analytics.firstVisit
+ sid, sct, sessionStart = s, count, freshSession
+ } else if firstTarget {
+ analytics.cid = strconv.FormatUint(uint64(rand.Uint32()>>1), 10) + "." + strconv.FormatInt(now.Unix(), 10)
+ analytics.firstVisit = true
+ } else {
+ firstVisit = analytics.firstVisit
+ }
target := &analyticsTarget{
tag: tag, build: container.Build, version: script.Version, container: container.Container, tagExp: analytics.experiments(script),
- rcb: rand.IntN(20), ecid: rand.Uint32() >> 1, sid: now.Unix(), last: now, script: address, cached: cached,
+ rcb: rand.IntN(20), ecid: rand.Uint32() >> 1, sid: sid, sct: sct, last: now, script: address, cached: cached,
}
if tagSample() >= 1-script.Diagnostics {
target.diagnostics, target.pid = true, rand.Int64N(1<<31)
analytics.diagnose(target, false)
}
- first := analytics.cid == ""
- if first {
- analytics.cid = strconv.FormatUint(uint64(rand.Uint32()>>1), 10) + "." + strconv.FormatInt(now.Unix(), 10)
- }
analytics.targets = append(analytics.targets, target)
- view := analyticsEvent{name: "page_view", gtm: true, at: now, params: []string{"_fv=1"}}
- if first {
- view.params = append(view.params, "_nsi=1")
+ var params []string
+ if firstVisit {
+ params = append(params, "_fv=1")
+ if firstTarget {
+ params = append(params, "_nsi=1")
+ }
}
- view.params = append(view.params, "_ss=1")
- view.params = append(view.params, analytics.eventParams(tag, "ep.percent_scrolled=0", "ep.scroll_increment=0", "ep.scroll_instance=1")...)
+ if sessionStart {
+ params = append(params, "_ss=1")
+ }
+ params = append(params, analytics.eventParams(tag, "ep.percent_scrolled=0", "ep.scroll_increment=0", "ep.scroll_instance=1")...)
+ view := analyticsEvent{name: "page_view", gtm: true, at: now, params: params}
analytics.send(target, []analyticsEvent{view}, now)
}
@@ -630,7 +655,10 @@ func (analytics *pageAnalytics) send(target *analyticsTarget, events []analytics
if len(events) == 1 && events[0].location != "" {
location[1] = "dl=" + uriComponent(events[0].location)
}
- session := []string{"sid=" + strconv.FormatInt(target.sid, 10), "sct=1", segment}
+ session := []string{"sid=" + strconv.FormatInt(target.sid, 10), "sct=" + strconv.Itoa(target.sct), segment}
+ if analytics.granted {
+ analytics.runtime.session.touchAnalyticsSession(tag.id, now)
+ }
tfd := "tfd=" + strconv.FormatInt(now.Sub(analytics.runtime.profile.NavigationStart).Milliseconds(), 10)
var body []byte
if len(events) == 1 {
@@ -684,22 +712,22 @@ func (analytics *pageAnalytics) send(target *analyticsTarget, events []analytics
address := collectURL + "?" + strings.Join(query, "&")
fallback := analyticsFallbackURL + "?" + strings.Join(fallbackQuery(query, tag.flags), "&")
runtime := analytics.runtime
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
- defer cancel()
+ unloading := runtime.unloading.Load()
+ runtime.startTelemetrySend(unloading, func(ctx context.Context) {
response, err := runtime.do(ctx, http.MethodPost, address, body, headers)
if err == nil {
runtime.drain(response, nil)
return
}
+ if ctx.Err() != nil {
+ return
+ }
analytics.mu.Lock()
target.fallbacks++
analytics.mu.Unlock()
headers.Set("Sec-Fetch-Site", fetchSite(analyticsFallbackURL))
- anonymous, cancel := context.WithTimeout(withRequestClass(context.Background(), requestClass{anonymous: true}), time.Minute)
- defer cancel()
- runtime.drain(runtime.do(anonymous, http.MethodPost, fallback, body, headers))
- }()
+ runtime.drain(runtime.do(withRequestClass(ctx, requestClass{anonymous: true}), http.MethodPost, fallback, body, headers))
+ })
}
// tagSample 是 GTM 容器与 gtag 每次载入为 tag 诊断抽样取的随机数
@@ -743,15 +771,14 @@ func (analytics *pageAnalytics) diagnose(target *analyticsTarget, fin bool) {
query := "&" + strings.Join(params, "&")
address := analyticsDiagnosticsURL + "?id=" + tag.id + query
runtime := analytics.runtime
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
- defer cancel()
+ unloading := fin || runtime.unloading.Load()
+ runtime.startTelemetrySend(unloading, func(ctx context.Context) {
runtime.drain(runtime.do(ctx, method, address, nil, headers))
- if fin {
+ if fin && ctx.Err() == nil {
script := target.script + "&is_td=1" + query
runtime.drain(runtime.do(ctx, http.MethodGet, script, nil, subresourceHeaders(script, "*/*", "script", "")))
}
- }()
+ })
}
// diagnoseContainer 像抽中诊断的 GTM 容器一样在 gtm.init 时以图片请求发出 seq=1 的 tag 诊断:experiments 是容器上报的实验,cached 表示容器脚本取自页面缓存
diff --git a/internal/aistudio/page_attachments.go b/internal/aistudio/page_attachments.go
index 32995091..61f5f0c7 100644
--- a/internal/aistudio/page_attachments.go
+++ b/internal/aistudio/page_attachments.go
@@ -120,6 +120,21 @@ func (runtime *goWAARuntime) beforeUploadNonBlocking(ctx context.Context, rerun
}
}
+// markAppFolderCalled 记下共享查询发出 GetAppFolder 的页面已按官网 shareReplay(1) 发出过 GetAppFolder,该页面为 ctx 中发起请求所在的页面,没有时为当前主页面
+func markAppFolderCalled(ctx context.Context, accountID string) {
+ worker := pageWorker(accountID)
+ if worker == nil {
+ return
+ }
+ page, ok := flightPageFromContext(ctx)
+ if !ok {
+ page = worker.current()
+ }
+ if runtime, ok := page.(*goWAARuntime); ok {
+ runtime.appFolderCalled.Store(true)
+ }
+}
+
// refreshAppFolderAsync 在本页面还没发过 GetAppFolder 时于后台发出一次,返回的文件夹 ID 交给 onFresh
func (runtime *goWAARuntime) refreshAppFolderAsync(ctx context.Context, onFresh func(string)) {
if runtime.client == nil || runtime.session == nil || !runtime.appFolderCalled.CompareAndSwap(false, true) {
diff --git a/internal/aistudio/page_auxiliary.go b/internal/aistudio/page_auxiliary.go
index 96ef4010..52fcd7d1 100644
--- a/internal/aistudio/page_auxiliary.go
+++ b/internal/aistudio/page_auxiliary.go
@@ -47,8 +47,6 @@ const (
lockupImage = "https://www.gstatic.com/images/branding/productlogos/makersuite/lockup_dark.svg"
// googleLogoImage 是新对话页主体中的 Google 标志
googleLogoImage = "https://www.gstatic.com/images/branding/productlogos/googleg/v6/24px.svg"
- // thinkingImage 是回答中思考面板的图标
- thinkingImage = "https://www.gstatic.com/aistudio/watermark/watermark.png"
// imageAccept 是 Firefox 158 图片请求的 Accept
imageAccept = "image/avif,image/jxl,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5"
// fontAccept 是 Firefox 158 字体请求的 Accept
@@ -179,7 +177,7 @@ func (runtime *goWAARuntime) loadPageScripts(ctx context.Context) {
}
// 同账户的第二个标签页从缓存载入 gapi 的加载脚本与 client 模块,页面应用开始请求后 180–720 ms 读取账户资料
client := runtime.pageCache.notes(gapiLoaderScript).Gapi
- _, loaderCached := runtime.pageCache.lookup(gapiLoaderScript, start)
+ loaderEntry, loaderCached := runtime.pageCache.lookup(gapiLoaderScript, start)
_, clientCached := runtime.pageCache.lookup(client, start)
cached := client != "" && loaderCached && clientCached
if cached {
@@ -192,16 +190,22 @@ func (runtime *goWAARuntime) loadPageScripts(ctx context.Context) {
if !wait(770 * time.Millisecond) {
return
}
- prefetch := http.Header{}
- prefetch.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
- prefetch.Set("Referer", aiStudioOrigin+"/")
- prefetch.Set("Sec-Purpose", "prefetch")
- prefetch.Set("Sec-Fetch-Dest", "empty")
- prefetch.Set("Sec-Fetch-Mode", "no-cors")
- prefetch.Set("Sec-Fetch-Site", fetchSite(gapiLoaderScript))
- prefetch.Set("Priority", "u=6")
+ var loaderHeaders http.Header
+ if loaderEntry.Received.IsZero() {
+ loaderHeaders = http.Header{}
+ loaderHeaders.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
+ loaderHeaders.Set("Referer", aiStudioOrigin+"/")
+ loaderHeaders.Set("Sec-Purpose", "prefetch")
+ loaderHeaders.Set("Sec-Fetch-Dest", "empty")
+ loaderHeaders.Set("Sec-Fetch-Mode", "no-cors")
+ loaderHeaders.Set("Sec-Fetch-Site", fetchSite(gapiLoaderScript))
+ loaderHeaders.Set("Priority", "u=6")
+ } else {
+ // 缓存过期需要条件重验时按普通脚本请求,不带 Sec-Purpose: prefetch
+ loaderHeaders = subresourceHeaders(gapiLoaderScript, "*/*", "script", "")
+ }
loaded := make(chan error, 1)
- group.Go(func() { loaded <- runtime.fetchCached(ctx, gapiLoaderScript, prefetch) })
+ group.Go(func() { loaded <- runtime.fetchCached(ctx, gapiLoaderScript, loaderHeaders) })
group.Go(func() {
_ = runtime.fetchCached(ctx, feedbackScript, subresourceHeaders(feedbackScript, "*/*", "script", ""))
})
@@ -209,6 +213,9 @@ func (runtime *goWAARuntime) loadPageScripts(ctx context.Context) {
group.Go(func() {
target := cookieBarConfigURL(runtime.cookieBarLanguage)
err := runtime.fetchCached(ctx, target, corsHeaders(target))
+ if err == nil && runtime.pageCache.notes(target).ConsentOptional {
+ runtime.vitals.setCookieBar(false)
+ }
close(ready)
if err == nil && ctx.Err() == nil {
runtime.analytics.load(ctx)
@@ -310,7 +317,7 @@ func (runtime *goWAARuntime) loadProfile(ctx context.Context) (string, error) {
return base + "=s64-cc-" + options, nil
}
-// loadRenderedResources 在页面框架、主体、入门卡片与思考面板渲染时请求其中的图片与字体:框架为产品标志、Inter 与 Google Symbols,主体为 Inter Tight 与 Google 标志,入门卡片为示例应用的预览图,思考面板为思考图标
+// loadRenderedResources 在页面框架、主体与入门卡片渲染时请求其中的图片与字体:框架为产品标志、Inter 与 Google Symbols,主体为 Inter Tight 与 Google 标志,入门卡片为示例应用的预览图
func (runtime *goWAARuntime) loadRenderedResources(ctx context.Context, document pageDocument, part pageRenderPart, images []string) {
var fonts [][2]string
switch part {
@@ -320,11 +327,9 @@ func (runtime *goWAARuntime) loadRenderedResources(ctx context.Context, document
case pageRenderMain:
images = append(images, googleLogoImage)
fonts = append(fonts, [2]string{runtime.fontURL(document, "Inter Tight"), "https://" + googleFontsHost + "/"})
- case pageRenderThoughts:
- images = append(images, thinkingImage)
}
priority := "u=4, i"
- if part == pageRenderCards || part == pageRenderThoughts {
+ if part == pageRenderCards {
priority = "u=5, i"
}
for _, image := range images {
@@ -371,19 +376,31 @@ type pageStorage struct {
items map[string]string
}
-// loadPageStorage 读取账户目录中页面写入的 localStorage 项,文件不存在时为空
+// pageStorageRegistry 按规范化后的存储路径在同账户多个页面间共享同一 *pageStorage 实例,防止并发页面与重载互相覆盖彼此写入的键
+var (
+ pageStorageRegistryMu sync.Mutex
+ pageStorageRegistry = map[string]*pageStorage{}
+)
+
+// loadPageStorage 读取或复用账户目录中页面写入的 localStorage 项,文件不存在时为空
func loadPageStorage(storageStatePath string) (*pageStorage, error) {
- storage := &pageStorage{path: filepath.Join(filepath.Dir(storageStatePath), pageStorageFile), items: map[string]string{}}
- data, err := os.ReadFile(storage.path)
- if errors.Is(err, os.ErrNotExist) {
- return storage, nil
+ target := filepath.Clean(filepath.Join(filepath.Dir(storageStatePath), pageStorageFile))
+ pageStorageRegistryMu.Lock()
+ defer pageStorageRegistryMu.Unlock()
+ if existing, ok := pageStorageRegistry[target]; ok {
+ return existing, nil
}
- if err != nil {
+ storage := &pageStorage{path: target, items: map[string]string{}}
+ data, err := os.ReadFile(storage.path)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("读取页面 localStorage: %w", err)
}
- if err := json.Unmarshal(data, &storage.items); err != nil {
- return nil, fmt.Errorf("解析页面 localStorage: %w", err)
+ if err == nil {
+ if err := json.Unmarshal(data, &storage.items); err != nil {
+ return nil, fmt.Errorf("解析页面 localStorage: %w", err)
+ }
}
+ pageStorageRegistry[target] = storage
return storage, nil
}
@@ -470,13 +487,10 @@ func parseGDPProfile(body []byte) (gdpProfile, error) {
return gdpProfile{member: field(0) == "1" || field(0) == "true", offers: len(offers), claimable: field(3) != "null"}, nil
}
-// gdpTourDelay 是导航栏额度入口出现后额度引导显示并记录展示的延迟
-const gdpTourDelay = 500 * time.Millisecond
-
// billingTargetingFeature 是官网以 EvaluateTargeting 查询结算账号时的固定功能字段
const billingTargetingFeature = `[2,[2,3,4]]`
-// loadGDPCredits 按官网导航栏处理 Google Developer Program 权益响应:已加入且有可兑换额度、或未加入但可领取额度时读取结算账号,再以 EvaluateTargeting 查询各结算账号;额度入口出现时记录入口展示,gdpTourDelay 后记录额度引导展示
+// loadGDPCredits 按官网导航栏处理 Google Developer Program 权益响应:已加入且有可兑换额度、或未加入但可领取额度时读取结算账号,再以 EvaluateTargeting 查询各结算账号
func (runtime *goWAARuntime) loadGDPCredits(ctx context.Context, apiKey string, visitID string, extension string, body []byte) {
profile, err := parseGDPProfile(body)
if err != nil {
@@ -484,33 +498,12 @@ func (runtime *goWAARuntime) loadGDPCredits(ctx context.Context, apiKey string,
}
flags := runtime.pageFlags
claim := flags.gdpClaim && !profile.member && profile.claimable
- var group sync.WaitGroup
if claim || profile.member && profile.offers > 0 {
- group.Go(func() {
- accounts := runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{{"ListBillingAccounts", "[]"}})[0]
- if targeting := billingTargetingBody(accounts); flags.billingTargeting && targeting != "" {
- runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{{"EvaluateTargeting", targeting}})
- }
- })
- }
- if claim || flags.gdpClaim && profile.offers > 0 {
- group.Go(func() {
- runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{gdpImpression("AccountSwitcherRedeemCreditsButton")})
- })
- group.Go(func() {
- pauseContext(ctx, gdpTourDelay)
- if ctx.Err() != nil {
- return
- }
- runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{gdpImpression("RedeemCreditsTourActionButton")})
- })
+ accounts := runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{{"ListBillingAccounts", "[]"}})[0]
+ if targeting := billingTargetingBody(accounts); flags.billingTargeting && targeting != "" {
+ runtime.sendPageRPCs(ctx, apiKey, visitID, extension, []pageRPC{{"EvaluateTargeting", targeting}})
+ }
}
- group.Wait()
-}
-
-// gdpImpression 返回记录额度入口展示的 LogGdpInteractionEvents 请求
-func gdpImpression(element string) pageRPC {
- return pageRPC{"LogGdpInteractionEvents", `[["ENTRY_POINT","impression","` + element + `"]]`}
}
// billingTargetingBody 按 ListBillingAccounts 响应中结算账号的顺序返回 EvaluateTargeting 正文,账号名去掉 billingAccounts/ 前缀;没有结算账号时为空
@@ -558,7 +551,7 @@ func pauseContext(ctx context.Context, duration time.Duration) {
}
}
-// requestStartup 按 offsets 在 pageStarted 之后分组发出 pageStartupRPCs,同组请求同时发出;GetUserPreferences 返回后关闭 preferencesReady,第二个 GenerateAccessToken 返回后关闭 tokenReady,全部返回后关闭 startupDone
+// requestStartup 按 offsets 在 pageStarted 之后分组发出 pageStartupRPCs,同组请求同时发出;GetUserPreferences 返回后关闭 preferencesReady,GenerateAccessToken 返回后关闭 tokenReady,全部返回后关闭 startupDone
func (runtime *goWAARuntime) requestStartup(ctx context.Context, apiKey string, visitID string, pageStarted time.Time, offsets [5]time.Duration) {
runtime.startupDone, runtime.preferencesReady, runtime.tokenReady = make(chan struct{}), make(chan struct{}), make(chan struct{})
started := runtime.startBackground(ctx, func(bg context.Context) {
@@ -679,13 +672,17 @@ func (runtime *goWAARuntime) acknowledgeMedia(ctx context.Context, confirmed tim
})
}
-// uploaded 在服务上传完附件后像官网输入框显示附件一样立即经 drive.count 由页面为每个附件同时发出只含该文件的 CountTokens,不等响应,记下读取附件的 drive
+// uploaded 在服务上传完附件后像官网输入框显示附件一样立即经 drive.count 由页面为每个附件同时发出只含该文件的 CountTokens,不等响应;按官网实测仅对非图片 Drive 文件记录以供发送后读取缩略图(本地图片在前端已有本地预览,官网不调 Drive files.get)
func (runtime *goWAARuntime) uploaded(ctx context.Context, files []FileRef, drive pageDrive) {
model := runtime.elements.pageModel()
for _, file := range files {
body, _ := json.Marshal([]any{model, nil, []any{model, []any{[]any{[]any{[]any{nil, nil, nil, nil, nil, []string{file.ID}}}, "user"}}}})
runtime.countChip(ctx, body, drive.count)
- runtime.attachedFiles.Store(file.ID, drive)
+ if strings.HasPrefix(strings.ToLower(file.MIME), "image/") {
+ runtime.elements.recordImageFile(file.ID)
+ } else {
+ runtime.attachedFiles.Store(file.ID, drive)
+ }
}
}
@@ -763,7 +760,7 @@ func (runtime *goWAARuntime) rejectCookieBar(ctx context.Context) error {
return err
}
headers := corsHeaders(auditRecordURL)
- headers.Del("Priority")
+ headers.Set("Priority", "u=0")
headers.Set("X-Goog-Api-Key", key)
headers.Set("Content-Type", "application/json+protobuf")
headers.Set("X-User-Agent", "grpc-web-javascript/0.1")
@@ -772,7 +769,16 @@ func (runtime *goWAARuntime) rejectCookieBar(ctx context.Context) error {
if err != nil {
return err
}
- return runtime.storage.set(cookieBarStorageKey, string(encoded))
+ if err := runtime.storage.set(cookieBarStorageKey, string(encoded)); err != nil {
+ return err
+ }
+ runtime.vmMu.Lock()
+ vm := runtime.vm
+ runtime.vmMu.Unlock()
+ if vm != nil {
+ _ = vm.SetLocalStorage(ctx, cookieBarStorageKey, string(encoded))
+ }
+ return nil
}
// auditRecordBody 返回 Cookie 提示条拒绝选择的审计记录:base64 编码的 protobuf,含选择、提示条文案与站点名、记录 UUID
diff --git a/internal/aistudio/page_catalog.go b/internal/aistudio/page_catalog.go
index 90d72aff..abf9b438 100644
--- a/internal/aistudio/page_catalog.go
+++ b/internal/aistudio/page_catalog.go
@@ -43,6 +43,7 @@ func (c *Client) ApplyPageCatalog(ctx context.Context, accountID string, page ca
catalog.bundle = page.Bundle
c.setBenefitTier(accountID, tier)
c.setModelCatalog(accountID, catalog)
+ c.assistants.setBuildAgencyFlag(accountID, page.BuildAgency)
return tier, cloneModels(catalog.models), nil
}
diff --git a/internal/aistudio/page_elements.go b/internal/aistudio/page_elements.go
index 7dd0acc6..7331c1d1 100644
--- a/internal/aistudio/page_elements.go
+++ b/internal/aistudio/page_elements.go
@@ -16,7 +16,6 @@ import (
"strings"
"sync"
"time"
- "unicode/utf8"
"github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative"
"github.com/Mag1cFall/AIStudio2API/internal/waa/mozjs"
@@ -58,6 +57,10 @@ const (
veLevel = 334163
// veInsert 是输入框旁插入图片、视频、音频与文件的按钮
veInsert = 225926
+ // veImageBlock、veImageOverlay、veImageAction 是对话中渲染图片附件块时曝光的一组 VE(253131 与 253133 跟踪可见性,253132 不跟踪)
+ veImageBlock = 253131
+ veImageAction = 253132
+ veImageOverlay = 253133
)
// systemDetail 是系统指令卡片在对话页的元素参数
@@ -111,114 +114,20 @@ type veData struct {
// MarshalJSON 按官网页面的键序编码附加数据
func (data veData) MarshalJSON() ([]byte, error) {
- return data.appendJSON(nil), nil
-}
-
-// appendJSON 把按官网页面键序编码的附加数据追加到 dst
-func (data veData) appendJSON(dst []byte) []byte {
- start := len(dst)
- dst = append(dst, '{')
- key := func(name string) {
- if len(dst) > start+1 {
- dst = append(dst, ',')
- }
- dst = append(dst, `"`+name+`":`...)
- }
+ wire := struct {
+ At [][1]int64 `json:"126,omitempty"`
+ Page any `json:"340,omitempty"`
+ Shown [][1]int64 `json:"618,omitempty"`
+ Detail any `json:"1174,omitempty"`
+ }{Page: data.page, Detail: data.detail}
if data.at != 0 {
- key("126")
- dst = append(strconv.AppendInt(append(dst, "[["...), data.at, 10), "]]"...)
- }
- if data.page != nil {
- key("340")
- dst = appendScriptJSON(dst, data.page)
+ wire.At = [][1]int64{{data.at}}
}
if data.shown != 0 {
- key("618")
- dst = append(strconv.AppendInt(append(dst, "[["...), data.shown, 10), "]]"...)
- }
- if data.detail != nil {
- key("1174")
- dst = appendScriptJSON(dst, data.detail)
- }
- return append(dst, '}')
-}
-
-// appendScriptJSON 把 value 按 scriptJSON 的编码追加到 dst:界面元素事件中的 nil、整数、字符串、数组与附加数据直接追加,其余类型经 scriptJSON 编码
-func appendScriptJSON(dst []byte, value any) []byte {
- switch value := value.(type) {
- case nil:
- return append(dst, "null"...)
- case int:
- return strconv.AppendInt(dst, int64(value), 10)
- case int64:
- return strconv.AppendInt(dst, value, 10)
- case string:
- return appendScriptString(dst, value)
- case []any:
- dst = append(dst, '[')
- for index, item := range value {
- if index > 0 {
- dst = append(dst, ',')
- }
- dst = appendScriptJSON(dst, item)
- }
- return append(dst, ']')
- case veData:
- return value.appendJSON(dst)
- default:
- encoded, _ := scriptJSON(value)
- return append(dst, encoded...)
- }
-}
-
-// appendScriptString 把 text 按 encoding/json 不转义 HTML 字符时的规则编码为 JSON 字符串追加到 dst
-func appendScriptString(dst []byte, text string) []byte {
- const hex = "0123456789abcdef"
- dst = append(dst, '"')
- start := 0
- for index := 0; index < len(text); {
- if b := text[index]; b < utf8.RuneSelf {
- if b >= 0x20 && b != '"' && b != '\\' {
- index++
- continue
- }
- dst = append(dst, text[start:index]...)
- switch b {
- case '"', '\\':
- dst = append(dst, '\\', b)
- case '\b':
- dst = append(dst, '\\', 'b')
- case '\f':
- dst = append(dst, '\\', 'f')
- case '\n':
- dst = append(dst, '\\', 'n')
- case '\r':
- dst = append(dst, '\\', 'r')
- case '\t':
- dst = append(dst, '\\', 't')
- default:
- dst = append(dst, '\\', 'u', '0', '0', hex[b>>4], hex[b&0xf])
- }
- index++
- start = index
- continue
- }
- r, size := utf8.DecodeRuneInString(text[index:])
- if r == utf8.RuneError && size == 1 {
- dst = append(append(dst, text[start:index]...), "\ufffd"...)
- index += size
- start = index
- continue
- }
- if r == '\u2028' || r == '\u2029' {
- dst = append(append(dst, text[start:index]...), '\\', 'u', '2', '0', '2', hex[r&0xf])
- index += size
- start = index
- continue
- }
- index += size
+ wire.Shown = [][1]int64{{data.shown}}
}
- return append(append(dst, text[start:]...), '"')
+ encoded, err := scriptJSON(wire)
+ return []byte(encoded), err
}
// starterSeries 是 starterModule 中一个模型系列的入门卡片,models 为官网判断页面模型属于该系列的名单
@@ -442,13 +351,13 @@ type pageElements struct {
listScroll float64
// viewport 与 width 是页面视口的高度与宽度
viewport, width float64
- // thoughtsRendered 表示本页已渲染过思考面板
- thoughtsRendered bool
// answers 是本页已完成的回答数
answers int
// chips 是上次点击 Run 之后输入框中附件的 CountTokens,还没有时为 nil
chips *pageChips
pending *pageTurn
+ // imageFiles 是本页经 Drive 上传的图片附件文件 ID 集合,供渲染回答占位时区分图片与非图片附件
+ imageFiles map[string]bool
// scanned 是 VE 记录器上一次扫描曝光元素的时刻,scanQueued 表示节流窗口结束时还有一次扫描
scanned time.Time
scanQueued bool
@@ -466,8 +375,6 @@ const (
pageRenderMain
// pageRenderCards 是入门卡片
pageRenderCards
- // pageRenderThoughts 是回答中的思考面板
- pageRenderThoughts
)
// rendered 在页面某部分渲染时请求其中的资源;调用方持有 mu
@@ -480,7 +387,7 @@ func (log *pageElements) rendered(part pageRenderPart, images []string) {
// newPageElements 建立页面载入的界面元素日志:window 为浏览器窗口 ID,experiments 为页面 WIZ 数据的实验 ID
func newPageElements(send func(clearcutShape, []byte), locale string, zone *time.Location, experiments []int64, window string, language string, model string) *pageElements {
return &pageElements{
- send: send, locale: locale, zone: zone, model: model, exposed: map[int]int{}, rows: map[string]int{},
+ send: send, locale: locale, zone: zone, model: model, exposed: map[int]int{}, rows: map[string]int{}, width: chatColumn + chatSides,
context: []any{nil, nil, nil, nil, experiments, pageElementsPath, window, nil, language, nil, pageElementsHost, uuid.NewString()},
}
}
@@ -523,7 +430,9 @@ func (log *pageElements) record(at time.Time, body func(seq int) []any) int {
head := append(strconv.AppendInt([]byte{'['}, now.UnixMilli(), 10), ",null,null,null,null,null,null,"...)
tail := strconv.AppendInt([]byte(",null,null,null,null,null,null,"), int64(-offset), 10)
tail = strconv.AppendInt(append(tail, ",null,null,null,null,null,"...), int64(log.seq), 10)
- tail = append(appendScriptString(append(tail, ",null,null,"...), string(appendScriptJSON(nil, body(log.seq)))), ']')
+ encodedBody, _ := scriptJSON(body(log.seq))
+ encodedLiteral, _ := scriptJSON(encodedBody)
+ tail = append(append(append(tail, ",null,null,"...), encodedLiteral...), ']')
log.batch = append(log.batch, encodedEvent{head: head, context: log.contextJSON, tail: tail})
if log.timer == nil {
log.due = now.Add(pageElementsDelay)
@@ -941,8 +850,11 @@ type pageTurn struct {
// chips 是这一轮输入框中附件的 CountTokens,没有附件时为 nil
chips *pageChips
closed time.Time
- // attachments 是最后一个 user 轮次的附件数,每个附件在对话中是单独一段
- attachments int
+ // answeredScheduled 表示本轮已安排记录回答结束,避免并发重复记录
+ answeredScheduled bool
+ // attachments 是最后一个 user 轮次的附件数,每个附件在对话中是单独一段;imageAttachments 是其中的图片附件数
+ attachments int
+ imageAttachments int
// thoughts 表示回答中出现了思考 Part
thoughts bool
// stopped 表示 Rerun 换成 Stop 的按钮已安排曝光,回答结束时 Run 按钮随之重新曝光
@@ -995,9 +907,73 @@ func (log *pageElements) turn(body []byte, counting bool) *pageTurn {
}
turn.counting = counting
turn.attachments = camoufoxnative.GenerateAttachments(body)
+ turn.imageAttachments = log.countLastUserImageAttachments(contents)
return turn
}
+// recordImageFile 记录经 Drive 上传的图片附件文件 ID,供随后这一轮对话渲染图片附件块 VE
+func (log *pageElements) recordImageFile(id string) {
+ log.mu.Lock()
+ if log.imageFiles == nil {
+ log.imageFiles = map[string]bool{}
+ }
+ log.imageFiles[id] = true
+ log.mu.Unlock()
+}
+
+// countLastUserImageAttachments 统计最后一个 user 轮次中图片附件数(内联 image/* 或已登记的 Drive 图片文件);调用方持有 mu
+func (log *pageElements) countLastUserImageAttachments(contents []json.RawMessage) int {
+ if len(contents) == 0 {
+ return 0
+ }
+ last, ok := wireArray(contents[len(contents)-1])
+ if !ok || len(last) == 0 {
+ return 0
+ }
+ var role string
+ if len(last) > 1 && json.Unmarshal(last[1], &role) == nil && role != "" && role != "user" {
+ return 0
+ }
+ parts, ok := wireArray(last[0])
+ if !ok {
+ return 0
+ }
+ count := 0
+ for _, rawPart := range parts {
+ part, ok := wireArray(rawPart)
+ if !ok {
+ continue
+ }
+ if len(part) > 2 {
+ if inline, ok := wireArray(part[2]); ok && len(inline) > 0 {
+ var mime string
+ if json.Unmarshal(inline[0], &mime) == nil && strings.HasPrefix(strings.ToLower(mime), "image/") {
+ count++
+ continue
+ }
+ }
+ }
+ if len(part) > 5 && len(log.imageFiles) > 0 {
+ if ref, ok := wireArray(part[5]); ok && len(ref) > 0 {
+ var fileID string
+ if json.Unmarshal(ref[0], &fileID) == nil && log.imageFiles[fileID] {
+ count++
+ }
+ }
+ }
+ }
+ return count
+}
+
+// showImageAttachments 按官网对话轮含图片附件时的顺序曝光每个图片附件块(253131 tracked、253133 tracked、253132 untracked);调用方持有 mu
+func (turn *pageTurn) showImageAttachments(shown time.Time) {
+ for range turn.imageAttachments {
+ turn.log.shown(veImageBlock, shown, nil, true)
+ turn.log.shown(veImageOverlay, shown, nil, true)
+ turn.log.shown(veImageAction, shown, nil, false)
+ }
+}
+
// changed 安排页面内容在 at 时刻变化(对话区重新布局并滚动):VE 记录器按节流扫描,show 在这次扫描完成的时刻曝光新渲染的元素,show 为 nil 时只推进节流;调用方持有 mu
func (log *pageElements) changed(at time.Time, show func(shown time.Time)) {
log.later(at, func() {
@@ -1034,6 +1010,7 @@ func (turn *pageTurn) started() {
log.shown(veChunkOptions, shown, nil, false)
}
if together {
+ turn.showImageAttachments(shown)
log.shown(243616, shown, nil, true)
}
if turn.scrolled {
@@ -1050,6 +1027,7 @@ func (turn *pageTurn) started() {
placeholder = scanFrame(log.scan(tracked))
log.later(placeholder, func() {
if !together {
+ turn.showImageAttachments(placeholder)
log.shown(243616, placeholder, nil, true)
}
})
@@ -1063,11 +1041,7 @@ func (turn *pageTurn) thought(at time.Time) {
defer log.mu.Unlock()
turn.thoughts = true
turn.change(at, func(shown time.Time) {
- log.shown(veThoughts, shown, append(make([]any, 18), []any{1, 2}), false)
- if !log.thoughtsRendered {
- log.thoughtsRendered = true
- log.rendered(pageRenderThoughts, nil)
- }
+ log.shown(veThoughts, shown, append(make([]any, 20), []any{2, nil, 0, 0}), false)
})
if turn.attachments > 0 && !turn.rerun && !turn.scrolled {
turn.scrolled = true
@@ -1146,17 +1120,18 @@ func (turn *pageTurn) grew(at time.Time, text string) {
// 官网对话区的排版,单位为 CSS 像素
// chatLine 是正文行高,chatTurn 是一轮正文之外的高度,chatThoughts 是模型轮次收起的思考面板
-// chatChrome 是视口中顶栏与输入框占去的高度,chatColumn 是对话列的最大宽度
+// chatChrome 是视口中顶栏与输入框占去的高度,chatColumn 与 chatMinColumn 是对话列的最大与最小宽度
// chatSides 是视口宽度中导航栏与运行设置面板,chatPadding 是一轮正文两侧的内边距,chatFont 是正文字号
const (
- chatLine = 20
- chatTurn = 30
- chatThoughts = 40
- chatChrome = 182
- chatColumn = 1000
- chatSides = 600
- chatPadding = 48
- chatFont = 14
+ chatLine = 20
+ chatTurn = 30
+ chatThoughts = 40
+ chatChrome = 182
+ chatColumn = 1000
+ chatMinColumn = 220
+ chatSides = 600
+ chatPadding = 48
+ chatFont = 14
)
// chatLines 返回 text 在对话区按正文字号与行宽折行的行数,每个换行另起一行;CJK 字符按全角宽度计
@@ -1164,7 +1139,7 @@ func (log *pageElements) chatLines(text string) int {
if text == "" {
return 0
}
- column := min(chatColumn, log.width-chatSides) - chatPadding
+ column := max(chatMinColumn, min(chatColumn, log.width-chatSides)-chatPadding)
lines := 0
for line := range strings.SplitSeq(text, "\n") {
width := 0.0
@@ -1282,11 +1257,8 @@ func (turn *pageTurn) done(at time.Time) {
return
}
turn.closed = at
- ready := turn.ready()
+ turn.scheduleAnswered()
log.mu.Unlock()
- if ready {
- turn.answered()
- }
}
// count 记录伴随的 CountTokens 在 at 时刻完成、统计出 tokens 个 token,正文已关闭且附件的 CountTokens 都已返回时随即安排回答结束
@@ -1295,11 +1267,8 @@ func (turn *pageTurn) count(at time.Time, tokens int) {
log.mu.Lock()
turn.counted = at
turn.prompted = tokens
- ready := turn.ready()
+ turn.scheduleAnswered()
log.mu.Unlock()
- if ready {
- turn.answered()
- }
}
// ready 判断回答结束所需的统计都已到齐:正文已关闭,伴随的 CountTokens 与输入框中附件的 CountTokens 都已返回;调用方持有 mu
@@ -1337,16 +1306,19 @@ func (log *pageElements) chipCounting() func(tokens int) {
chips.tokens += tokens
chips.counted = time.Now()
turn := chips.turn
- ready := turn != nil && turn.ready()
- log.mu.Unlock()
- if ready {
- turn.answered()
+ if turn != nil {
+ turn.scheduleAnswered()
}
+ log.mu.Unlock()
}
}
-// answered 在正文关闭后 44–49 ms、伴随的 CountTokens 与附件的 CountTokens 完成后 4 ms 中最晚的时刻记录回答结束,参数为页面 token 统计在这一轮增加的输入与输出 token 数:输入为伴随 CountTokens 统计的输入框与各附件的 token 数之和,输出为可见输出,显示了思考面板时再加思考
-func (turn *pageTurn) answered() {
+// scheduleAnswered 在正文关闭后 44–49 ms、伴随的 CountTokens 与附件的 CountTokens 完成后 4 ms 中最晚的时刻记录回答结束,参数为页面 token 统计在这一轮增加的输入与输出 token 数:输入为伴随 CountTokens 统计的输入框与各附件的 token 数之和,输出为可见输出,显示了思考面板时再加思考;调用方持有 log.mu
+func (turn *pageTurn) scheduleAnswered() {
+ if turn.answeredScheduled || !turn.ready() {
+ return
+ }
+ turn.answeredScheduled = true
at := turn.closed.Add(time.Duration(44+rand.IntN(6)) * time.Millisecond)
if counted := turn.counted.Add(4 * time.Millisecond); counted.After(at) {
at = counted
@@ -1358,13 +1330,14 @@ func (turn *pageTurn) answered() {
at = counted
}
}
+ model := turn.model
log := turn.log
log.after(at, func() {
output := turn.output
if turn.thoughts {
output = turn.total - turn.input
}
- log.pageEvent(veAnswered, at, []any{nil, nil, nil, nil, nil, nil, nil, nil, []any{input, output, nil, turn.model}})
+ log.pageEvent(veAnswered, at, []any{nil, nil, nil, nil, nil, nil, nil, nil, []any{input, output, nil, model}})
})
}
@@ -1398,7 +1371,7 @@ func (log *pageElements) close() {
// 官网对话区中界面元素的 VE 编号
const (
// veThoughts 是回答中的思考面板
- veThoughts = 334158
+ veThoughts = 339191
// veScrollbar 是对话区的滚动条
veScrollbar = 273488
// veChunkOptions 是对话中每段内容的更多选项按钮
diff --git a/internal/aistudio/page_resources.go b/internal/aistudio/page_resources.go
index 6b87683d..69b8c0a4 100644
--- a/internal/aistudio/page_resources.go
+++ b/internal/aistudio/page_resources.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
+ "log/slog"
"math"
"net/http"
"net/url"
@@ -327,7 +328,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.ConsentOptional && notes.Gapi == "" && notes.GapiProxy == "" && notes.Tags == nil
+ return notes.Loader == nil && !notes.LoaderMissing && notes.Starters == nil && notes.Fonts == nil && notes.AuditKey == "" && notes.Consent == "" && !notes.ConsentOptional && notes.Gapi == "" && notes.GapiProxy == "" && notes.Tags == nil
}
// noteReader 返回从该资源正文读出缓存内容的函数,不需要读正文的资源返回 nil
@@ -336,7 +337,11 @@ func noteReader(address *url.URL) func([]byte) (pageCacheNotes, error) {
case camoufoxnative.FrontendBundle(address):
return func(body []byte) (pageCacheNotes, error) {
position, err := scriptLoaderPosition(body)
- return pageCacheNotes{Loader: &position}, err
+ if err != nil {
+ slog.Warn("AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位", "url", address.String(), "error", err)
+ return pageCacheNotes{LoaderMissing: true}, nil
+ }
+ return pageCacheNotes{Loader: &position}, nil
}
case strings.HasSuffix(address.Path, "/m="+starterModule):
return func(body []byte) (pageCacheNotes, error) {
@@ -449,7 +454,9 @@ type pageCache struct {
// pageCacheEntry 是一个子资源最近一次响应的缓存元数据
type pageCacheEntry struct {
// Received 是收到响应的时刻
- Received time.Time `json:"received"`
+ Received time.Time `json:"received"`
+ // LastUsed 是最近一次命中或写入缓存的时刻,条目数超限时按它淘汰最久未用的
+ LastUsed time.Time `json:"lastUsed,omitempty"`
Date string `json:"date,omitempty"`
Age string `json:"age,omitempty"`
CacheControl string `json:"cacheControl,omitempty"`
@@ -462,6 +469,8 @@ type pageCacheEntry struct {
type pageCacheNotes struct {
// Loader 是前端主程序中脚本加载调用的位置
Loader *sourcePosition `json:"loader,omitempty"`
+ // LoaderMissing 表示已解析过前端主程序但未找到脚本加载调用,避免每次冷启动重复下载主程序
+ LoaderMissing bool `json:"loaderMissing,omitempty"`
// Starters 是入门卡片模块中各模型系列的入门卡片
Starters []starterSeries `json:"starters,omitempty"`
// Fonts 是 Google Fonts 样式表中拉丁字符子集的字体地址,按字体族名索引
@@ -496,16 +505,17 @@ func loadPageCache(storageStatePath string) (*pageCache, error) {
return cache, nil
}
-// lookup 返回地址的缓存条目,以及它在 now 时刻按 max-age 是否仍新鲜
+// lookup 返回地址的缓存条目,以及它在 now 时刻按 max-age 是否仍新鲜;新鲜命中时在内存记录 LastUsed,随下次 store 落盘
func (cache *pageCache) lookup(target string, now time.Time) (pageCacheEntry, bool) {
cache.mu.Lock()
entry, ok := cache.entries[target]
- cache.mu.Unlock()
if !ok {
+ cache.mu.Unlock()
return entry, false
}
maxAge, cacheable := cacheMaxAge(entry.CacheControl)
if !cacheable {
+ cache.mu.Unlock()
return entry, false
}
age := time.Duration(0)
@@ -515,7 +525,13 @@ func (cache *pageCache) lookup(target string, now time.Time) (pageCacheEntry, bo
if seconds, err := strconv.Atoi(entry.Age); err == nil {
age = max(age, time.Duration(seconds)*time.Second)
}
- return entry, age+now.Sub(entry.Received) < maxAge
+ fresh := age+now.Sub(entry.Received) < maxAge
+ if fresh {
+ entry.LastUsed = now
+ cache.entries[target] = entry
+ }
+ cache.mu.Unlock()
+ return entry, fresh
}
// loader 返回前端主程序缓存条目中脚本加载调用的位置
@@ -536,7 +552,10 @@ func (cache *pageCache) starters(target string) []starterSeries {
return cache.entries[target].Starters
}
-// store 按响应更新地址的缓存条目并写回文件:304 刷新新鲜度,200 替换条目并记下从正文读出的内容,no-store 删除条目
+// pageCacheMaxEntries 是 spidermonkey-cache.json 保留的最大缓存条目数,超出时淘汰最久未用的条目
+const pageCacheMaxEntries = 64
+
+// store 按响应更新地址的缓存条目并写回文件:304 刷新新鲜度,200 替换条目并记下从正文读出的内容,no-store 删除条目;条目数超过 pageCacheMaxEntries 时先淘汰最久未用的条目
func (cache *pageCache) store(target string, response *http.Response, received time.Time, notes pageCacheNotes) error {
cache.mu.Lock()
defer cache.mu.Unlock()
@@ -545,7 +564,7 @@ func (cache *pageCache) store(target string, response *http.Response, received t
if response.StatusCode == http.StatusOK {
entry = pageCacheEntry{LastModified: header.Get("Last-Modified"), ETag: header.Get("ETag"), pageCacheNotes: notes}
}
- entry.Received, entry.Date, entry.Age = received, header.Get("Date"), header.Get("Age")
+ entry.Received, entry.LastUsed, entry.Date, entry.Age = received, received, header.Get("Date"), header.Get("Age")
if value := header.Get("Cache-Control"); value != "" || response.StatusCode == http.StatusOK {
entry.CacheControl = value
}
@@ -554,6 +573,7 @@ func (cache *pageCache) store(target string, response *http.Response, received t
} else {
cache.entries[target] = entry
}
+ cache.pruneLocked(target)
data, err := json.Marshal(cache.entries)
if err != nil {
return err
@@ -561,6 +581,41 @@ func (cache *pageCache) store(target string, response *http.Response, received t
return atomicWriteExistingDirFile(cache.path, data, 0o600)
}
+// pruneLocked 在条目数超过 pageCacheMaxEntries 时按 LastUsed(缺失时取 Received)从最久未用开始删除,保留刚写入的 keep;调用方持有 mu
+func (cache *pageCache) pruneLocked(keep string) {
+ if len(cache.entries) <= pageCacheMaxEntries {
+ return
+ }
+ type aged struct {
+ address string
+ used time.Time
+ }
+ list := make([]aged, 0, len(cache.entries))
+ for address, entry := range cache.entries {
+ if address == keep {
+ continue
+ }
+ used := entry.LastUsed
+ if used.IsZero() {
+ used = entry.Received
+ }
+ list = append(list, aged{address: address, used: used})
+ }
+ slices.SortFunc(list, func(a, b aged) int {
+ if a.used.Before(b.used) {
+ return -1
+ }
+ if a.used.After(b.used) {
+ return 1
+ }
+ return strings.Compare(a.address, b.address)
+ })
+ excess := len(cache.entries) - pageCacheMaxEntries
+ for index := 0; index < excess && index < len(list); index++ {
+ delete(cache.entries, list[index].address)
+ }
+}
+
// cacheMaxAge 返回 Cache-Control 的 max-age,no-cache、no-store 或没有 max-age 时不可直接使用缓存
func cacheMaxAge(value string) (time.Duration, bool) {
maxAge, found := time.Duration(0), false
diff --git a/internal/aistudio/page_survey.go b/internal/aistudio/page_survey.go
index 00e1cee7..7151e1b4 100644
--- a/internal/aistudio/page_survey.go
+++ b/internal/aistudio/page_survey.go
@@ -115,10 +115,14 @@ func (runtime *goWAARuntime) surveyEnded(completed bool) {
}
if !survey.model {
surveys.trigger(survey.id)
- go runtime.requestSurvey(survey.id)
+ id := survey.id
+ runtime.startBackground(nil, func(bg context.Context) {
+ runtime.requestSurvey(bg, id)
+ })
return
}
var timer *time.Timer
+ id := survey.id
timer = time.AfterFunc(surveyModelDelay, func() {
surveys.mu.Lock()
defer surveys.mu.Unlock()
@@ -126,8 +130,10 @@ func (runtime *goWAARuntime) surveyEnded(completed bool) {
return
}
surveys.timer = nil
- surveys.trigger(survey.id)
- go runtime.requestSurvey(survey.id)
+ surveys.trigger(id)
+ runtime.startBackground(nil, func(bg context.Context) {
+ runtime.requestSurvey(bg, id)
+ })
})
surveys.timer = timer
return
@@ -142,11 +148,14 @@ func (surveys *pageSurveys) trigger(id string) {
surveys.triggered[id] = true
}
-// requestSurvey 像页面的反馈服务一样请求问卷 id:约 25 ms 后开始,本页第一次请求时先载入问卷代理 iframe;读取问卷启动配置,配置开启问卷时请求问卷;失败不影响页面
-func (runtime *goWAARuntime) requestSurvey(id string) {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+// requestSurvey 像页面的反馈服务一样请求问卷 id:约 25 ms 后开始,本页第一次请求时先载入问卷代理 iframe;读取问卷启动配置,配置开启问卷时请求问卷;失败或页面关闭时中止,不影响页面
+func (runtime *goWAARuntime) requestSurvey(parent context.Context, id string) {
+ ctx, cancel := context.WithTimeout(parent, 30*time.Second)
defer cancel()
- time.Sleep(time.Duration(20+rand.IntN(15)) * time.Millisecond)
+ pauseContext(ctx, time.Duration(20+rand.IntN(15))*time.Millisecond)
+ if ctx.Err() != nil {
+ return
+ }
surveys := &runtime.surveys
surveys.frame.Do(func() {
frame, err := runtime.loadSurveyFrame(ctx)
@@ -162,7 +171,7 @@ func (runtime *goWAARuntime) requestSurvey(id string) {
if err != nil || !surveyEnabled(config) {
return
}
- _, _ = runtime.surveyRPC(ctx, surveys.framed, "trigger", runtime.headers.Get("x-goog-api-key"), surveyTriggerBody(id, time.Now().In(runtime.location())))
+ _, _ = runtime.surveyRPC(ctx, surveys.framed, "trigger", runtime.headers.Get("x-goog-api-key"), surveyTriggerBodyForLang(id, runtime.pageLang, time.Now().In(runtime.location())))
}
// loadSurveyFrame 以 iframe 导航载入 feedback-pa 的 gapi 代理页,再按代理页的顺序载入 googleapis.proxy.js 与其中的代理模块,返回代理页地址
@@ -242,14 +251,18 @@ func surveyEnabled(config []byte) bool {
return value == "1" || value == "true"
}
-// surveyTriggerBody 返回请求问卷 id 的 JSPB 正文:触发上下文为问卷 ID 与语言,客户端上下文为 at 所在时区相对 UTC 的秒数(为 0 时不写)与问卷库的平台、支持的问卷形式和版本
-func surveyTriggerBody(id string, at time.Time) string {
+// surveyTriggerBodyForLang 返回请求问卷 id 的 JSPB 正文:触发上下文为问卷 ID 与页面文档语言(为空时回退 surveyLanguage),客户端上下文为 at 所在时区相对 UTC 的秒数(为 0 时不写)与问卷库的平台、支持的问卷形式和版本
+func surveyTriggerBodyForLang(id string, lang string, at time.Time) string {
+ if lang == "" {
+ lang = surveyLanguage
+ }
_, offset := at.Zone()
timezone := "[]"
if offset != 0 {
timezone = "[" + strconv.Itoa(offset) + "]"
}
- return `[["` + id + `",["` + surveyLanguage + `"]],[[null,null,` + timezone + `],[1,null,[1,2],` + strconv.Itoa(surveyLibraryVersion) + `]]]`
+ encodedLang, _ := json.Marshal(lang)
+ return `[["` + id + `",[` + string(encodedLang) + `]],[[null,null,` + timezone + `],[1,null,[1,2],` + strconv.Itoa(surveyLibraryVersion) + `]]]`
}
// gapiProxyExtensions 返回 googleapis.proxy.js 配置中声明的 le 列表,以逗号相连;代理页按地址中的 jsh 载入代理模块时不带脚本末尾追加的扩展
diff --git a/internal/aistudio/page_tabs.go b/internal/aistudio/page_tabs.go
index 48d5c0fb..728ee8d5 100644
--- a/internal/aistudio/page_tabs.go
+++ b/internal/aistudio/page_tabs.go
@@ -256,12 +256,20 @@ func (worker *NativeWorker) deferOnPage(ctx context.Context, lease *AccountLease
}
}
-// pageForRPC 非阻塞返回发送页面伴随 RPC 使用的页面:租约已持有页面时返回该页面,否则直接返回当前主页面,不等待也不新开页面
+// pageForRPC 非阻塞返回发送页面伴随 RPC 使用的页面:租约已持有页面时返回该页面,上下文不带租约而带共享调用发起请求的页面时返回该页面,否则直接返回当前主页面,不等待也不新开页面
func (worker *NativeWorker) pageForRPC(ctx context.Context) workerRuntime {
- lease, ok := AccountLeaseFromContext(ctx)
- if !ok {
- return worker.current()
+ if lease, ok := AccountLeaseFromContext(ctx); ok {
+ if page := worker.heldPage(lease); page != nil {
+ return page
+ }
+ } else if page, ok := flightPageFromContext(ctx); ok {
+ return page
}
+ return worker.current()
+}
+
+// heldPage 返回 lease 已持有的页面,没有时返回 nil
+func (worker *NativeWorker) heldPage(lease *AccountLease) workerRuntime {
worker.tabsMu.Lock()
var held *pageTab
for _, tab := range worker.tabs {
@@ -271,10 +279,10 @@ func (worker *NativeWorker) pageForRPC(ctx context.Context) workerRuntime {
}
}
worker.tabsMu.Unlock()
- if held != nil {
- return worker.tabPage(held)
+ if held == nil {
+ return nil
}
- return worker.current()
+ return worker.tabPage(held)
}
// notifyTabs 唤醒等待页面空出或新开结束的请求;调用方持有 tabsMu
diff --git a/internal/aistudio/page_telemetry.go b/internal/aistudio/page_telemetry.go
index acbf7e9d..e4213644 100644
--- a/internal/aistudio/page_telemetry.go
+++ b/internal/aistudio/page_telemetry.go
@@ -66,17 +66,23 @@ func (runtime *goWAARuntime) sendClearcut(shape clearcutShape, body []byte) {
runtime.elementsMu.Unlock()
}
class := requestClass{anonymous: shape == clearcutPlain}
- go func() {
+ unloading := runtime.unloading.Load()
+ started := runtime.startTelemetrySend(unloading, func(ctx context.Context) {
if done != nil {
defer close(done)
}
if previous != nil {
- <-previous
+ select {
+ case <-previous:
+ case <-ctx.Done():
+ return
+ }
}
- ctx, cancel := context.WithTimeout(withRequestClass(context.Background(), class), time.Minute)
- defer cancel()
- runtime.drain(runtime.do(ctx, http.MethodPost, target, body, headers))
- }()
+ runtime.drain(runtime.do(withRequestClass(ctx, class), http.MethodPost, target, body, headers))
+ })
+ if !started && done != nil {
+ close(done)
+ }
}
// clearcutClient 返回官网页面上报正文的客户端信息,label 为前端构建标签或客户端版本,kind 为日志客户端类别
@@ -159,9 +165,12 @@ func (report cspReport) body(script string) (string, []byte, error) {
return target, []byte(encoded), err
}
-// sendScriptReport 像 Firefox 一样以不带凭据的匿名请求发出解释器脚本的 CSP 违规报告,报告的策略与地址已在页面载入时校验
+// sendScriptReport 像 Firefox 一样以不带凭据的匿名请求发出解释器脚本的 CSP 违规报告;策略缺失或校验失败时跳过不发送
func (runtime *goWAARuntime) sendScriptReport(script string) {
- target, body, _ := runtime.scriptReport.body(script)
+ target, body, err := runtime.scriptReport.body(script)
+ if err != nil || target == "" {
+ return
+ }
headers := http.Header{}
headers.Set("Accept", "*/*")
headers.Set("Content-Type", "application/csp-report")
@@ -170,11 +179,11 @@ func (runtime *goWAARuntime) sendScriptReport(script string) {
headers.Set("Sec-Fetch-Mode", "no-cors")
headers.Set("Sec-Fetch-Site", "same-origin")
headers.Set("Priority", "u=4")
- go func() {
- ctx, cancel := context.WithTimeout(withRequestClass(context.Background(), requestClass{anonymous: true}), time.Minute)
+ runtime.startBackground(nil, func(bg context.Context) {
+ ctx, cancel := context.WithTimeout(withRequestClass(bg, requestClass{anonymous: true}), time.Minute)
defer cancel()
runtime.drain(runtime.do(ctx, http.MethodPost, target, body, headers))
- }()
+ })
}
// pageTelemetry 是官网页面 WIZ 数据中 clearcut 上报用到的值
diff --git a/internal/aistudio/page_vitals.go b/internal/aistudio/page_vitals.go
index 54174eec..9918b5a3 100644
--- a/internal/aistudio/page_vitals.go
+++ b/internal/aistudio/page_vitals.go
@@ -19,10 +19,18 @@ const (
pageApplication = "alkali-makersuite"
// pageRoute 是官网新对话页的路由
pageRoute = "prompts/new_chat"
- // pageLCPSelector 是官网新对话页最大内容绘制元素的选择器
+ // pageLCPSelector 是官网新对话页显示 Cookie 提示条时最大内容绘制元素的选择器
pageLCPSelector = "#glue-cookie-notification-bar-1>p.glue-cookie-notification-bar__text"
+ // pageMessageLCPSelector 是官网新对话页没有 Cookie 提示条时最大内容绘制元素的选择器
+ pageMessageLCPSelector = "div.main-content-container>div.incognito-container.ng-star-inserted>p.message"
)
+// pageVitalsState 描述本次页面载入的可见状态与资源缓存命中情况
+type pageVitalsState struct {
+ cookieBar bool
+ warmCache bool
+}
+
// pageRouteTimes 是官网会话现场中点 New chat 后路由切换的耗时(毫秒)
var pageRouteTimes = []int{10, 19, 36, 210}
@@ -58,23 +66,32 @@ func navigationInt(navigation map[string]any, name string) int {
return value
}
-// newPageVitals 按 BotGuard 读取的同一份导航计时建立页面载入的 web vitals 上报并安排发送;首次内容绘制取 DOMContentLoaded 到 load 之间官网现场所在的区段,最大内容绘制为同时出现的 Cookie 提示文字,资源统计按官网现场的类别与耗时范围抽样
-func newPageVitals(send func(clearcutShape, []byte), telemetry pageTelemetry, locale string, zone *time.Location, origin time.Time, navigation map[string]any, path string) *pageVitals {
+// newPageVitalsState 按 BotGuard 读取的同一份导航计时建立页面载入的 web vitals 上报并安排发送:state.cookieBar 为假时最大内容绘制元素是主体消息文字,state.warmCache 为真时资源耗时取缓存命中的范围;首次内容绘制取 DOMContentLoaded 到 load 之间官网现场所在的区段,资源统计按官网现场的类别与耗时范围抽样
+func newPageVitalsState(send func(clearcutShape, []byte), telemetry pageTelemetry, locale string, zone *time.Location, origin time.Time, navigation map[string]any, path string, state pageVitalsState) *pageVitals {
nav := func(name string) int { return navigationInt(navigation, name) }
interactive, complete := nav("domInteractive"), nav("domComplete")
paint := interactive + int(float64(complete-interactive)*(0.15+0.35*rand.Float64()))
firstByte := nav("responseStart")
lookup, connect, connected := nav("domainLookupStart"), nav("connectStart"), nav("connectEnd")
+ selector := pageMessageLCPSelector
+ if state.cookieBar {
+ selector = pageLCPSelector
+ }
+ scripts := 20 + rand.IntN(6)
+ resources := []any{1, 200 + rand.IntN(100), nil, nil, 9 + rand.IntN(2), 800 + rand.IntN(150), 6, 1300 + rand.IntN(1600), scripts, 1400 + rand.IntN(250)}
+ if state.warmCache {
+ resources = []any{1, 20 + rand.IntN(60), nil, nil, 10 + rand.IntN(2), 20 + rand.IntN(120), 6, 30 + rand.IntN(180), scripts, 60 + rand.IntN(320)}
+ }
payload := make([]any, 18)
payload[4] = []any{nil, nil, "aistudio.google.com", pageApplication + "-" + pageRoute, pageApplication, path, nil, 3, pageVitalsID(time.Now()), telemetry.bundle, 1}
payload[7] = []any{1, nav("startTime"), nav("fetchStart"), lookup, nav("domainLookupEnd"), connect, connected, nav("requestStart"), firstByte, nav("responseEnd"), interactive, complete, nav("loadEventStart"), nav("loadEventEnd")}
payload[8] = []any{nil, paint, nil, paint, firstByte}
- payload[9] = []any{1, 200 + rand.IntN(100), nil, nil, 9 + rand.IntN(2), 800 + rand.IntN(150), 6, 1300 + rand.IntN(1600), 8 + rand.IntN(2), 1400 + rand.IntN(250)}
+ payload[9] = resources
payload[10] = []any{nil, paint}
payload[12] = []any{[]any{[]any{"", pageRoute, 1100 + rand.IntN(500)}}}
payload[13] = []any{
nil, []any{paint, firstByte, paint - firstByte}, nil,
- []any{paint, pageLCPSelector, nil, firstByte, 0, 0, paint - firstByte},
+ []any{paint, selector, nil, firstByte, 0, 0, paint - firstByte},
[]any{firstByte, lookup, connect - lookup, connected - connect, firstByte - connected},
}
payload[17] = telemetry.sampling
@@ -98,6 +115,23 @@ func pageVitalsID(now time.Time) string {
return string(prefix) + string(fraction)
}
+// setCookieBar 在载入记录发出前按 Cookie 提示条是否显示更新它的最大内容绘制选择器;vitals 为 nil 时不做任何事
+func (vitals *pageVitals) setCookieBar(visible bool) {
+ if vitals == nil {
+ return
+ }
+ vitals.mu.Lock()
+ defer vitals.mu.Unlock()
+ if vitals.closed || !vitals.loaded {
+ return
+ }
+ selector := pageMessageLCPSelector
+ if visible {
+ selector = pageLCPSelector
+ }
+ vitals.payload[13].([]any)[3].([]any)[1] = selector
+}
+
// tick 发出积攒的记录并安排下一次,周期由上一次发出后起算
func (vitals *pageVitals) tick() {
vitals.mu.Lock()
diff --git a/internal/aistudio/request.go b/internal/aistudio/request.go
index e38694ac..9c55388c 100644
--- a/internal/aistudio/request.go
+++ b/internal/aistudio/request.go
@@ -3,12 +3,10 @@ package aistudio
import (
"cmp"
"context"
- "encoding/base64"
"encoding/json"
"fmt"
"io"
"slices"
- "strconv"
"strings"
)
@@ -200,11 +198,12 @@ func encodeContents(contents []Content) ([]any, error) {
return nil, err
}
wire := make([]any, 0, len(linked))
+ mediaIndex := 0
for index, content := range linked {
if len(content.Parts) == 0 {
continue
}
- encoded, err := encodeContent(content)
+ encoded, err := encodeContent(content, &mediaIndex)
if err != nil {
return nil, fmt.Errorf("编码 content %d: %w", index, err)
}
@@ -277,7 +276,8 @@ func linkFunctionResults(content Content, pendingCalls *[]FunctionCall) (Content
return content, nil
}
-func encodeContent(content Content) ([]any, error) {
+// encodeContent 编码一条对话轮,mediaIndex 是请求内各轮内联附件的累计序号
+func encodeContent(content Content, mediaIndex *int) ([]any, error) {
role := ""
switch content.Role {
case RoleUser:
@@ -291,6 +291,12 @@ func encodeContent(content Content) ([]any, error) {
}
parts := make([]any, 0, len(content.Parts))
for index, part := range content.Parts {
+ if part.InlineData != nil {
+ *mediaIndex++
+ if content.Role == RoleUser && part.DisplayName == "" {
+ part.DisplayName = fmt.Sprintf("inline-media-%d", *mediaIndex)
+ }
+ }
encoded, err := encodePart(part)
if err != nil {
return nil, fmt.Errorf("编码 part %d: %w", index, err)
@@ -360,7 +366,12 @@ func encodePart(part Part) ([]any, error) {
if part.InlineData.MIME == "" || len(part.InlineData.Data) == 0 {
return nil, fmt.Errorf("inline data 缺少 MIME 或数据")
}
- wire := []any{nil, nil, []any{part.InlineData.MIME, base64.StdEncoding.EncodeToString(part.InlineData.Data)}}
+ blob := []any{part.InlineData.MIME, part.InlineData.Data}
+ if part.DisplayName != "" {
+ // Blob field 6 为文件显示名,与官网内联附件的 CountTokens / GenerateContent 一致
+ blob = append(blob, nil, nil, nil, part.DisplayName)
+ }
+ wire := []any{nil, nil, blob}
return encodeVideoPart(wire, part)
}
if part.ExternalMedia != nil {
@@ -385,7 +396,7 @@ func encodePart(part Part) ([]any, error) {
if upload := part.Upload; upload != nil {
// Part field 18 上传附件:MIME、上传路径、文件名、字节数
wire := make([]any, 18)
- wire[17] = []any{upload.MIME, upload.Path, upload.Name, strconv.FormatInt(upload.Size, 10)}
+ wire[17] = []any{upload.MIME, upload.Path, upload.Name, upload.Size}
return encodeVideoPart(wire, part)
}
if part.FunctionCall != nil {
diff --git a/internal/aistudio/runtime_go.go b/internal/aistudio/runtime_go.go
index cb079947..268bd2c7 100644
--- a/internal/aistudio/runtime_go.go
+++ b/internal/aistudio/runtime_go.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/base64"
+ "encoding/binary"
"encoding/json"
"errors"
"fmt"
@@ -17,6 +18,7 @@ import (
"path/filepath"
"regexp"
"slices"
+ "sort"
"strconv"
"strings"
"sync"
@@ -126,9 +128,11 @@ type goWAARuntime struct {
clientDetails string
// cookieBarLanguage 是 Cookie 提示条按文档 lang 选出的文案语言
cookieBarLanguage string
+ // pageLang 是页面文档 属性,用于 HaTS 问卷触发语言
+ pageLang string
// storage 是页面写入、随账户保存的 localStorage 项
storage *pageStorage
- // startupDone 在页面启动请求全部返回后关闭;preferencesReady 在其中 GetUserPreferences 返回、preferences 记下响应正文后关闭;tokenReady 在第二个 GenerateAccessToken 返回、accessToken 记下 Drive access token 与取得时刻 tokenAt 后关闭;cookieBarDone 在本次启动的 2a.json 请求结束后关闭
+ // startupDone 在页面启动请求全部返回后关闭;preferencesReady 在其中 GetUserPreferences 返回、preferences 记下响应正文后关闭;tokenReady 在 GenerateAccessToken 返回、accessToken 记下 Drive access token 与取得时刻 tokenAt 后关闭;cookieBarDone 在本次启动的 2a.json 请求结束后关闭
startupDone chan struct{}
preferencesReady chan struct{}
tokenReady chan struct{}
@@ -146,11 +150,13 @@ type goWAARuntime struct {
// surveys 是页面在回答结束后请求 HaTS 问卷的状态
surveys pageSurveys
// bgMu 保护页面后台任务的取消上下文、关闭状态与登记计数,Close 时取消并等待所有后台页面活动结束
- bgMu sync.Mutex
- bgCtx context.Context
- bgCancel context.CancelFunc
- bgClosed bool
- bgGroup sync.WaitGroup
+ bgMu sync.Mutex
+ bgCtx context.Context
+ bgCancel context.CancelFunc
+ bgClosed bool
+ bgGroup sync.WaitGroup
+ telemetryGroup sync.WaitGroup
+ unloading atomic.Bool
}
// startBackground 在页面生命周期内启动后台任务,继承 parent 中的值但不随 parent 取消,页面已关闭时不启动并返回 false,Close 时取消并等待结束
@@ -197,7 +203,40 @@ func (runtime *goWAARuntime) afterBackground(parent context.Context, delay time.
})
}
-// closeBackground 标记页面后台已关闭、取消后台上下文并等待已启动的后台任务结束
+// startTelemetrySend 在页面生命周期或卸载窗口内异步发送一次遥测请求:普通阶段受 bgCtx 取消控制,卸载阶段给予 5 秒收尾窗口;均由 telemetryGroup 追踪,Close 返回前等待退出,页面后台已关闭时不发送并返回 false
+func (runtime *goWAARuntime) startTelemetrySend(unloading bool, run func(context.Context)) bool {
+ runtime.bgMu.Lock()
+ if runtime.bgClosed {
+ runtime.bgMu.Unlock()
+ return false
+ }
+ if unloading {
+ runtime.telemetryGroup.Add(1)
+ runtime.bgMu.Unlock()
+ go func() {
+ defer runtime.telemetryGroup.Done()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ run(ctx)
+ }()
+ return true
+ }
+ if runtime.bgCtx == nil {
+ runtime.bgCtx, runtime.bgCancel = context.WithCancel(context.Background())
+ }
+ pageCtx := runtime.bgCtx
+ runtime.telemetryGroup.Add(1)
+ runtime.bgMu.Unlock()
+ go func() {
+ defer runtime.telemetryGroup.Done()
+ ctx, cancel := context.WithTimeout(pageCtx, time.Minute)
+ defer cancel()
+ run(ctx)
+ }()
+ return true
+}
+
+// closeBackground 标记页面后台已关闭、取消后台上下文并等待已启动的后台任务与遥测收尾结束
func (runtime *goWAARuntime) closeBackground() {
runtime.bgMu.Lock()
runtime.bgClosed = true
@@ -207,6 +246,7 @@ func (runtime *goWAARuntime) closeBackground() {
cancel()
}
runtime.bgGroup.Wait()
+ runtime.telemetryGroup.Wait()
}
// vmRefreshTimeout 是后台重建 VM 的期限
@@ -231,16 +271,16 @@ var pageCatalogStartupRPCs = []pageRPC{
{"ListModels", "[]"},
}
-// pageStartupRPCs 是官网页面启动时与 GetLoggingContext、Waa/Create、权益和模型目录请求先后发出的其余请求,按发出先后分为三组:GetUserPreferences 与第一个 GenerateAccessToken、第二个 GenerateAccessToken、ListIncidentsHistory 与 ListPromos
+// pageStartupRPCs 是官网页面启动时与 GetLoggingContext、Waa/Create、权益和模型目录请求先后发出的其余请求,按发出先后分为三组:GetUserPreferences、GenerateAccessToken(每页 1 次)、ListIncidentsHistory 与 ListPromos
var pageStartupRPCs = [][]pageRPC{
- {{"GetUserPreferences", "[]"}, {"GenerateAccessToken", `["users/me"]`}},
+ {{"GetUserPreferences", "[]"}},
{{"GenerateAccessToken", `["users/me"]`}},
{incidentsRPC, {"ListPromos", "[]"}},
}
// pageStartupTimes 是官网页面载入中各组启动请求在 GetLoggingContext 之后的发出时刻
// 单位为毫秒;每行是一次预检已缓存的官网载入,共四次
-// 各列依次为 GetUserPreferences 与第一个 GenerateAccessToken、Waa/Create、第二个 GenerateAccessToken、
+// 各列依次为 GetUserPreferences、Waa/Create、GenerateAccessToken、
// ListIncidentsHistory 与 ListPromos、GetAiStudioBenefitTier 与 ListModels
var pageStartupTimes = [][5]int{{49, 119, 124, 125, 150}, {25, 36, 40, 61, 85}, {40, 53, 71, 95, 120}, {26, 38, 53, 74, 95}}
@@ -282,12 +322,20 @@ type pageFlags struct {
billingTargeting bool
// loggingContextMaxAge 为页面数据 NHyHAe:localStorage 中上一次 GetLoggingContext 结果的有效毫秒数,0 时不使用
loggingContextMaxAge int64
+ // buildAgency 为 TSDtV 中标志 45831005 的取值(nil 表示缺失或非布尔),按官方结构解析
+ buildAgency *bool
}
// parsePageFlags 读取官网页面内联数据中的构建开关
func parsePageFlags(body []byte) pageFlags {
enabled := func(id string) bool { return bytes.Contains(body, []byte("["+id+",null,true,")) }
- flags := pageFlags{gdpProfile: enabled("45806340"), plusBenefit: enabled("45777963"), gdpClaim: enabled("45854328"), billingTargeting: enabled("45822819")}
+ flags := pageFlags{
+ gdpProfile: enabled("45806340"),
+ plusBenefit: enabled("45777963"),
+ gdpClaim: enabled("45854328"),
+ billingTargeting: enabled("45822819"),
+ buildAgency: camoufoxnative.BuildAgencyFromHTML(body),
+ }
if match := loggingContextMaxAgePattern.FindSubmatch(body); match != nil {
flags.loggingContextMaxAge, _ = strconv.ParseInt(string(match[1]), 10, 64)
}
@@ -379,42 +427,51 @@ func newGoWAAHTTPClient(proxyURL string) (*http.Client, error) {
}
// NewSpiderMonkeyWorker 启动单个账户的 SpiderMonkey WAA runtime
+// 进入 StartupBootstrappingWAA 阶段时页面已载入完成而 WAA 尚未就绪,此时 Worker 登记到页面注册表并调用 options.PageReady,页面 RPC 与 Drive 上传可用,取 proof 要等 WAA 就绪
func NewSpiderMonkeyWorker(ctx context.Context, accountID string, options camoufoxnative.Options) (*NativeWorker, error) {
if accountID == "" {
return nil, fmt.Errorf("缺少账户 ID")
}
- runtime, err := newGoWAARuntime(ctx, options)
+ if options.Model == "" {
+ return nil, errors.New("WAA bootstrap 缺少实时目录聊天模型")
+ }
+ var worker *NativeWorker
+ progress := options.StartupProgress
+ options.StartupProgress = func(stage camoufoxnative.StartupStage) {
+ if stage == camoufoxnative.StartupBootstrappingWAA {
+ pageWorkers.Store(accountID, worker)
+ if options.PageReady != nil {
+ options.PageReady()
+ }
+ }
+ if progress != nil {
+ progress(stage)
+ }
+ }
+ reportGoStartup(options, camoufoxnative.StartupPreparingBrowser)
+ runtime, fingerprint, err := newGoPageRuntime(options)
if err != nil {
return nil, err
}
- worker := &NativeWorker{
+ worker = &NativeWorker{
accountID: accountID,
runtime: runtime,
state: WorkerState{
AccountID: accountID,
- Phase: WorkerReady,
+ Phase: WorkerBusy,
PID: os.Getpid(),
RuntimeID: "spidermonkey-waa",
- PageURL: runtime.pageURL,
},
}
- pageWorkers.Store(accountID, worker)
- return worker, nil
-}
-
-func newGoWAARuntime(ctx context.Context, options camoufoxnative.Options) (*goWAARuntime, error) {
- if options.Model == "" {
- return nil, errors.New("WAA bootstrap 缺少实时目录聊天模型")
- }
- reportGoStartup(options, camoufoxnative.StartupPreparingBrowser)
- runtime, fingerprint, err := newGoPageRuntime(options)
- if err != nil {
- return nil, err
- }
if err := runtime.open(ctx, fingerprint); err != nil {
+ pageWorkers.CompareAndDelete(accountID, worker)
return nil, err
}
- return runtime, nil
+ worker.stateMu.Lock()
+ worker.state.PageURL = runtime.pageURL
+ worker.stateMu.Unlock()
+ worker.setPhase(WorkerReady)
+ return worker, nil
}
// Reload 以同一 HTTP 客户端与账户 Cookie 按官网冷启动重新载入页面,返回新页面的 runtime
@@ -426,6 +483,7 @@ func (runtime *goWAARuntime) Reload(ctx context.Context) (workerRuntime, error)
return nil, err
}
next.windowID = runtime.windowID
+ next.storage = runtime.storage
next.previous = runtime
if err := next.open(ctx, fingerprint); err != nil {
return nil, err
@@ -456,8 +514,10 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
runtime.profile.LocalStorage[item.Name] = item.Value
}
}
- if runtime.storage, err = loadPageStorage(options.StorageStatePath); err != nil {
- return err
+ if runtime.storage == nil {
+ if runtime.storage, err = loadPageStorage(options.StorageStatePath); err != nil {
+ return err
+ }
}
maps.Copy(runtime.profile.LocalStorage, runtime.storage.snapshot())
appVersion, _ := fingerprint["navigator.appVersion"].(string)
@@ -475,17 +535,26 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
}
runtime.uiLocale = uiLocale(document.frontendBundle())
runtime.cookieBarLanguage = cookieBarLanguage(document.lang)
+ runtime.pageLang = strings.TrimSpace(document.lang)
runtime.serviceStreamz = runtime.newStreamz(nil)
page, err := url.Parse(runtime.pageURL)
if err != nil {
return err
}
+ _, warmCache := runtime.pageCache.lookup(document.frontendBundle(), time.Now())
if err := runtime.loadDocumentResources(ctx, document); err != nil {
return err
}
documentTiming(runtime.profile.Navigation, time.Since(runtime.profile.NavigationStart))
+ _, cookieDecided := runtime.profile.LocalStorage[cookieBarStorageKey]
+ consentOptional := runtime.pageCache.notes(cookieBarConfigURL(runtime.cookieBarLanguage)).ConsentOptional
+ if runtime.telemetry.label != "" {
+ runtime.vitals = newPageVitalsState(runtime.sendClearcut, runtime.telemetry, runtime.uiLocale, runtime.location(), runtime.profile.NavigationStart, runtime.profile.Navigation, page.Path, pageVitalsState{
+ cookieBar: !cookieDecided && !consentOptional,
+ warmCache: warmCache,
+ })
+ }
runtime.startBackground(ctx, runtime.loadPageScripts)
- runtime.vitals = newPageVitals(runtime.sendClearcut, runtime.telemetry, runtime.uiLocale, runtime.location(), runtime.profile.NavigationStart, runtime.profile.Navigation, page.Path)
if runtime.windowID == "" {
runtime.windowID = pageWindowID()
}
@@ -496,16 +565,17 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
runtime.loadRenderedResources(ctx, document, part, images)
}
runtime.elements.load(runtime.profile.NavigationStart.Add(time.Duration(navigationInt(runtime.profile.Navigation, "domInteractive")) * time.Millisecond))
- dependency, module, err := starterModuleURLs(document)
- if err != nil {
- return err
+ if dependency, module, err := starterModuleURLs(document); err != nil {
+ slog.Warn("AI Studio 页面缺少入门卡片模块,跳过预载", "error", err)
+ } else {
+ runtime.startBackground(ctx, func(bg context.Context) {
+ runtime.loadStarters(bg, dependency, module)
+ })
}
- runtime.startBackground(ctx, func(bg context.Context) {
- runtime.loadStarters(bg, dependency, module)
- })
if runtime.scriptReport.policy != "" {
if runtime.scriptReport.loader, err = runtime.pageCache.loader(runtime.scriptReport.bundle); err != nil {
- return err
+ slog.Warn("AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告", "error", err)
+ runtime.scriptReport.policy = ""
}
}
runtime.loadPageIcons(ctx, document)
@@ -557,6 +627,12 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
catalogDone <- bodies
}()
runtime.requestStartup(ctx, apiKey, visitID, pageStarted, offsets)
+ runtime.startBackground(ctx, func(bg context.Context) {
+ if !closedBefore(bg, runtime.tokenReady) {
+ return
+ }
+ runtime.sendFollowupRPCs(bg, apiKey, visitID, loggedExtension())
+ })
type startedVM struct {
vm *waa.Runtime
err error
@@ -583,10 +659,11 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
}
extension := logging.extension
runtime.pageCatalog = camoufoxnative.PageCatalog{
- Logging: logging.body,
- Tier: catalog[0],
- Models: catalog[1],
- Bundle: document.frontendBundle(),
+ Logging: logging.body,
+ Tier: catalog[0],
+ Models: catalog[1],
+ Bundle: document.frontendBundle(),
+ BuildAgency: runtime.pageFlags.buildAgency,
}
tier, _ := decodeBenefitTier(catalog[0])
runtime.elements.catalog(catalogAt, tier.HeaderValue(), parseCatalogModels(catalog[1]))
@@ -600,12 +677,6 @@ func (runtime *goWAARuntime) open(ctx context.Context, fingerprint map[string]an
runtime.headers.Set("x-goog-ext-519733851-bin", extension)
}
reportGoStartup(options, camoufoxnative.StartupBootstrappingWAA)
- runtime.startBackground(ctx, func(bg context.Context) {
- if !closedBefore(bg, runtime.startupDone) {
- return
- }
- runtime.sendFollowupRPCs(bg, apiKey, visitID, extension)
- })
started := <-vmDone
if started.err != nil {
return started.err
@@ -704,7 +775,7 @@ func profileFromFingerprint(config map[string]any) (waa.Profile, string, string)
}
acceptLanguage, _ := config["headers.Accept-Language"].(string)
if acceptLanguage == "" {
- acceptLanguage = "en-US,en;q=0.5"
+ acceptLanguage = "en-US,en;q=0.9"
}
return profile, userAgent, acceptLanguage
}
@@ -722,10 +793,51 @@ func numberValue(value any) (float64, bool) {
return 0, false
}
-// sessionCookies 是 SpiderMonkey runtime 的账户 Cookie 状态
+// gaSessionState 是已授予分析同意(gcs=G111)时单个 GA4 目标在同账户多标签页与重载间复用的会话状态
+type gaSessionState struct {
+ sid int64
+ sct int
+ last time.Time
+}
+
+// sessionCookies 是 SpiderMonkey runtime 的账户 Cookie 与跨页 GA4 会话状态
type sessionCookies struct {
- mu sync.Mutex
- state StorageState
+ mu sync.Mutex
+ state StorageState
+ gaCID string
+ gaSessions map[string]gaSessionState
+}
+
+// analyticsIdentity 返回账户在分析存储已授权(gcs=G111)时某个 GA4 目标的 cid、是否首次访问、sid、sct 与是否新会话
+func (session *sessionCookies) analyticsIdentity(tagID string, now time.Time) (string, bool, int64, int, bool) {
+ session.mu.Lock()
+ defer session.mu.Unlock()
+ firstVisit := session.gaCID == ""
+ if firstVisit {
+ session.gaCID = strconv.FormatUint(uint64(rand.Uint32()>>1), 10) + "." + strconv.FormatInt(now.Unix(), 10)
+ }
+ if session.gaSessions == nil {
+ session.gaSessions = map[string]gaSessionState{}
+ }
+ current, ok := session.gaSessions[tagID]
+ if ok && now.Sub(current.last) < analyticsSessionTimeout {
+ current.last = now
+ session.gaSessions[tagID] = current
+ return session.gaCID, firstVisit, current.sid, current.sct, false
+ }
+ next := gaSessionState{sid: now.Unix(), sct: current.sct + 1, last: now}
+ session.gaSessions[tagID] = next
+ return session.gaCID, firstVisit, next.sid, next.sct, true
+}
+
+// touchAnalyticsSession 刷新该 GA4 目标的最近活跃时刻
+func (session *sessionCookies) touchAnalyticsSession(tagID string, now time.Time) {
+ session.mu.Lock()
+ defer session.mu.Unlock()
+ if current, ok := session.gaSessions[tagID]; ok {
+ current.last = now
+ session.gaSessions[tagID] = current
+ }
}
// cookies 返回当前账户 Cookie 状态副本
@@ -898,13 +1010,17 @@ func (runtime *goWAARuntime) loadPage(ctx context.Context) (string, pageDocument
})
runtime.profile.TrustedTypes = requiresTrustedScripts(response.Header.Values("Content-Security-Policy"))
document := parsePageDocument(body, target)
- if runtime.telemetry, err = parsePageTelemetry(body, document.frontendBundle()); err != nil {
- return "", pageDocument{}, err
+ if telemetry, err := parsePageTelemetry(body, document.frontendBundle()); err != nil {
+ slog.Warn("AI Studio 页面遥测数据解析失败,降级继续启动", "error", err)
+ runtime.telemetry = pageTelemetry{}
+ } else {
+ runtime.telemetry = telemetry
}
runtime.scriptReport = cspReport{policy: response.Header.Get("Content-Security-Policy-Report-Only"), document: target, bundle: document.frontendBundle()}
if runtime.scriptReport.policy != "" {
if _, _, err := runtime.scriptReport.body(""); err != nil {
- return "", pageDocument{}, fmt.Errorf("AI Studio 页面 report-only CSP: %w", err)
+ slog.Warn("AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告", "error", err)
+ runtime.scriptReport.policy = ""
}
}
return string(match[1]), document, nil
@@ -1058,11 +1174,7 @@ func encodeJSPBFields(raw []byte) ([]byte, error) {
}
func appendVarint(output []byte, value uint64) []byte {
- for value >= 0x80 {
- output = append(output, byte(value)|0x80)
- value >>= 7
- }
- return append(output, byte(value))
+ return binary.AppendUvarint(output, value)
}
// createChallenge 按官网请求体调用 Waa/Create,刷新时携带已加载解释器 hash 与上一 VM 的 snapshot
@@ -1153,7 +1265,7 @@ func (runtime *goWAARuntime) loadInterpreter(ctx context.Context, challenge waa.
headers.Set("Referer", aiStudioOrigin+"/")
headers.Set("Sec-Fetch-Dest", "script")
headers.Set("Sec-Fetch-Mode", "no-cors")
- headers.Set("Sec-Fetch-Site", "same-site")
+ headers.Set("Sec-Fetch-Site", fetchSite(challenge.InterpreterURL))
if cached != "" && entry.LastModified != "" {
headers.Set("If-Modified-Since", entry.LastModified)
}
@@ -1202,8 +1314,12 @@ func (runtime *goWAARuntime) startVM(ctx context.Context, challenge waa.Challeng
slog.Warn("WAA 解释器版本变化", "previous", runtime.interpreterHash, "current", challenge.InterpreterHash)
}
runtime.interpreterHash, runtime.interpreter = challenge.InterpreterHash, interpreter
- cookie, _ := documentCookie(runtime.cookies())
+ cookie, _ := documentCookieAt(runtime.cookies(), runtime.pageURL, time.Now())
profile := runtime.profile
+ profile.LocalStorage = maps.Clone(runtime.profile.LocalStorage)
+ if runtime.storage != nil {
+ maps.Copy(profile.LocalStorage, runtime.storage.snapshot())
+ }
profile.Document = map[string]any{"cookie": cookie, "lastModified": runtime.pageLoaded.In(runtime.location()).Format("01/02/2006 15:04:05")}
var loaded time.Time
if loadEnd, ok := profile.Navigation["loadEventEnd"].(int); ok {
@@ -1262,6 +1378,8 @@ func (runtime *goWAARuntime) closeVM(vm *waa.Runtime) {
// closeTelemetry 像官网页面卸载一样发出尚未发出的界面元素事件、2584 计数与 GA4 事件,停止页面全部 1828 定时上报与尚未发出的 1957 上报
func (runtime *goWAARuntime) closeTelemetry() {
+ runtime.unloading.Store(true)
+ defer runtime.unloading.Store(false)
if runtime.vitals != nil {
runtime.vitals.close()
}
@@ -1280,14 +1398,44 @@ func (runtime *goWAARuntime) closeTelemetry() {
}
}
-// documentCookie 返回页面脚本可见的非 HttpOnly Cookie 串
+// documentCookie 返回页面脚本在默认路径下可见的非 HttpOnly、未过期、非分区的 Cookie 串
func documentCookie(state StorageState) (string, error) {
- parts := make([]string, 0, len(state.Cookies))
- for _, cookie := range state.Cookies {
- if cookie.HTTPOnly || !cookieDomainMatches(cookie.Domain, "aistudio.google.com") {
+ return documentCookieAt(state, aiStudioOrigin+"/prompts/new_chat", time.Now())
+}
+
+// documentCookieAt 返回 pageURL 页面脚本在 now 时刻可见的非 HttpOnly Cookie 串:过滤已过期、路径不匹配与第三方分区 Cookie,按路径长度降序排列,空值 Cookie 输出为 name=
+func documentCookieAt(state StorageState, pageURL string, now time.Time) (string, error) {
+ target, err := url.Parse(pageURL)
+ if err != nil {
+ return "", err
+ }
+ nowSeconds := float64(now.UnixNano()) / 1e9
+ type candidate struct {
+ cookie StateCookie
+ index int
+ }
+ candidates := make([]candidate, 0, len(state.Cookies))
+ for index, cookie := range state.Cookies {
+ if cookie.HTTPOnly || cookie.PartitionKey != "" {
+ continue
+ }
+ if cookie.Expires >= 0 && cookie.Expires <= nowSeconds {
+ continue
+ }
+ if !cookieDomainMatches(cookie.Domain, target.Hostname()) || !cookiePathMatches(cookie.Path, target.EscapedPath()) {
continue
}
- parts = append(parts, cookie.Name+"="+cookie.Value)
+ candidates = append(candidates, candidate{cookie: cookie, index: index})
+ }
+ sort.SliceStable(candidates, func(left, right int) bool {
+ if len(candidates[left].cookie.Path) == len(candidates[right].cookie.Path) {
+ return candidates[left].index < candidates[right].index
+ }
+ return len(candidates[left].cookie.Path) > len(candidates[right].cookie.Path)
+ })
+ parts := make([]string, 0, len(candidates))
+ for _, item := range candidates {
+ parts = append(parts, item.cookie.Name+"="+item.cookie.Value)
}
return strings.Join(parts, "; "), nil
}
@@ -1301,7 +1449,7 @@ func (runtime *goWAARuntime) loadImage(address string) bool {
headers.Set("Referer", aiStudioOrigin+"/")
headers.Set("Sec-Fetch-Dest", "image")
headers.Set("Sec-Fetch-Mode", "no-cors")
- headers.Set("Sec-Fetch-Site", "same-origin")
+ headers.Set("Sec-Fetch-Site", fetchSite(address))
headers.Set("Priority", "u=5, i")
response, err := runtime.do(ctx, http.MethodGet, address, nil, headers)
if err != nil {
@@ -1479,7 +1627,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 len(contents) > 0 && camoufoxnative.StartsNewChat(runtime.chat, contents) {
newChat = runtime.newChat
}
proof, err = vm.RunProofAfter(ctx, digest, prompt, newChat, settings, pickedPause)
@@ -1496,10 +1644,12 @@ func (runtime *goWAARuntime) proof(ctx context.Context, digest string, prompt st
}
switch {
case run || rerun:
- runtime.running = vm
- runtime.elements.press(runtime.pointer.Clicked(), rerun)
- if run {
- runtime.analytics.clicked(runtime.pointer.Clicked())
+ if len(contents) > 0 || rerun {
+ runtime.running = vm
+ runtime.elements.press(runtime.pointer.Clicked(), rerun)
+ if run {
+ runtime.analytics.clicked(runtime.pointer.Clicked())
+ }
}
case input == proofSubmit:
runtime.running = vm
diff --git a/internal/aistudio/runtime_native.go b/internal/aistudio/runtime_native.go
index 0daaeb3a..d661d303 100644
--- a/internal/aistudio/runtime_native.go
+++ b/internal/aistudio/runtime_native.go
@@ -211,11 +211,16 @@ func (worker *NativeWorker) Prepare(ctx context.Context, request ProtectedReques
}
_, rerun := ctx.Value(pageRerunKey{}).(int)
generate := strings.HasSuffix(request.URL, "/GenerateContent")
+ assistantGen := strings.HasSuffix(request.URL, "/StreamRunAgentTask") || strings.HasSuffix(request.URL, "/CodeAssistantOffline")
result, submit := "", false
if generate && request.PagePrompt == "" && !rerun {
result, submit = wireFunctionResult(request.Body)
}
- proof, page, headers, err = worker.proofAndHeaders(gesture, proofDigest(request), request.PagePrompt, request.Body, generate && (request.PagePrompt != "" || rerun), result, submit)
+ runBody := request.Body
+ if assistantGen {
+ runBody = nil
+ }
+ proof, page, headers, err = worker.proofAndHeaders(gesture, proofDigest(request), request.PagePrompt, runBody, (generate && (request.PagePrompt != "" || rerun)) || (assistantGen && request.PagePrompt != ""), result, submit)
} else {
headers, err = worker.current().ProtocolHeaders(ctx)
}
@@ -348,8 +353,16 @@ func stringEnd(body []byte, from int) (int, bool) {
return 0, false
}
-// pageCountTokensDelay 是官网页面在 GenerateContent 发出后统计用户轮次 token 的时延
-const pageCountTokensDelay = 2200 * time.Millisecond
+// pageCountTokensDelayMin 是官网页面在 GenerateContent 发出后统计用户轮次 token 的最短时延,实际按官网实测在 [1970, 2150] ms 内抽样
+const (
+ pageCountTokensDelayMin = 1970 * time.Millisecond
+ pageCountTokensDelaySpan = 180 * time.Millisecond
+)
+
+// pageCountTokensDelay 返回官网页面伴随 CountTokens 的发出时延
+func pageCountTokensDelay() time.Duration {
+ return pageCountTokensDelayMin + rand.N(pageCountTokensDelaySpan)
+}
// pageSubmitCountDelay 是官网页面提交函数结果、发出 GenerateContent 后统计函数调用与函数结果两轮 token 的最短时延,实际另加不超过 150 ms 的随机值
const pageSubmitCountDelay = 250 * time.Millisecond
@@ -368,7 +381,7 @@ func (worker *NativeWorker) SendProtected(ctx context.Context, request Protected
ctx = withFollowUp(ctx, followUp{URL: makerSuiteRPCURL + "CountTokens", Body: body, Delay: delay})
}
headers := request.Headers
- if strings.HasSuffix(request.URL, "/GenerateContent") {
+ if strings.HasSuffix(request.URL, "/GenerateContent") || strings.HasSuffix(request.URL, "/StreamRunAgentTask") || strings.HasSuffix(request.URL, "/CodeAssistantOffline") {
headers = headers.Clone()
headers.Set("Priority", "u=0")
}
@@ -434,7 +447,7 @@ func countTokensBody(generate ProtectedRequest) ([]byte, time.Duration, bool) {
}
if generate.PagePrompt != "" {
body, err := json.Marshal([]any{model, []any{[]any{[]any{[]any{nil, generate.PagePrompt}}, "user"}}})
- return body, pageCountTokensDelay, err == nil
+ return body, pageCountTokensDelay(), err == nil
}
if _, result := wireFunctionResult(generate.Body); !result {
return nil, 0, false
diff --git a/internal/aistudio/schema.go b/internal/aistudio/schema.go
index fc52b511..5fa45075 100644
--- a/internal/aistudio/schema.go
+++ b/internal/aistudio/schema.go
@@ -871,11 +871,10 @@ func inlineSchemaRefs(raw json.RawMessage) json.RawMessage {
if len(definitions) == 0 {
return raw
}
+ delete(root, "$defs")
+ delete(root, "definitions")
budget := maxSchemaRefExpansions
- resolved := resolveSchemaRefs(root, definitions, nil, &budget).(map[string]any)
- delete(resolved, "$defs")
- delete(resolved, "definitions")
- encoded, _ := json.Marshal(resolved)
+ encoded, _ := json.Marshal(resolveSchemaRefs(root, definitions, nil, &budget))
return encoded
}
diff --git a/internal/aistudio/search_alias.go b/internal/aistudio/search_alias.go
index daf061dd..582fdf2d 100644
--- a/internal/aistudio/search_alias.go
+++ b/internal/aistudio/search_alias.go
@@ -67,7 +67,7 @@ func ModelsWithSearchAliases(models []Model) []Model {
if _, exists := knownIDs[aliasID]; exists {
continue
}
- alias := cloneModels([]Model{model})[0]
+ alias := cloneModel(model)
alias.ID = aliasID
alias.Name = model.Name + " (Search)"
alias.Description = searchAliasDescription(model.Description)
diff --git a/internal/aistudio/service.go b/internal/aistudio/service.go
index b89da782..09482b83 100644
--- a/internal/aistudio/service.go
+++ b/internal/aistudio/service.go
@@ -22,6 +22,7 @@ import (
// RequestOptions 保存单次请求与目录同步可热替换的行为选项
type RequestOptions struct {
BuildNativeNonstream bool
+ BuildChatProtocol string
YouTubeLinks bool
DiscoverHiddenModels bool
StripThoughtSignatures bool
@@ -47,6 +48,9 @@ type PooledService struct {
func (s *PooledService) SetRequestOptions(opts RequestOptions) {
copyOpts := opts
s.options.Store(©Opts)
+ if s.client != nil {
+ s.client.SetBuildChatProtocol(opts.BuildChatProtocol)
+ }
}
// requestOptions 返回当前生效的行为选项快照,未设置时为零值
@@ -339,22 +343,42 @@ func bindingPrompt(request GenerateRequest) (string, error) {
if len(request.Contents) == 0 {
return "", fmt.Errorf("GenerateContent contents 不能为空")
}
- values := make([]string, 0)
+ size, parts := 0, 0
for _, content := range request.Contents {
for _, part := range content.Parts {
+ parts++
switch {
case part.Text != "":
- values = append(values, part.Text)
+ size += len(part.Text)
+ case part.InlineData != nil:
+ size += base64.StdEncoding.EncodedLen(len(part.InlineData.Data))
+ case part.File != nil:
+ size += len(part.File.ID)
+ }
+ }
+ }
+ var binding strings.Builder
+ binding.Grow(size + parts)
+ written := 0
+ for _, content := range request.Contents {
+ for _, part := range content.Parts {
+ if written > 0 {
+ binding.WriteByte(' ')
+ }
+ written++
+ switch {
+ case part.Text != "":
+ binding.WriteString(part.Text)
case part.InlineData != nil:
- values = append(values, base64.StdEncoding.EncodeToString(part.InlineData.Data))
+ encoder := base64.NewEncoder(base64.StdEncoding, &binding)
+ _, _ = encoder.Write(part.InlineData.Data)
+ _ = encoder.Close()
case part.File != nil:
- values = append(values, part.File.ID)
- default:
- values = append(values, "")
+ binding.WriteString(part.File.ID)
}
}
}
- return strings.Join(values, " "), nil
+ return binding.String(), nil
}
// contentsText 返回各 Part 的文本以空格连接,作为写入页面输入框的提示词
@@ -393,11 +417,11 @@ func (s *PooledService) Models(ctx context.Context) ([]Model, error) {
targets = append(targets, status)
}
}
- models := make([]Model, 0)
+ var lists [][]Model
available := 0
var failures GroupedErrors
for _, result := range s.refreshModelCatalogs(ctx, targets) {
- models = mergeModels(models, result.models)
+ lists = append(lists, result.models)
if result.available {
available++
}
@@ -414,7 +438,7 @@ func (s *PooledService) Models(ctx context.Context) ([]Model, error) {
}
return nil, ErrNoEligibleAccount
}
- return models, nil
+ return mergeModels(lists...), nil
}
// RefreshAccountModels 占用指定账户的一个普通槽位刷新其权益与模型目录,不受账户启用、调度状态与冷却限制;reload 为 true 时重新载入账户页面
@@ -603,13 +627,13 @@ func (s *PooledService) verificationGeneration(ctx context.Context, lease *Accou
func (s *PooledService) CachedModels() []Model {
s.pool.mu.Lock()
defer s.pool.mu.Unlock()
- models := make([]Model, 0)
+ lists := make([][]Model, 0, len(s.pool.accounts)+1)
for _, account := range s.pool.accounts {
if account != nil && account.Config.Enabled {
- models = mergeModels(models, account.Models)
+ lists = append(lists, account.Models)
}
}
- return mergeModels(models, s.pool.buildOnlyModelsLocked())
+ return mergeModels(append(lists, s.pool.buildOnlyModelsLocked())...)
}
type accountModelsResult struct {
@@ -619,25 +643,23 @@ type accountModelsResult struct {
err error
}
+// modelCatalogRefreshConcurrency 是同时刷新模型目录的账户数上限
+const modelCatalogRefreshConcurrency = 32
+
+// refreshModelCatalogs 并发刷新各账户的模型目录,结果按 statuses 的顺序排列
func (s *PooledService) refreshModelCatalogs(ctx context.Context, statuses []AccountStatus) []accountModelsResult {
- results := make(chan accountModelsResult, len(statuses))
+ results := make([]accountModelsResult, len(statuses))
+ limit := make(chan struct{}, modelCatalogRefreshConcurrency)
var refreshes sync.WaitGroup
- for _, status := range statuses {
- refreshes.Add(1)
- go func(status AccountStatus) {
- defer refreshes.Done()
- results <- s.modelsForStatus(ctx, status)
- }(status)
- }
- go func() {
- refreshes.Wait()
- close(results)
- }()
- collected := make([]accountModelsResult, 0, len(statuses))
- for result := range results {
- collected = append(collected, result)
+ for index, status := range statuses {
+ limit <- struct{}{}
+ refreshes.Go(func() {
+ defer func() { <-limit }()
+ results[index] = s.modelsForStatus(ctx, status)
+ })
}
- return collected
+ refreshes.Wait()
+ return results
}
func (s *PooledService) modelsForStatus(ctx context.Context, status AccountStatus) accountModelsResult {
@@ -690,7 +712,7 @@ func (l *AccountLease) Model(modelID string) (Model, bool) {
defer l.pool.mu.Unlock()
for _, model := range l.account.Models {
if modelMatchesID(model, modelID) {
- return cloneModels([]Model{model})[0], true
+ return cloneModel(model), true
}
}
return Model{}, false
@@ -1121,47 +1143,53 @@ func forwardEventsWithLease(
}
}
-func mergeModels(base []Model, additions []Model) []Model {
- merged := make(map[string]Model, len(base)+len(additions))
- for _, model := range append(cloneModels(base), cloneModels(additions)...) {
- current, exists := merged[model.ID]
- if !exists {
- merged[model.ID] = model
- continue
- }
- current.Methods = unionOrdered(current.Methods, model.Methods)
- if current.Name == "" {
- current.Name = model.Name
- }
- if current.Description == "" {
- current.Description = model.Description
- }
- current.InputTokenLimit = minimumPositive(current.InputTokenLimit, model.InputTokenLimit)
- current.OutputTokenLimit = minimumPositive(current.OutputTokenLimit, model.OutputTokenLimit)
- if current.Capabilities == nil && len(model.Capabilities) > 0 {
- current.Capabilities = make(map[string]bool, len(model.Capabilities))
- }
- for name, enabled := range model.Capabilities {
- current.Capabilities[name] = current.Capabilities[name] || enabled
- }
- if current.CapabilityOptions == nil && len(model.CapabilityOptions) > 0 {
- current.CapabilityOptions = make(map[string][]string, len(model.CapabilityOptions))
- }
- for name, values := range model.CapabilityOptions {
- current.CapabilityOptions[name] = unionOrdered(current.CapabilityOptions[name], values)
- }
- if len(current.VoiceDetails) == 0 {
- current.VoiceDetails = model.VoiceDetails
- }
- if len(current.Languages) == 0 {
- current.Languages = model.Languages
+// mergeModels 依次合并多个目录,同一 ID 的模型合并方法、能力与选项,顺序按各目录的上游顺序,每个模型只复制一次
+func mergeModels(lists ...[]Model) []Model {
+ merged := make(map[string]Model)
+ for _, models := range lists {
+ for _, model := range models {
+ current, exists := merged[model.ID]
+ if !exists {
+ merged[model.ID] = cloneModel(model)
+ continue
+ }
+ current.Methods = unionOrdered(current.Methods, model.Methods)
+ if current.Name == "" {
+ current.Name = model.Name
+ }
+ if current.Description == "" {
+ current.Description = model.Description
+ }
+ current.InputTokenLimit = minimumPositive(current.InputTokenLimit, model.InputTokenLimit)
+ current.OutputTokenLimit = minimumPositive(current.OutputTokenLimit, model.OutputTokenLimit)
+ if current.Capabilities == nil && len(model.Capabilities) > 0 {
+ current.Capabilities = make(map[string]bool, len(model.Capabilities))
+ }
+ for name, enabled := range model.Capabilities {
+ current.Capabilities[name] = current.Capabilities[name] || enabled
+ }
+ if current.CapabilityOptions == nil && len(model.CapabilityOptions) > 0 {
+ current.CapabilityOptions = make(map[string][]string, len(model.CapabilityOptions))
+ }
+ for name, values := range model.CapabilityOptions {
+ current.CapabilityOptions[name] = unionOrdered(current.CapabilityOptions[name], values)
+ }
+ if len(current.VoiceDetails) == 0 {
+ current.VoiceDetails = model.VoiceDetails
+ }
+ if current.DefaultVoice == "" {
+ current.DefaultVoice = model.DefaultVoice
+ }
+ if len(current.Languages) == 0 {
+ current.Languages = model.Languages
+ }
+ current.AccessModes = unionInt64(current.AccessModes, model.AccessModes)
+ current.Paid = current.Paid || model.Paid
+ merged[model.ID] = current
}
- current.AccessModes = unionInt64(current.AccessModes, model.AccessModes)
- current.Paid = current.Paid || model.Paid
- merged[model.ID] = current
}
result := make([]Model, 0, len(merged))
- for _, id := range upstreamModelOrder(base, additions) {
+ for _, id := range upstreamModelOrder(lists...) {
model := merged[id]
model.Methods = unionOrdered(nil, model.Methods)
result = append(result, model)
@@ -1207,9 +1235,12 @@ func unionInt64(left []int64, right []int64) []int64 {
// unionOrdered 按首次出现的顺序合并两组取值并去重
func unionOrdered(left []string, right []string) []string {
- result := slices.Clone(left)
+ result := left
for _, value := range right {
if !slices.Contains(result, value) {
+ if len(result) == len(left) {
+ result = slices.Clone(left)
+ }
result = append(result, value)
}
}
diff --git a/internal/aistudio/transcription_service.go b/internal/aistudio/transcription_service.go
index 5cb0aac4..4078f6cb 100644
--- a/internal/aistudio/transcription_service.go
+++ b/internal/aistudio/transcription_service.go
@@ -52,14 +52,13 @@ type TranscriptionRequest struct {
// TranscriptionResult 表示完整转录及其上游元数据
type TranscriptionResult struct {
- Text string
- Segments []TranscriptMetadata
- Usage Usage
- FinishReason string
- ProviderModel string
- FirstEvent time.Duration
- FirstContent time.Duration
- accessCheckedAt time.Time
+ Text string
+ Segments []TranscriptMetadata
+ Usage Usage
+ FinishReason string
+ ProviderModel string
+ FirstEvent time.Duration
+ FirstContent time.Duration
}
// TranscriptionService 定义音频转录公开端点所需能力
@@ -103,7 +102,6 @@ func (s *PooledService) Transcribe(ctx context.Context, request TranscriptionReq
checkedAt := lease.CheckedAt()
attempted[accountID] = struct{}{}
result, requestErr = s.transcribeWithLease(ctx, lease, request, startedAt)
- result.accessCheckedAt = checkedAt
var releaseErr error
if owned {
releaseErr = lease.Release()
diff --git a/internal/aistudio/transport_browser.go b/internal/aistudio/transport_browser.go
index 49e6dffd..8711ee5f 100644
--- a/internal/aistudio/transport_browser.go
+++ b/internal/aistudio/transport_browser.go
@@ -160,6 +160,50 @@ var gapiRequestHeaderOrder = []string{
"te",
}
+// uploadStartHeaderOrder 是 Firefox 158 发出官网 /_/upload 可续传上传 start 请求的请求头顺序
+var uploadStartHeaderOrder = []string{
+ "user-agent",
+ "accept",
+ "accept-language",
+ "accept-encoding",
+ "referer",
+ "x-goog-authuser",
+ "x-goog-hash",
+ "x-goog-upload-header-content-length",
+ "x-goog-upload-header-content-type",
+ "x-goog-upload-protocol",
+ "x-goog-upload-command",
+ "content-type",
+ "content-length",
+ "origin",
+ "cookie",
+ "sec-fetch-dest",
+ "sec-fetch-mode",
+ "sec-fetch-site",
+ "te",
+}
+
+// uploadFinalizeHeaderOrder 是 Firefox 158 发出官网 /_/upload 上传 finalize 请求的请求头顺序
+var uploadFinalizeHeaderOrder = []string{
+ "user-agent",
+ "accept",
+ "accept-language",
+ "accept-encoding",
+ "referer",
+ "x-goog-authuser",
+ "content-type",
+ "x-goog-hash",
+ "x-goog-upload-command",
+ "x-goog-upload-offset",
+ "content-length",
+ "origin",
+ "cookie",
+ "sec-fetch-dest",
+ "sec-fetch-mode",
+ "sec-fetch-site",
+ "te",
+}
+
// noStoreFetchHeaderOrder 是 Firefox 158 发出页面脚本以 fetch 的 cache: "no-store" 发出的请求(带 Pragma 与 Cache-Control)的请求头顺序,没有正文的 POST 把 content-length 写在 te 之前
var noStoreFetchHeaderOrder = []string{
"user-agent",
@@ -696,6 +740,10 @@ func (transport *browserRoundTripper) RoundTrip(request *stdhttp.Request) (*stdh
upstream.Host = request.Host
upstream.ContentLength = request.ContentLength
upstream.GetBody = request.GetBody
+ if request.Body == stdhttp.NoBody {
+ upstream.Body = fhttp.NoBody
+ upstream.GetBody = func() (io.ReadCloser, error) { return fhttp.NoBody, nil }
+ }
upstream.Header = make(fhttp.Header, len(request.Header)+2)
for name, values := range request.Header {
upstream.Header[name] = append([]string(nil), values...)
@@ -937,9 +985,15 @@ func requestHeaderOrder(host string) []string {
return order
}
-// orderedHeaderNames 返回按 Firefox 顺序排列的全部请求头名,顺序表之外的头按字母序排在最后;跨源样式表引用的字体在 CORS 加上 origin 之后才写入 referer
+// orderedHeaderNames 返回按 Firefox 顺序排列的全部请求头名,顺序表之外的头按字母序排在最后;可续传上传的 start 与 finalize 请求各用一张顺序表,跨源样式表引用的字体在 CORS 加上 origin 之后才写入 referer
func orderedHeaderNames(headers fhttp.Header, host string) []string {
order := requestHeaderOrder(host)
+ switch headers.Get("X-Goog-Upload-Command") {
+ case "start":
+ order = uploadStartHeaderOrder
+ case "upload, finalize":
+ order = uploadFinalizeHeaderOrder
+ }
if headers.Get("Pragma") != "" {
order = noStoreFetchHeaderOrder
if headers.Get("Content-Type") == "" {
diff --git a/internal/aistudio/transport_http.go b/internal/aistudio/transport_http.go
index 3be83668..eb3eb5d0 100644
--- a/internal/aistudio/transport_http.go
+++ b/internal/aistudio/transport_http.go
@@ -86,15 +86,24 @@ type cachedGapiFingerprint struct {
type accountLeaseContextKey struct{}
type flightAccountContextKey struct{}
+type flightPageContextKey struct{}
type accountSelectionObserverContextKey struct{}
-// contextWithFlightAccount 剥离单个请求的账户租约并注入共享内部调用使用的只读账户指针,避免取消方扣住并发槽位
+// contextWithFlightAccount 剥离单个请求的账户租约并注入共享内部调用使用的只读账户指针,避免取消方扣住并发槽位;该租约此刻已持有页面时同时注入这个页面,共享调用由发起请求的页面发出
func contextWithFlightAccount(ctx context.Context, account *Account) context.Context {
stripped := contextWithoutAccountLease{Context: ctx}
if account == nil {
return stripped
}
- return context.WithValue(stripped, flightAccountContextKey{}, account)
+ flight := context.WithValue(stripped, flightAccountContextKey{}, account)
+ if lease, ok := AccountLeaseFromContext(ctx); ok {
+ if worker := pageWorker(account.ID); worker != nil {
+ if page := worker.heldPage(lease); page != nil {
+ flight = context.WithValue(flight, flightPageContextKey{}, page)
+ }
+ }
+ }
+ return flight
}
// flightAccountFromContext 返回共享内部调用上下文中绑定的只读账户指针
@@ -103,6 +112,12 @@ func flightAccountFromContext(ctx context.Context) (*Account, bool) {
return account, ok
}
+// flightPageFromContext 返回共享内部调用上下文中绑定的发起请求所在的页面
+func flightPageFromContext(ctx context.Context) (workerRuntime, bool) {
+ page, ok := ctx.Value(flightPageContextKey{}).(workerRuntime)
+ return page, ok
+}
+
// residentCatalogContextKey 是 context 中要求账户目录读取在常驻 Worker 的页面上进行的键
type residentCatalogContextKey struct{}
@@ -317,6 +332,7 @@ func (t *MakerSuiteHTTPTransport) UploadAssistantFile(ctx context.Context, accou
return response.Header, raw, nil
}
header, _, err := send(aiStudioOrigin+"/_/upload", http.Header{
+ "Content-Type": {"application/x-www-form-urlencoded;charset=utf-8"},
"X-Goog-Upload-Header-Content-Length": {strconv.Itoa(len(blob.Data))},
"X-Goog-Upload-Header-Content-Type": {blob.MIME},
"X-Goog-Hash": {hash},
diff --git a/internal/aistudio/types.go b/internal/aistudio/types.go
index d9bcc879..e7950a00 100644
--- a/internal/aistudio/types.go
+++ b/internal/aistudio/types.go
@@ -531,6 +531,8 @@ type Model struct {
CapabilityOptions map[string][]string `json:"capability_options,omitempty"`
// VoiceDetails 是 TTS 与 Live 模型的音色介绍,顺序与官网音色列表一致
VoiceDetails []VoiceDetail `json:"voice_details,omitempty"`
+ // DefaultVoice 是 Live 模型官网默认选中的音色,目录没有给出时对话模型为 Live 音色列表第一个,翻译模型为空
+ DefaultVoice string `json:"default_voice,omitempty"`
// Languages 是实时翻译与转录模型可选的语言,顺序与官网语言列表一致
Languages []Language `json:"languages,omitempty"`
AccessModes []int64 `json:"access_modes,omitempty"`
@@ -540,6 +542,8 @@ type Model struct {
AgentModel string `json:"agent_model,omitempty"`
// Hidden 表示官网前端已配置、ListModels 尚未列出、经 CountTokens 确认可用的模型
Hidden bool `json:"hidden,omitempty"`
+ // Unavailable 是本服务调用不了模型的原因,取值为 "paid_api_key" 或 "no_methods",由 CatalogModels 填写
+ Unavailable string `json:"unavailable,omitempty"`
}
// ThinkingBudget 是 ListModels field 72 的思考预算配置
diff --git a/internal/aistudio/upload.go b/internal/aistudio/upload.go
index d3f4d8c1..2ddf5caa 100644
--- a/internal/aistudio/upload.go
+++ b/internal/aistudio/upload.go
@@ -1,6 +1,7 @@
package aistudio
import (
+ "bufio"
"bytes"
"cmp"
"context"
@@ -253,6 +254,8 @@ func (copies *TemporaryFileCopies) cleanup(parent context.Context) error {
}
}
errs := make([]error, len(copies.copies))
+ boundDeleted := make([]string, len(copies.copies))
+ sem := make(chan struct{}, min(len(copies.copies), inlineMediaUploadConcurrency))
var group sync.WaitGroup
for index, copy := range copies.copies {
token := copy.token
@@ -264,6 +267,8 @@ func (copies *TemporaryFileCopies) cleanup(parent context.Context) error {
token = lazyToken
}
group.Go(func() {
+ sem <- struct{}{}
+ defer func() { <-sem }()
cleanupCtx, cancel := context.WithTimeout(parent, driveCleanupTimeout)
defer cancel()
cleanupCtx = ContextWithAccountLease(cleanupCtx, copies.lease)
@@ -273,16 +278,24 @@ func (copies *TemporaryFileCopies) cleanup(parent context.Context) error {
if driveFileNotFound(deleteErr, "DriveDelete") {
deleteErr = nil
}
- bindErr := error(nil)
if deleteErr == nil && copy.bound {
- if bindErr = copies.lease.pool.unbindResourceContext(cleanupCtx, copy.id); errors.Is(bindErr, ErrResourceNotFound) {
- bindErr = nil
- }
+ boundDeleted[index] = copy.id
}
- errs[index] = errors.Join(deleteErr, bindErr)
+ errs[index] = deleteErr
})
}
group.Wait()
+ var toUnbind []string
+ for _, id := range boundDeleted {
+ if id != "" {
+ toUnbind = append(toUnbind, id)
+ }
+ }
+ if len(toUnbind) > 0 {
+ unbindCtx, cancel := context.WithTimeout(parent, driveCleanupTimeout)
+ errs = append(errs, copies.lease.pool.unbindResourcesContext(unbindCtx, copies.lease.Account().ID, toUnbind))
+ cancel()
+ }
slices.Reverse(errs)
copies.err = errors.Join(errs...)
})
@@ -433,80 +446,88 @@ func driveCacheMatchesAccount(entry cachedDriveValue, account *Account, authGen
return entry.account == account && entry.authGen == authGen
}
-// cachedDriveTokenFor 按账户指针与认证代次返回账户级缓存中仍在有效期的 Drive access token
-func (c *Client) cachedDriveTokenFor(accountID string, account *Account, authGen uint64) string {
+// cachedDriveValueFor 返回 table 中该账户仍有效的缓存值,ttl 大于 0 时超过它的项视为过期
+func (c *Client) cachedDriveValueFor(table *map[string]cachedDriveValue, accountID string, account *Account, authGen uint64, ttl time.Duration) string {
c.driveCacheMu.Lock()
defer c.driveCacheMu.Unlock()
- entry, ok := c.driveTokens[accountID]
- if !ok || entry.value == "" || !driveCacheMatchesAccount(entry, account, authGen) || time.Since(entry.at) > pageTokenLifetime {
+ entry, ok := (*table)[accountID]
+ if !ok || entry.value == "" || !driveCacheMatchesAccount(entry, account, authGen) || (ttl > 0 && time.Since(entry.at) > ttl) {
return ""
}
return entry.value
}
-// storeDriveTokenFor 按账户指针与认证代次写入 Drive access token 缓存,at 为零值时按当前时刻记,同一账户已有更新代次的项时不覆盖
-func (c *Client) storeDriveTokenFor(accountID string, account *Account, authGen uint64, token string, at time.Time) {
- if token == "" {
+// storeDriveValueFor 按账户指针与认证代次写入 table,at 为零值时按当前时刻记,同一账户已有更新代次的项时不覆盖
+func (c *Client) storeDriveValueFor(table *map[string]cachedDriveValue, accountID string, account *Account, authGen uint64, value string, at time.Time) {
+ if value == "" {
return
}
if at.IsZero() {
at = time.Now()
}
- entry := cachedDriveValue{value: token, account: account, authGen: authGen, at: at}
+ entry := cachedDriveValue{value: value, account: account, authGen: authGen, at: at}
c.driveCacheMu.Lock()
- if c.driveTokens == nil {
- c.driveTokens = make(map[string]cachedDriveValue)
+ if *table == nil {
+ *table = make(map[string]cachedDriveValue)
}
- if prev, ok := c.driveTokens[accountID]; ok && account != nil && prev.account == account && prev.authGen > authGen {
+ if prev, ok := (*table)[accountID]; ok && account != nil && prev.account == account && prev.authGen > authGen {
c.driveCacheMu.Unlock()
return
}
- c.driveTokens[accountID] = entry
+ (*table)[accountID] = entry
c.driveCacheMu.Unlock()
}
-// invalidateDriveToken 在账户缓存中的 token 等于 oldToken 时删除它,oldToken 为空时无条件删除
-func (c *Client) invalidateDriveToken(accountID, oldToken string) {
+// invalidateDriveValue 在 table 中该账户的缓存值等于 oldValue 时删除它,oldValue 为空时无条件删除
+func (c *Client) invalidateDriveValue(table *map[string]cachedDriveValue, accountID, oldValue string) {
c.driveCacheMu.Lock()
- if entry, ok := c.driveTokens[accountID]; ok && (oldToken == "" || entry.value == oldToken) {
- delete(c.driveTokens, accountID)
+ if entry, ok := (*table)[accountID]; ok && (oldValue == "" || entry.value == oldValue) {
+ delete(*table, accountID)
}
c.driveCacheMu.Unlock()
}
-// doDriveStringFlight 合并同账户并发的 Drive 令牌或应用文件夹查询,run 不持有任何请求的租约,全部等待方取消时中止
-func (c *Client) doDriveStringFlight(
+// doCancellableFlight 合并同键并发请求,run 不持有任何请求的租约,全部等待方取消时中止;timeout 大于 0 时附带超时
+func doCancellableFlight[K comparable, V any](
ctx context.Context,
- table *map[string]*driveStringFlight,
- accountID string,
+ mu *sync.Mutex,
+ table *map[K]*cancellableFlight[V],
+ key K,
account *Account,
- run func(context.Context) (string, error),
-) (string, error) {
- c.driveCacheMu.Lock()
+ timeout time.Duration,
+ run func(context.Context) (V, error),
+) (V, error) {
+ mu.Lock()
if *table == nil {
- *table = make(map[string]*driveStringFlight)
+ *table = make(map[K]*cancellableFlight[V])
}
- flight := (*table)[accountID]
+ flight := (*table)[key]
if flight != nil {
flight.waiters++
- c.driveCacheMu.Unlock()
+ mu.Unlock()
} else {
baseCtx := context.WithoutCancel(ctx)
if account != nil {
baseCtx = contextWithFlightAccount(baseCtx, account)
}
- flightCtx, cancel := context.WithTimeout(baseCtx, driveLookupFlightTimeout)
- flight = &driveStringFlight{waiters: 1, cancel: cancel, done: make(chan struct{})}
- (*table)[accountID] = flight
- c.driveCacheMu.Unlock()
+ var flightCtx context.Context
+ var cancel context.CancelFunc
+ if timeout > 0 {
+ flightCtx, cancel = context.WithTimeout(baseCtx, timeout)
+ } else {
+ flightCtx, cancel = context.WithCancel(baseCtx)
+ }
+ flight = &cancellableFlight[V]{waiters: 1, cancel: cancel, done: make(chan struct{})}
+ (*table)[key] = flight
+ mu.Unlock()
go func() {
defer func() {
cancel()
- c.driveCacheMu.Lock()
- if (*table)[accountID] == flight {
- delete(*table, accountID)
+ mu.Lock()
+ if (*table)[key] == flight {
+ delete(*table, key)
}
- c.driveCacheMu.Unlock()
+ mu.Unlock()
close(flight.done)
}()
flight.value, flight.err = run(flightCtx)
@@ -516,26 +537,42 @@ func (c *Client) doDriveStringFlight(
case <-flight.done:
return flight.value, flight.err
case <-ctx.Done():
- c.driveCacheMu.Lock()
+ mu.Lock()
flight.waiters--
stop := flight.waiters == 0
- if stop && (*table)[accountID] == flight {
- delete(*table, accountID)
+ if stop && (*table)[key] == flight {
+ delete(*table, key)
}
- c.driveCacheMu.Unlock()
+ mu.Unlock()
if stop {
flight.cancel()
}
- return "", ctx.Err()
+ var zero V
+ return zero, ctx.Err()
}
}
+// cachedDriveTokenFor 按账户指针与认证代次返回账户级缓存中仍在有效期的 Drive access token
+func (c *Client) cachedDriveTokenFor(accountID string, account *Account, authGen uint64) string {
+ return c.cachedDriveValueFor(&c.driveTokens, accountID, account, authGen, pageTokenLifetime)
+}
+
+// storeDriveTokenFor 按账户指针与认证代次写入 Drive access token 缓存,at 为零值时按当前时刻记,同一账户已有更新代次的项时不覆盖
+func (c *Client) storeDriveTokenFor(accountID string, account *Account, authGen uint64, token string, at time.Time) {
+ c.storeDriveValueFor(&c.driveTokens, accountID, account, authGen, token, at)
+}
+
+// invalidateDriveToken 在账户缓存中的 token 等于 oldToken 时删除它,oldToken 为空时无条件删除
+func (c *Client) invalidateDriveToken(accountID, oldToken string) {
+ c.invalidateDriveValue(&c.driveTokens, accountID, oldToken)
+}
+
// fetchDriveTokenFor 按账户指针与认证代次读取或申请账户 Drive access token 并写入缓存
func (c *Client) fetchDriveTokenFor(ctx context.Context, accountID string, account *Account, authGen uint64) (string, error) {
if cached := c.cachedDriveTokenFor(accountID, account, authGen); cached != "" {
return cached, nil
}
- return c.doDriveStringFlight(ctx, &c.driveTokenFlights, accountID, account, func(fetchCtx context.Context) (string, error) {
+ return doCancellableFlight(ctx, &c.driveCacheMu, &c.driveTokenFlights, accountID, account, driveLookupFlightTimeout, func(fetchCtx context.Context) (string, error) {
if cached := c.cachedDriveTokenFor(accountID, account, authGen); cached != "" {
return cached, nil
}
@@ -550,40 +587,17 @@ func (c *Client) fetchDriveTokenFor(ctx context.Context, accountID string, accou
// cachedAppFolderFor 按账户指针与认证代次返回账户级缓存中的应用文件夹 ID
func (c *Client) cachedAppFolderFor(accountID string, account *Account, authGen uint64) string {
- c.driveCacheMu.Lock()
- defer c.driveCacheMu.Unlock()
- entry, ok := c.appFolders[accountID]
- if !ok || entry.value == "" || !driveCacheMatchesAccount(entry, account, authGen) {
- return ""
- }
- return entry.value
+ return c.cachedDriveValueFor(&c.appFolders, accountID, account, authGen, 0)
}
// storeAppFolderFor 按账户指针与认证代次写入应用文件夹 ID 缓存,同一账户已有更新代次的项时不覆盖
func (c *Client) storeAppFolderFor(accountID string, account *Account, authGen uint64, folder string) {
- if folder == "" {
- return
- }
- entry := cachedDriveValue{value: folder, account: account, authGen: authGen, at: time.Now()}
- c.driveCacheMu.Lock()
- if c.appFolders == nil {
- c.appFolders = make(map[string]cachedDriveValue)
- }
- if prev, ok := c.appFolders[accountID]; ok && account != nil && prev.account == account && prev.authGen > authGen {
- c.driveCacheMu.Unlock()
- return
- }
- c.appFolders[accountID] = entry
- c.driveCacheMu.Unlock()
+ c.storeDriveValueFor(&c.appFolders, accountID, account, authGen, folder, time.Time{})
}
// invalidateAppFolder 在账户缓存中的应用文件夹等于 oldFolder 时删除它,oldFolder 为空时无条件删除
func (c *Client) invalidateAppFolder(accountID, oldFolder string) {
- c.driveCacheMu.Lock()
- if entry, ok := c.appFolders[accountID]; ok && (oldFolder == "" || entry.value == oldFolder) {
- delete(c.appFolders, accountID)
- }
- c.driveCacheMu.Unlock()
+ c.invalidateDriveValue(&c.appFolders, accountID, oldFolder)
}
// fetchAppFolderFor 按账户指针与认证代次读取或申请账户应用文件夹 ID,onSent 在 GetAppFolder 发出后回调
@@ -591,7 +605,7 @@ func (c *Client) fetchAppFolderFor(ctx context.Context, accountID string, accoun
if cached := c.cachedAppFolderFor(accountID, account, authGen); cached != "" {
return cached, nil
}
- return c.doDriveStringFlight(ctx, &c.appFolderFlights, accountID, account, func(fetchCtx context.Context) (string, error) {
+ return doCancellableFlight(ctx, &c.driveCacheMu, &c.appFolderFlights, accountID, account, driveLookupFlightTimeout, func(fetchCtx context.Context) (string, error) {
if cached := c.cachedAppFolderFor(accountID, account, authGen); cached != "" {
return cached, nil
}
@@ -605,6 +619,7 @@ func (c *Client) fetchAppFolderFor(ctx context.Context, accountID string, accoun
if err != nil {
return "", err
}
+ markAppFolderCalled(fetchCtx, accountID)
c.storeAppFolderFor(accountID, account, authGen, folder)
return folder, nil
})
@@ -612,53 +627,84 @@ func (c *Client) fetchAppFolderFor(ctx context.Context, accountID string, accoun
// doInlineUpload 合并同账户同一个待上传内联附件的并发上传,run 不持有任何请求的租约,全部等待方取消时中止
func (c *Client) doInlineUpload(ctx context.Context, accountID string, account *Account, key inlineMediaKey, run func(context.Context) (FileRef, error)) (FileRef, error) {
- flightKey := inlineUploadFlightKey{accountID: accountID, key: key}
- c.inlineUploadMu.Lock()
- if c.inlineUploads == nil {
- c.inlineUploads = make(map[inlineUploadFlightKey]*inlineUploadFlight)
+ return doCancellableFlight(ctx, &c.inlineUploadMu, &c.inlineUploads, inlineUploadFlightKey{accountID: accountID, key: key}, account, 0, run)
+}
+
+// driveUploadState 是同一批并发上传共享的账户令牌与应用文件夹,tokenFromCache 与 folderFromCache 表示取值在这批上传开始前就已存在
+// 约束:token 与 folder 由 mu 保护,tokenFromCache 与 folderFromCache 创建后只读
+type driveUploadState struct {
+ mu sync.Mutex
+ token, folder string
+ tokenFromCache bool
+ folderFromCache bool
+}
+
+// current 返回共享的令牌与应用文件夹
+func (state *driveUploadState) current() (token, folder string) {
+ state.mu.Lock()
+ defer state.mu.Unlock()
+ return state.token, state.folder
+}
+
+// resolve 返回这批上传当前使用的令牌与应用文件夹:共享取值,账户缓存中有取值时以缓存为准
+func (state *driveUploadState) resolve(c *Client, accountID string, account *Account, authGen uint64) (token, folder string) {
+ token, folder = state.current()
+ if fresh := c.cachedDriveTokenFor(accountID, account, authGen); fresh != "" {
+ token = fresh
}
- flight := c.inlineUploads[flightKey]
- if flight != nil {
- flight.waiters++
- c.inlineUploadMu.Unlock()
- } else {
- baseCtx := context.WithoutCancel(ctx)
- if account != nil {
- baseCtx = contextWithFlightAccount(baseCtx, account)
- }
- flightCtx, cancel := context.WithCancel(baseCtx)
- flight = &inlineUploadFlight{waiters: 1, cancel: cancel, done: make(chan struct{})}
- c.inlineUploads[flightKey] = flight
- c.inlineUploadMu.Unlock()
- go func() {
- defer func() {
- cancel()
- c.inlineUploadMu.Lock()
- if c.inlineUploads[flightKey] == flight {
- delete(c.inlineUploads, flightKey)
- }
- c.inlineUploadMu.Unlock()
- close(flight.done)
- }()
- flight.file, flight.err = run(flightCtx)
- }()
+ if fresh := c.cachedAppFolderFor(accountID, account, authGen); fresh != "" {
+ folder = fresh
}
- select {
- case <-flight.done:
- return flight.file, flight.err
- case <-ctx.Done():
- c.inlineUploadMu.Lock()
- flight.waiters--
- stop := flight.waiters == 0
- if stop && c.inlineUploads[flightKey] == flight {
- delete(c.inlineUploads, flightKey)
+ return token, folder
+}
+
+// refreshForRetry 在上传以 401 且令牌来自缓存、或 404 且应用文件夹来自缓存失败时失效对应的缓存并刷新,返回重试上传使用的令牌与应用文件夹;不需要重试时 retry 为 false,刷新失败时返回刷新的错误
+// 刷新后以共享取值与账户缓存中更新的取值为准,调用方在重试前自行准备新的数据读取器
+func (c *Client) refreshForRetry(ctx context.Context, accountID string, account *Account, authGen uint64, state *driveUploadState, uploadErr error, useToken, useFolder string) (token, folder string, retry bool, err error) {
+ switch driveUploadHTTPStatus(uploadErr) {
+ case http.StatusUnauthorized:
+ if !state.tokenFromCache {
+ return "", "", false, nil
}
- c.inlineUploadMu.Unlock()
- if stop {
- flight.cancel()
+ c.invalidateDriveToken(accountID, useToken)
+ refreshed, refreshErr := c.fetchDriveTokenFor(ctx, accountID, account, authGen)
+ if refreshErr != nil {
+ return "", "", false, refreshErr
+ }
+ state.mu.Lock()
+ state.token = refreshed
+ state.mu.Unlock()
+ _, folder = state.resolve(c, accountID, account, authGen)
+ return refreshed, folder, true, nil
+ case http.StatusNotFound:
+ if !state.folderFromCache {
+ return "", "", false, nil
}
- return FileRef{}, ctx.Err()
+ c.invalidateAppFolder(accountID, useFolder)
+ refreshed, refreshErr := c.fetchAppFolderFor(ctx, accountID, account, authGen, nil)
+ if refreshErr != nil {
+ return "", "", false, refreshErr
+ }
+ state.mu.Lock()
+ state.folder = refreshed
+ state.mu.Unlock()
+ token, _ = state.resolve(c, accountID, account, authGen)
+ return token, refreshed, true, nil
}
+ return "", "", false, nil
+}
+
+// checkImageAsync 与内联图片的上传同时由页面发出官网插入图片时的 CheckImage,响应与错误都不影响上传;返回的函数取消尚未完成的检查,上传不等待检查
+func (c *Client) checkImageAsync(ctx context.Context, accountID string, blob *Blob) context.CancelFunc {
+ if !strings.HasPrefix(blob.MIME, "image/") {
+ return func() {}
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ go func() {
+ body, _ := json.Marshal([][]string{{blob.MIME, base64.StdEncoding.EncodeToString(blob.Data)}})
+ _, _ = c.readRPC(issuedByPage(ctx), "CheckImage", accountID, body)
+ }()
+ return cancel
}
// GenerateAccessToken 获取网页账户授权的短期 bearer token
@@ -1220,11 +1266,6 @@ func (s *PooledService) CopyFileReferencesToLease(
return
}
targetFolder = folder
- if worker := pageWorker(targetID); worker != nil {
- if cur, ok := worker.current().(*goWAARuntime); ok {
- cur.appFolderCalled.Store(true)
- }
- }
})
}
for _, owner := range sourceOwners {
@@ -1277,9 +1318,7 @@ func (s *PooledService) CopyFileReferencesToLease(
return nil, nil, errors.Join(sourceLookupErr, releaseSources(), copies.Cleanup())
}
- var targetMu sync.Mutex
- currentTargetToken := targetToken
- currentTargetFolder := targetFolder
+ state := &driveUploadState{token: targetToken, folder: targetFolder, tokenFromCache: targetTokenFromCache, folderFromCache: targetFolderFromCache}
drive := s.client.transport.(DriveTransport)
type copyResult struct {
@@ -1361,15 +1400,7 @@ func (s *PooledService) CopyFileReferencesToLease(
return
}
targetOpCtx := ContextWithAccountLease(copyCtx, target)
- targetMu.Lock()
- useToken, useFolder := currentTargetToken, currentTargetFolder
- targetMu.Unlock()
- if fresh := s.client.cachedDriveTokenFor(targetID, targetAccount, targetAuthGen); fresh != "" {
- useToken = fresh
- }
- if fresh := s.client.cachedAppFolderFor(targetID, targetAccount, targetAuthGen); fresh != "" {
- useFolder = fresh
- }
+ useToken, useFolder := state.resolve(s.client, targetID, targetAccount, targetAuthGen)
req := UploadRequest{
AccountID: targetID,
Name: job.metadata.Name,
@@ -1382,59 +1413,19 @@ func (s *PooledService) CopyFileReferencesToLease(
closeErr := media.Body.Close()
usedToken := useToken
if uploadErr != nil {
- switch driveUploadHTTPStatus(uploadErr) {
- case http.StatusUnauthorized:
- if targetTokenFromCache {
- s.client.invalidateDriveToken(targetID, useToken)
- refreshed, refreshErr := s.client.fetchDriveTokenFor(targetOpCtx, targetID, targetAccount, targetAuthGen)
- if refreshErr != nil {
- uploadErr = refreshErr
- } else if refreshed != "" {
- targetMu.Lock()
- currentTargetToken = refreshed
- useFolder = currentTargetFolder
- targetMu.Unlock()
- if freshFolder := s.client.cachedAppFolderFor(targetID, targetAccount, targetAuthGen); freshFolder != "" {
- useFolder = freshFolder
- }
- retryMedia, retryErr := openSource(copyCtx, st, job.fileID)
- if retryErr != nil {
- resultCh <- copyResult{index: index, err: retryErr}
- return
- }
- req.Reader = retryMedia.Body
- req.Folder = useFolder
- usedToken = refreshed
- copied, uploadErr = drive.UploadDrive(targetOpCtx, targetID, refreshed, req)
- closeErr = retryMedia.Body.Close()
- }
- }
- case http.StatusNotFound:
- if targetFolderFromCache {
- s.client.invalidateAppFolder(targetID, useFolder)
- refreshed, refreshErr := s.client.fetchAppFolderFor(targetOpCtx, targetID, targetAccount, targetAuthGen, nil)
- if refreshErr != nil {
- uploadErr = refreshErr
- } else if refreshed != "" {
- targetMu.Lock()
- currentTargetFolder = refreshed
- useToken = currentTargetToken
- targetMu.Unlock()
- if freshToken := s.client.cachedDriveTokenFor(targetID, targetAccount, targetAuthGen); freshToken != "" {
- useToken = freshToken
- }
- retryMedia, retryErr := openSource(copyCtx, st, job.fileID)
- if retryErr != nil {
- resultCh <- copyResult{index: index, err: retryErr}
- return
- }
- req.Reader = retryMedia.Body
- req.Folder = refreshed
- usedToken = useToken
- copied, uploadErr = drive.UploadDrive(targetOpCtx, targetID, useToken, req)
- closeErr = retryMedia.Body.Close()
- }
+ retryToken, retryFolder, retry, refreshErr := s.client.refreshForRetry(targetOpCtx, targetID, targetAccount, targetAuthGen, state, uploadErr, useToken, useFolder)
+ switch {
+ case refreshErr != nil:
+ uploadErr = refreshErr
+ case retry:
+ retryMedia, retryErr := openSource(copyCtx, st, job.fileID)
+ if retryErr != nil {
+ resultCh <- copyResult{index: index, err: retryErr}
+ return
}
+ req.Reader, req.Folder, usedToken = retryMedia.Body, retryFolder, retryToken
+ copied, uploadErr = drive.UploadDrive(targetOpCtx, targetID, retryToken, req)
+ closeErr = retryMedia.Body.Close()
}
}
resultCh <- copyResult{index: index, file: copied, token: usedToken, err: errors.Join(uploadErr, closeErr), targetOp: true}
@@ -1735,8 +1726,20 @@ func (s *PooledService) reclaimExpiredResources(ctx context.Context, accountID s
return errors.Join(copies.cleanup(leaseCtx), lease.Release())
}
+// inlineMediaBinding 是一个待记录到账户资源的已上传内联附件
+type inlineMediaBinding struct {
+ file FileRef
+ key inlineMediaKey
+ size int64
+}
+
// bindInlineMediaAccount 把上传到 account 的内联附件记录到账户资源,account 已不是池中当前实例时返回 ErrAccountNotFound
func (p *AccountPool) bindInlineMediaAccount(ctx context.Context, account *Account, file FileRef, key inlineMediaKey, size int64) error {
+ return p.bindInlineMediaBatchAccount(ctx, account, []inlineMediaBinding{{file: file, key: key, size: size}})
+}
+
+// bindInlineMediaBatchAccount 在单次运行状态事务中把一批已上传内联附件批量记录到账户资源,已存在同账户绑定时幂等跳过
+func (p *AccountPool) bindInlineMediaBatchAccount(ctx context.Context, account *Account, items []inlineMediaBinding) error {
account.storageMu.Lock()
defer account.storageMu.Unlock()
accountID := account.ID
@@ -1744,14 +1747,21 @@ func (p *AccountPool) bindInlineMediaAccount(ctx context.Context, account *Accou
if current != account {
return false, nil, fmt.Errorf("%w: %s", ErrAccountNotFound, accountID)
}
- if owner, exists := p.resources[file.ID]; exists && owner != accountID {
- return false, nil, fmt.Errorf("资源 %s 已绑定账户 %s", file.ID, owner)
- }
now := time.Now().UTC()
- runtimeState.Resources[file.ID] = ResourceBinding{
- Kind: "inline-media", Name: file.Name, MIME: file.MIME, Size: size, SHA256: key.sha256, CreatedAt: now, UsedAt: now, DisplayName: key.name,
+ changed := false
+ for _, item := range items {
+ if owner, exists := p.resources[item.file.ID]; exists && owner != accountID {
+ return false, nil, fmt.Errorf("资源 %s 已绑定账户 %s", item.file.ID, owner)
+ }
+ if existing, exists := runtimeState.Resources[item.file.ID]; exists && existing.Kind == "inline-media" {
+ continue
+ }
+ runtimeState.Resources[item.file.ID] = ResourceBinding{
+ Kind: "inline-media", Name: item.file.Name, MIME: item.file.MIME, Size: item.size, SHA256: item.key.sha256, CreatedAt: now, UsedAt: now, DisplayName: item.key.name,
+ }
+ changed = true
}
- return true, nil, nil
+ return changed, nil, nil
})
return err
}
@@ -2018,10 +2028,6 @@ func (s *PooledService) UploadInlineMediaToLease(
folder, folderErr = s.client.fetchAppFolderFor(lookupCtx, targetID, targetAccount, targetAuthGen, startDiscovery)
if folderErr != nil {
cancelLookup()
- } else if worker != nil {
- if current, ok := worker.current().(*goWAARuntime); ok {
- current.appFolderCalled.Store(true)
- }
}
})
}
@@ -2058,9 +2064,7 @@ func (s *PooledService) UploadInlineMediaToLease(
timing.TokenFolder = time.Since(lookupStart)
}
uploadErr := folderErr
- var tokenMu sync.Mutex
- currentToken := token
- currentFolder := folder
+ state := &driveUploadState{token: token, folder: folder, tokenFromCache: tokenFromCache, folderFromCache: folderFromCache}
uploadStart := time.Now()
uploadedCount := 0
if len(pending) > 0 && folderErr == nil {
@@ -2078,15 +2082,9 @@ func (s *PooledService) UploadInlineMediaToLease(
}
defer func() { <-sem }()
file, err := s.client.doInlineUpload(uploadCtx, targetID, targetAccount, job.key, func(flightCtx context.Context) (FileRef, error) {
- tokenMu.Lock()
- useToken, useFolder := currentToken, currentFolder
- tokenMu.Unlock()
- if fresh := s.client.cachedDriveTokenFor(targetID, targetAccount, targetAuthGen); fresh != "" {
- useToken = fresh
- }
- if fresh := s.client.cachedAppFolderFor(targetID, targetAccount, targetAuthGen); fresh != "" {
- useFolder = fresh
- }
+ cancelCheck := s.client.checkImageAsync(flightCtx, targetID, job.blob)
+ defer cancelCheck()
+ useToken, useFolder := state.resolve(s.client, targetID, targetAccount, targetAuthGen)
req := UploadRequest{
AccountID: targetID,
Name: job.name,
@@ -2098,49 +2096,13 @@ func (s *PooledService) UploadInlineMediaToLease(
uploaded, err := drive.UploadDrive(flightCtx, targetID, useToken, req)
usedToken := useToken
if err != nil {
- switch driveUploadHTTPStatus(err) {
- case http.StatusUnauthorized:
- if tokenFromCache {
- s.client.invalidateDriveToken(targetID, useToken)
- refreshed, refreshErr := s.client.fetchDriveTokenFor(flightCtx, targetID, targetAccount, targetAuthGen)
- if refreshErr != nil {
- return FileRef{}, refreshErr
- }
- if refreshed != "" {
- tokenMu.Lock()
- currentToken = refreshed
- useFolder = currentFolder
- tokenMu.Unlock()
- if freshFolder := s.client.cachedAppFolderFor(targetID, targetAccount, targetAuthGen); freshFolder != "" {
- useFolder = freshFolder
- }
- req.Reader = bytes.NewReader(job.blob.Data)
- req.Folder = useFolder
- usedToken = refreshed
- uploaded, err = drive.UploadDrive(flightCtx, targetID, refreshed, req)
- }
- }
- case http.StatusNotFound:
- if folderFromCache {
- s.client.invalidateAppFolder(targetID, useFolder)
- refreshed, refreshErr := s.client.fetchAppFolderFor(flightCtx, targetID, targetAccount, targetAuthGen, nil)
- if refreshErr != nil {
- return FileRef{}, refreshErr
- }
- if refreshed != "" {
- tokenMu.Lock()
- currentFolder = refreshed
- useToken = currentToken
- tokenMu.Unlock()
- if freshToken := s.client.cachedDriveTokenFor(targetID, targetAccount, targetAuthGen); freshToken != "" {
- useToken = freshToken
- }
- req.Reader = bytes.NewReader(job.blob.Data)
- req.Folder = refreshed
- usedToken = useToken
- uploaded, err = drive.UploadDrive(flightCtx, targetID, useToken, req)
- }
- }
+ retryToken, retryFolder, retry, refreshErr := s.client.refreshForRetry(flightCtx, targetID, targetAccount, targetAuthGen, state, err, useToken, useFolder)
+ if refreshErr != nil {
+ return FileRef{}, refreshErr
+ }
+ if retry {
+ req.Reader, req.Folder, usedToken = bytes.NewReader(job.blob.Data), retryFolder, retryToken
+ uploaded, err = drive.UploadDrive(flightCtx, targetID, retryToken, req)
}
}
if err != nil {
@@ -2160,10 +2122,6 @@ func (s *PooledService) UploadInlineMediaToLease(
cleanupOrphan()
return FileRef{}, flightCtx.Err()
}
- if bindErr := s.pool.bindInlineMediaAccount(context.WithoutCancel(flightCtx), targetAccount, uploaded, job.key, int64(len(job.blob.Data))); bindErr != nil {
- cleanupOrphan()
- return FileRef{}, bindErr
- }
return uploaded, nil
})
resultChannel <- uploadResult{index: index, file: file, err: err}
@@ -2179,15 +2137,47 @@ func (s *PooledService) UploadInlineMediaToLease(
}
cancelUploads()
var failures GroupedErrors
+ bindings := make([]inlineMediaBinding, 0, len(pending))
+ boundIndices := make([]int, 0, len(pending))
for index, result := range results {
if result.err != nil {
failures.Add("", result.err)
continue
}
job := pending[index]
- files[job.key] = result.file
- used = append(used, result.file.ID)
- uploadedCount++
+ bindings = append(bindings, inlineMediaBinding{file: result.file, key: job.key, size: int64(len(job.blob.Data))})
+ boundIndices = append(boundIndices, index)
+ }
+ if len(bindings) > 0 {
+ if bindErr := s.pool.bindInlineMediaBatchAccount(context.WithoutCancel(targetCtx), targetAccount, bindings); bindErr != nil {
+ orphanToken, _ := state.resolve(s.client, targetID, targetAccount, targetAuthGen)
+ var orphanWG sync.WaitGroup
+ orphanSem := make(chan struct{}, min(len(bindings), inlineMediaUploadConcurrency))
+ for _, item := range bindings {
+ if item.file.ID == "" {
+ continue
+ }
+ orphanWG.Go(func() {
+ orphanSem <- struct{}{}
+ defer func() { <-orphanSem }()
+ cleanupCtx, cancel := context.WithTimeout(contextWithFlightAccount(context.WithoutCancel(targetCtx), targetAccount), driveCleanupTimeout)
+ defer cancel()
+ if delErr := s.client.deleteDriveFile(cleanupCtx, targetID, orphanToken, item.file.ID); delErr != nil && !driveFileNotFound(delErr, "DriveDelete") {
+ slog.Warn("回收未绑定内联附件失败", "account", targetID, "file", item.file.ID, "error", delErr)
+ }
+ })
+ }
+ orphanWG.Wait()
+ failures.Add("", bindErr)
+ } else {
+ for _, index := range boundIndices {
+ job := pending[index]
+ file := results[index].file
+ files[job.key] = file
+ used = append(used, file.ID)
+ uploadedCount++
+ }
+ }
}
uploadErr = failures.Join(nil)
}
@@ -2195,12 +2185,7 @@ func (s *PooledService) UploadInlineMediaToLease(
timing.Upload = time.Since(uploadStart)
timing.Uploaded = uploadedCount
}
- tokenMu.Lock()
- finalToken := currentToken
- tokenMu.Unlock()
- if fresh := s.client.cachedDriveTokenFor(targetID, targetAccount, targetAuthGen); fresh != "" {
- finalToken = fresh
- }
+ finalToken, _ := state.resolve(s.client, targetID, targetAccount, targetAuthGen)
for _, id := range expired {
temporary.copies = append(temporary.copies, temporaryDriveCopy{id: id, token: finalToken, bound: true})
}
@@ -2659,11 +2644,15 @@ func uploadDriveMultipart(ctx context.Context, client *http.Client, address stri
suffix := "\r\n--" + gapiBoundary + "--"
encoded, writer := io.Pipe()
go func() {
- encoder := base64.NewEncoder(base64.StdEncoding, writer)
+ buffered := bufio.NewWriterSize(writer, 64<<10)
+ encoder := base64.NewEncoder(base64.StdEncoding, buffered)
_, err := io.Copy(encoder, request.Reader)
if err == nil {
err = encoder.Close()
}
+ if err == nil {
+ err = buffered.Flush()
+ }
writer.CloseWithError(err)
}()
body := struct {
diff --git a/internal/aistudio/webchannel.go b/internal/aistudio/webchannel.go
index 312eb020..22d31060 100644
--- a/internal/aistudio/webchannel.go
+++ b/internal/aistudio/webchannel.go
@@ -66,6 +66,7 @@ type BidiSession struct {
mode BidiMode
buildPath string
modelAccessScope string
+ capabilities map[string]bool
accountID string
modelAccessObserver func()
headerMu sync.RWMutex
@@ -161,6 +162,8 @@ func (s *PooledService) OpenBidi(ctx context.Context, request BidiRequest) (*Bid
return nil, entryErr
}
request.generationDefaults = entry.defaults
+ request.defaultVoice = entry.model.DefaultVoice
+ request.capabilities = entry.model.Capabilities
if request.Mode == BidiModeLive {
request.variant = bidiVariantFor(entry.model)
}
@@ -335,6 +338,38 @@ func (s *BidiSession) SendToolResponses(ctx context.Context, results []FunctionR
return s.sendProtected(ctx, body, proofAt, binding, "", false, true)
}
+// SendClientContent 发送官网 clientContent 帧
+func (s *BidiSession) SendClientContent(ctx context.Context, turns []BidiTurn, turnComplete bool) error {
+ body, proofAt, binding, err := s.liveFrame(
+ func() ([]byte, int, string, error) { return EncodeBidiClientContentRequest(turns, turnComplete) },
+ nil,
+ )
+ if err != nil {
+ return err
+ }
+ return s.sendProtected(
+ ctx, body, proofAt, binding, "",
+ turnComplete && s.modelAccessScope != "" && (s.mode == BidiModeRobotics || s.modelAccessScope == s.model), true,
+ )
+}
+
+// SendContextUpdate 发送官网 contextUpdate 帧,系统指令与工具的更新分别需要目录能力码 100 与 101
+func (s *BidiSession) SendContextUpdate(ctx context.Context, update BidiContextUpdate) error {
+ body, proofAt, binding, err := s.liveFrame(func() ([]byte, int, string, error) {
+ if update.SystemInstruction != nil && !s.capabilities["capability_code_100"] {
+ return nil, 0, "", fmt.Errorf("%w: 模型 %s 不支持 %s", ErrInvalidArgument, s.model, "context_update.system_instruction")
+ }
+ if update.UpdateTools && !s.capabilities["capability_code_101"] {
+ return nil, 0, "", fmt.Errorf("%w: 模型 %s 不支持 %s", ErrInvalidArgument, s.model, "context_update.tools")
+ }
+ return EncodeBidiContextUpdateRequest(update)
+ }, nil)
+ if err != nil {
+ return err
+ }
+ return s.sendProtected(ctx, body, proofAt, binding, "", false, true)
+}
+
// Close 取消网络读取并等待账户租约释放
func (s *BidiSession) Close() error {
s.closeOnce.Do(func() {
@@ -414,7 +449,7 @@ func (t *WorkerProtectedTransport) OpenBidiProtected(
session := &BidiSession{
ctx: requestCtx, cancel: cancel, lease: lease, release: release, worker: worker, client: client,
headers: webChannelHeaders(protocolHeaders), model: strings.TrimPrefix(strings.TrimSpace(request.Model), "models/"),
- mode: request.Mode, buildPath: buildPath, modelAccessScope: strings.TrimSpace(request.ModelAccessScope),
+ mode: request.Mode, buildPath: buildPath, modelAccessScope: strings.TrimSpace(request.ModelAccessScope), capabilities: request.capabilities,
modelAccessObserver: request.ObserveModelAccessChange,
accountID: lease.Account().ID, rid: newWebChannelRID(), latestResumptionToken: strings.TrimSpace(request.SessionToken),
events: make(chan BidiEvent, 32), wireEvents: make(chan BidiEvent, 32),
diff --git a/internal/api/admin.go b/internal/api/admin.go
index c74172d9..d660c624 100644
--- a/internal/api/admin.go
+++ b/internal/api/admin.go
@@ -237,6 +237,8 @@ type AdminAccount struct {
DeviceBoundSession bool `json:"device_bound_session,omitempty"`
// MigratedModels 是账户目录中被 Google 迁移到任务接口的模型 ID,没有时省略
MigratedModels []string `json:"migrated_models,omitempty"`
+ // CallableModels 是账户按选号的同一判定可以调用的模型 ID,不看账户的启用、状态与冷却
+ CallableModels []string `json:"callable_models"`
}
// AccountExit 表示一个账户出口代理的公网 IP 与按 IP 定位的国家、时区和语言,Proxy 为空时是直连,查询失败时 Error 为原因
@@ -407,6 +409,7 @@ type RuntimeConfig struct {
MediaOutput string `json:"media_output"`
MediaBaseURL string `json:"media_base_url"`
BuildChatModels bool `json:"build_chat_models"`
+ BuildChatProtocol string `json:"build_chat_protocol"`
HideModels string `json:"hide_models"`
GenerateContentAccounts string `json:"generate_content_accounts"`
SillyTavernAPIKeys string `json:"sillytavern_api_keys"`
diff --git a/internal/api/anthropic.go b/internal/api/anthropic.go
index eb56cab7..716ac21b 100644
--- a/internal/api/anthropic.go
+++ b/internal/api/anthropic.go
@@ -170,8 +170,9 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request)
}
events, err := s.generate(r.Context(), generateRequest)
var startUsage *aistudio.Usage
+ var stream eventStream
if err == nil && request.Stream {
- events, startUsage, err = awaitStreamStart(r.Context(), events)
+ stream, startUsage, err = awaitStreamStart(r.Context(), events)
}
if err != nil {
if shouldWriteRequestError(r, err) {
@@ -180,13 +181,13 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request)
return
}
if request.Stream {
- stream, err := openStream(w, anthropicHeartbeat)
- defer stream.stop()
+ out, err := openStream(w, anthropicHeartbeat)
+ defer out.stop()
if err != nil {
return
}
writer := &anthropicStreamWriter{
- send: sseSender(stream), id: messageID, model: request.Model,
+ send: sseSender(out), id: messageID, model: request.Model,
inputTokens: <-estimate, startUsage: startUsage,
searchKey: s.config.APIKeys(), omitted: request.thinkingOmitted(),
media: media, context: contextResult, search: declaredSearch,
@@ -194,7 +195,7 @@ func (s *server) handleAnthropicMessages(w http.ResponseWriter, r *http.Request)
if err := writer.start(); err != nil {
return
}
- s.streamAnthropic(r, writer, events)
+ s.streamAnthropic(r, writer, stream)
return
}
result, err := consumeEvents(r.Context(), events)
@@ -1132,24 +1133,33 @@ func anthropicBlocks(result generationResult, omitted bool, media mediaOutput, s
// sseSender 返回把流式事件写成 SSE 的发送函数
func sseSender(w http.ResponseWriter) func(string, any) error {
return func(eventType string, payload any) error {
- if frame, ok := anthropicTextDelta(eventType, payload); ok {
+ if frame, ok := anthropicDelta(eventType, payload); ok {
return writeSSEFrame(w, frame)
}
return writeSSE(w, eventType, officialOrder("anthropic", payload))
}
}
-// anthropicTextDelta 返回正文 text_delta 的 content_block_delta SSE 帧,字节与按官方字段顺序编码的同一事件相同;其他事件返回 false
-func anthropicTextDelta(eventType string, payload any) ([]byte, bool) {
+// anthropicDelta 返回正文 text_delta 或思考 thinking_delta 的 content_block_delta SSE 帧,字节与按官方字段顺序编码的同一事件相同;其他事件返回 false
+func anthropicDelta(eventType string, payload any) ([]byte, bool) {
event, _ := payload.(map[string]any)
delta, _ := event["delta"].(map[string]any)
index, indexed := event["index"].(int)
- text, texted := delta["text"].(string)
- if eventType != "content_block_delta" || len(event) != 3 || len(delta) != 2 || delta["type"] != "text_delta" || !indexed || !texted {
+ kind, _ := delta["type"].(string)
+ field := ""
+ switch kind {
+ case "text_delta":
+ field = "text"
+ case "thinking_delta":
+ field = "thinking"
+ }
+ value, valued := delta[field].(string)
+ if eventType != "content_block_delta" || field == "" || len(event) != 3 || len(delta) != 2 || !indexed || !valued {
return nil, false
}
- frame := strconv.AppendInt(append(sseFrameStart(eventType, 96+len(text)), `{"type":"content_block_delta","index":`...), int64(index), 10)
- frame = appendJSONString(append(frame, `,"delta":{"type":"text_delta","text":`...), text)
+ frame := strconv.AppendInt(append(sseFrameStart(eventType, 96+len(value)), `{"type":"content_block_delta","index":`...), int64(index), 10)
+ frame = append(append(append(append(frame, `,"delta":{"type":"`...), kind...), `","`...), field...)
+ frame = appendJSONString(append(frame, `":`...), value)
return append(frame, "}}\n\n"...), true
}
@@ -1325,8 +1335,8 @@ type anthropicStreamWriter struct {
}
// streamAnthropic 写出流式事件
-func (s *server) streamAnthropic(r *http.Request, writer *anthropicStreamWriter, events <-chan aistudio.Event) {
- result, err := consumeStreamEvents(r.Context(), events, writer.live)
+func (s *server) streamAnthropic(r *http.Request, writer *anthropicStreamWriter, events eventStream) {
+ result, err := collectStreamEvents(r.Context(), events, writer.live, false)
if err != nil {
if shouldWriteRequestError(r, err) {
_ = writer.error(err)
diff --git a/internal/api/audio_encode.go b/internal/api/audio_encode.go
index e72f609f..c1ced9ba 100644
--- a/internal/api/audio_encode.go
+++ b/internal/api/audio_encode.go
@@ -9,15 +9,15 @@ import (
"mime"
"strconv"
- mp3 "github.com/Mag1cFall/go-mp3"
- mp3pcm "github.com/Mag1cFall/go-mp3/pcm"
"github.com/mewkiz/flac"
"github.com/mewkiz/flac/frame"
"github.com/mewkiz/flac/meta"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
aacpcm "github.com/tphakala/go-aac/pcm"
- "github.com/zaf/g711"
+ mp3 "github.com/tphakala/go-mp3"
+ mp3pcm "github.com/tphakala/go-mp3/pcm"
+ "github.com/zaf/g711/v2"
"github.com/Mag1cFall/AIStudio2API/internal/aistudio"
"github.com/Mag1cFall/AIStudio2API/internal/resample"
@@ -141,7 +141,7 @@ func resamplePCM(audio audioPCM, rate int) audioPCM {
// mp3DefaultBitRate 为未指定码率时的 MP3 码率
const mp3DefaultBitRate = 192000
-// encodeMP3 以最接近目标码率的 CBR 码率编码 MPEG-1 Layer III,码率为零时使用 mp3DefaultBitRate,码率搜索使用快速模式
+// encodeMP3 以最接近目标码率的 CBR 码率编码 MPEG-1 Layer III,码率为零时使用 mp3DefaultBitRate
func encodeMP3(audio audioPCM, bitRate int) ([]byte, error) {
if bitRate == 0 {
bitRate = mp3DefaultBitRate
@@ -153,7 +153,7 @@ func encodeMP3(audio audioPCM, bitRate int) ([]byte, error) {
}
}
bitRate = nearest
- encoder, err := mp3.NewEncoder(mp3.EncoderConfig{SampleRate: audio.SampleRate, Channels: audio.Channels, Bitrate: bitRate, RateControl: mp3.RateControlFast})
+ encoder, err := mp3.NewEncoder(mp3.EncoderConfig{SampleRate: audio.SampleRate, Channels: audio.Channels, Bitrate: bitRate})
if err != nil {
return nil, err
}
diff --git a/internal/api/chat_choices.go b/internal/api/chat_choices.go
index 20c2ce0a..92d3d5ef 100644
--- a/internal/api/chat_choices.go
+++ b/internal/api/chat_choices.go
@@ -16,7 +16,7 @@ const maxChatChoices = 128
type chatChoices struct {
ctx context.Context
cancel context.CancelFunc
- events []<-chan aistudio.Event
+ streams []eventStream
err error
once sync.Once
running sync.WaitGroup
@@ -24,7 +24,7 @@ type chatChoices struct {
// startChatChoices 在各自 goroutine 中启动每个 choice 并立即读取其事件,非流式请求等待各 Generate 返回,流式请求等待首个就绪的 choice
func (s *server) startChatChoices(ctx context.Context, request aistudio.GenerateRequest, count int, stream bool) *chatChoices {
- choices := &chatChoices{events: make([]<-chan aistudio.Event, count)}
+ choices := &chatChoices{streams: make([]eventStream, count)}
choices.ctx, choices.cancel = context.WithCancel(ctx)
started := make(chan error, count)
for index := range count {
@@ -38,12 +38,12 @@ func (s *server) startChatChoices(ctx context.Context, request aistudio.Generate
}
}
events := make(chan aistudio.Event)
- choices.events[index] = events
+ choices.streams[index] = eventStream{ch: events}
choices.running.Add(1)
go func() {
defer choices.running.Done()
upstream, err := s.generate(choices.ctx, choice)
- source := upstream
+ source := eventStream{ch: upstream}
if err == nil && stream {
source, _, err = awaitStreamStart(choices.ctx, upstream)
}
@@ -52,7 +52,7 @@ func (s *server) startChatChoices(ctx context.Context, request aistudio.Generate
failed := make(chan aistudio.Event, 1)
failed <- aistudio.Event{Kind: aistudio.EventError, Err: err}
close(failed)
- source = failed
+ source = eventStream{ch: failed}
}
relayEvents(choices.ctx, source, events)
if upstream != nil {
@@ -74,15 +74,26 @@ func (s *server) startChatChoices(ctx context.Context, request aistudio.Generate
return choices
}
-// relayEvents 经内存队列把 source 的事件转发到 out,已发出的槽位清空,队列发空时从头复用
-func relayEvents(ctx context.Context, source <-chan aistudio.Event, out chan<- aistudio.Event) {
+// relayEventBufferLimit 是 relayEvents 内存队列的事件数上限,队列满时暂停读取上游
+const relayEventBufferLimit = 256
+
+// relayEvents 经内存队列把 source 的事件转发到 out,已发出的槽位清空,队列发空时从头复用,队列达到上限时暂停读取上游
+func relayEvents(ctx context.Context, source eventStream, out chan<- aistudio.Event) {
var queue []aistudio.Event
- for source != nil || len(queue) > 0 {
+ if source.hasFirst {
+ queue = append(queue, source.first)
+ }
+ upstream := source.ch
+ for upstream != nil || len(queue) > 0 {
var send chan<- aistudio.Event
var next aistudio.Event
if len(queue) > 0 {
send, next = out, queue[0]
}
+ receive := upstream
+ if len(queue) >= relayEventBufferLimit {
+ receive = nil
+ }
select {
case <-ctx.Done():
return
@@ -93,9 +104,9 @@ func relayEvents(ctx context.Context, source <-chan aistudio.Event, out chan<- a
} else {
queue = queue[1:]
}
- case event, ok := <-source:
+ case event, ok := <-receive:
if !ok {
- source = nil
+ upstream = nil
continue
}
queue = append(queue, event)
@@ -113,14 +124,14 @@ func (choices *chatChoices) fail(err error) {
}
// run 并发消费各 choice 的事件流并按 index 返回结果
-func (choices *chatChoices) run(consume func(int, <-chan aistudio.Event) (generationResult, error)) ([]generationResult, error) {
- results := make([]generationResult, len(choices.events))
+func (choices *chatChoices) run(consume func(int, eventStream) (generationResult, error)) ([]generationResult, error) {
+ results := make([]generationResult, len(choices.streams))
var wait sync.WaitGroup
- for index, events := range choices.events {
+ for index, stream := range choices.streams {
wait.Add(1)
go func() {
defer wait.Done()
- result, err := consume(index, events)
+ result, err := consume(index, stream)
if err != nil {
choices.fail(err)
}
@@ -134,7 +145,7 @@ func (choices *chatChoices) run(consume func(int, <-chan aistudio.Event) (genera
// settle 取消未结束的生成;多个 choice 时等待各生成退出,再把访问日志的错误设为首个错误
func (choices *chatChoices) settle(ctx context.Context) {
choices.cancel()
- if len(choices.events) < 2 {
+ if len(choices.streams) < 2 {
return
}
choices.running.Wait()
@@ -143,7 +154,7 @@ func (choices *chatChoices) settle(ctx context.Context) {
// record 在多个 choice 时把用量与工具调用数之和写入访问日志
func (choices *chatChoices) record(ctx context.Context, results []generationResult) {
- if len(choices.events) < 2 {
+ if len(choices.streams) < 2 {
return
}
toolCalls := 0
diff --git a/internal/api/errors.go b/internal/api/errors.go
index 2911cf5e..fe76e672 100644
--- a/internal/api/errors.go
+++ b/internal/api/errors.go
@@ -14,6 +14,7 @@ import (
"strconv"
"strings"
"time"
+ "unicode/utf8"
"github.com/Mag1cFall/AIStudio2API/internal/aistudio"
"github.com/Mag1cFall/AIStudio2API/internal/i18n"
@@ -122,10 +123,57 @@ func writeSSEFrame(w http.ResponseWriter, frame []byte) error {
return http.NewResponseController(w).Flush()
}
-// appendJSONString 追加按 json.Marshal 转义的 JSON 字符串
+// jsonHex 是 JSON 转义用的小写十六进制数字
+const jsonHex = "0123456789abcdef"
+
+// appendJSONString 追加与 json.Marshal 逐字节相同的 JSON 字符串:转义引号、反斜杠、控制字符、HTML 字符与 U+2028、U+2029,无效 UTF-8 替换为 U+FFFD
func appendJSONString(buffer []byte, value string) []byte {
- encoded, _ := json.Marshal(value)
- return append(buffer, encoded...)
+ buffer = append(buffer, '"')
+ start := 0
+ for index := 0; index < len(value); {
+ if b := value[index]; b < utf8.RuneSelf {
+ if b >= 0x20 && b != '"' && b != '\\' && b != '<' && b != '>' && b != '&' {
+ index++
+ continue
+ }
+ buffer = append(buffer, value[start:index]...)
+ switch b {
+ case '"', '\\':
+ buffer = append(buffer, '\\', b)
+ case '\b':
+ buffer = append(buffer, '\\', 'b')
+ case '\f':
+ buffer = append(buffer, '\\', 'f')
+ case '\n':
+ buffer = append(buffer, '\\', 'n')
+ case '\r':
+ buffer = append(buffer, '\\', 'r')
+ case '\t':
+ buffer = append(buffer, '\\', 't')
+ default:
+ buffer = append(buffer, '\\', 'u', '0', '0', jsonHex[b>>4], jsonHex[b&0xF])
+ }
+ index++
+ start = index
+ continue
+ }
+ r, size := utf8.DecodeRuneInString(value[index:])
+ if r == utf8.RuneError && size == 1 || r == '\u2028' || r == '\u2029' {
+ buffer = append(buffer, value[start:index]...)
+ if r == utf8.RuneError {
+ buffer = append(buffer, "\ufffd"...)
+ } else {
+ buffer = append(buffer, `\u202`...)
+ buffer = append(buffer, jsonHex[r&0xF])
+ }
+ index += size
+ start = index
+ continue
+ }
+ index += size
+ }
+ buffer = append(buffer, value[start:]...)
+ return append(buffer, '"')
}
// writeSSEText 写入文本事件并刷新网络缓冲
@@ -195,7 +243,7 @@ func codeFromError(err error, defaultCode string) string {
// requestProtocol 返回请求路径与请求头所属的公开协议:gemini、anthropic 或 openai
func requestProtocol(r *http.Request) string {
switch {
- case strings.HasPrefix(r.URL.Path, "/v1beta/"), strings.HasPrefix(r.URL.Path, "/upload/"), interactionsPath(r.URL.Path), geminiV1Path(r):
+ case strings.HasPrefix(r.URL.Path, "/v1beta/"), strings.HasPrefix(r.URL.Path, "/upload/"), strings.HasPrefix(r.URL.Path, "/ws/"), interactionsPath(r.URL.Path), geminiV1Path(r):
return "gemini"
case strings.HasPrefix(r.URL.Path, "/v1/messages"), r.Header.Get("Anthropic-Version") != "":
return "anthropic"
@@ -609,49 +657,39 @@ func anthropicErrorType(err error) string {
return anthropicStatusErrorType(statusFromError(err))
}
+var anthropicStatusTypes = map[int]string{
+ http.StatusBadRequest: "invalid_request_error",
+ http.StatusUnauthorized: "authentication_error",
+ http.StatusForbidden: "permission_error",
+ http.StatusNotFound: "not_found_error",
+ http.StatusRequestEntityTooLarge: "request_too_large",
+ http.StatusTooManyRequests: "rate_limit_error",
+ http.StatusGatewayTimeout: "timeout_error",
+ 529: "overloaded_error",
+}
+
// anthropicStatusErrorType 返回 HTTP 状态对应的 Anthropic 错误类型
func anthropicStatusErrorType(status int) string {
- switch status {
- case http.StatusBadRequest:
- return "invalid_request_error"
- case http.StatusUnauthorized:
- return "authentication_error"
- case http.StatusForbidden:
- return "permission_error"
- case http.StatusNotFound:
- return "not_found_error"
- case http.StatusRequestEntityTooLarge:
- return "request_too_large"
- case http.StatusTooManyRequests:
- return "rate_limit_error"
- case http.StatusGatewayTimeout:
- return "timeout_error"
- case 529:
- return "overloaded_error"
- default:
- return "api_error"
+ if kind, ok := anthropicStatusTypes[status]; ok {
+ return kind
}
+ return "api_error"
+}
+
+var geminiErrorStatuses = map[int]string{
+ http.StatusBadRequest: "INVALID_ARGUMENT",
+ http.StatusUnauthorized: "UNAUTHENTICATED",
+ http.StatusForbidden: "PERMISSION_DENIED",
+ http.StatusNotFound: "NOT_FOUND",
+ http.StatusConflict: "ALREADY_EXISTS",
+ http.StatusTooManyRequests: "RESOURCE_EXHAUSTED",
+ http.StatusServiceUnavailable: "UNAVAILABLE",
+ http.StatusGatewayTimeout: "DEADLINE_EXCEEDED",
}
func geminiErrorStatus(err error) string {
- switch statusFromError(err) {
- case http.StatusBadRequest:
- return "INVALID_ARGUMENT"
- case http.StatusUnauthorized:
- return "UNAUTHENTICATED"
- case http.StatusForbidden:
- return "PERMISSION_DENIED"
- case http.StatusNotFound:
- return "NOT_FOUND"
- case http.StatusConflict:
- return "ALREADY_EXISTS"
- case http.StatusTooManyRequests:
- return "RESOURCE_EXHAUSTED"
- case http.StatusServiceUnavailable:
- return "UNAVAILABLE"
- case http.StatusGatewayTimeout:
- return "DEADLINE_EXCEEDED"
- default:
- return "INTERNAL"
+ if status, ok := geminiErrorStatuses[statusFromError(err)]; ok {
+ return status
}
+ return "INTERNAL"
}
diff --git a/internal/api/field_order.go b/internal/api/field_order.go
index ead514ff..e3bf82da 100644
--- a/internal/api/field_order.go
+++ b/internal/api/field_order.go
@@ -23,7 +23,6 @@ type fieldOrder struct {
Opaque []string `json:"opaque"`
global map[string]int
kinds map[string]map[string]int
- protocol string
}
// fieldOrders 是 gemini、chat、responses、anthropic 与 interactions 输出的字段顺序
@@ -35,8 +34,7 @@ func loadFieldOrders() map[string]*fieldOrder {
if err := json.Unmarshal(fieldOrderJSON, &orders); err != nil {
panic(err)
}
- for protocol, order := range orders {
- order.protocol = protocol
+ for _, order := range orders {
order.global = fieldRanks(order.Global)
order.kinds = make(map[string]map[string]int, len(order.Kinds))
for kind, keys := range order.Kinds {
@@ -74,7 +72,7 @@ type anthropicStartUsage struct {
InferenceGeo *string `json:"inference_geo"`
}
-// officialOrder 将响应投影为固定字段结构与动态字段对象
+// officialOrder 把响应中的动态对象按 protocol 的官方字段顺序编码
func officialOrder(protocol string, value any) any {
return fieldOrders[protocol].value(value, "")
}
@@ -102,7 +100,7 @@ func (order *fieldOrder) value(value any, parent string) any {
for key, item := range value {
fields[key] = order.value(item, key)
}
- return order.object(fields, parent)
+ return orderedJSON{fields: fields, order: order, parent: parent}
case map[string]string:
if value == nil {
return value
@@ -111,7 +109,7 @@ func (order *fieldOrder) value(value any, parent string) any {
for key, item := range value {
fields[key] = item
}
- return order.object(fields, parent)
+ return orderedJSON{fields: fields, order: order, parent: parent}
case map[string]json.RawMessage:
if value == nil {
return value
@@ -120,7 +118,7 @@ func (order *fieldOrder) value(value any, parent string) any {
for key, item := range value {
fields[key] = item
}
- return order.object(fields, parent)
+ return orderedJSON{fields: fields, order: order, parent: parent}
case []map[string]any:
if value == nil {
return value
@@ -162,286 +160,6 @@ func (o orderedJSON) MarshalJSONTo(encoder *jsontext.Encoder) error {
return encoder.WriteToken(jsontext.EndObject)
}
-// object 返回固定响应的具名结构体或动态字段对象
-func (order *fieldOrder) object(fields map[string]any, parent string) any {
- switch order.protocol {
- case "chat":
- if mapString(fields, "object") == "chat.completion" {
- return chatCompletionJSON{
- ID: fields["id"],
- Object: fields["object"],
- Created: fields["created"],
- Model: fields["model"],
- Choices: fields["choices"],
- Usage: fields["usage"],
- ServiceTier: fields["service_tier"],
- ProviderModel: fields["provider_model"],
- SystemFingerprint: fields["system_fingerprint"],
- }
- }
- if mapString(fields, "object") == "chat.completion.chunk" {
- return chatChunkJSON{
- ID: fields["id"],
- Object: fields["object"],
- Created: fields["created"],
- Model: fields["model"],
- SystemFingerprint: fields["system_fingerprint"],
- Choices: fields["choices"],
- ProviderModel: fields["provider_model"],
- Usage: fields["usage"],
- }
- }
- case "gemini":
- if fields["modelVersion"] != nil || fields["candidates"] != nil || fields["promptFeedback"] != nil {
- return geminiGenerationJSON{
- Candidates: fields["candidates"],
- PromptFeedback: fields["promptFeedback"],
- UsageMetadata: fields["usageMetadata"],
- ModelVersion: fields["modelVersion"],
- ResponseID: fields["responseId"],
- TurnToken: fields["turnToken"],
- DebugInfo: fields["debugInfo"],
- }
- }
- if parent == "candidates" {
- return geminiCandidateJSON{
- Content: fields["content"],
- FinishReason: fields["finishReason"],
- Index: fields["index"],
- FinishMessage: fields["finishMessage"],
- SafetyRatings: fields["safetyRatings"],
- CitationMetadata: fields["citationMetadata"],
- GroundingMetadata: fields["groundingMetadata"],
- DetailedFinishReason: fields["detailedFinishReason"],
- URLContextMetadata: fields["urlContextMetadata"],
- }
- }
- case "anthropic":
- if mapString(fields, "type") == "message" && mapString(fields, "role") == "assistant" {
- return anthropicMessageJSON{
- ID: fields["id"],
- Type: fields["type"],
- Role: fields["role"],
- Content: fields["content"],
- Model: fields["model"],
- StopReason: fields["stop_reason"],
- StopSequence: fields["stop_sequence"],
- StopDetails: fields["stop_details"],
- Usage: fields["usage"],
- Container: fields["container"],
- ContextManagement: fields["context_management"],
- ProviderFinishReason: fields["provider_finish_reason"],
- ProviderModel: fields["provider_model"],
- }
- }
- case "responses":
- if mapString(fields, "object") == "response" {
- return responsesJSON{
- ID: fields["id"],
- Object: fields["object"],
- CreatedAt: fields["created_at"],
- Status: fields["status"],
- CompletedAt: fields["completed_at"],
- Background: fields["background"],
- Error: fields["error"],
- IncompleteDetails: fields["incomplete_details"],
- Instructions: fields["instructions"],
- MaxOutputTokens: fields["max_output_tokens"],
- MaxToolCalls: fields["max_tool_calls"],
- Model: fields["model"],
- Output: fields["output"],
- ParallelToolCalls: fields["parallel_tool_calls"],
- PreviousResponseID: fields["previous_response_id"],
- Reasoning: fields["reasoning"],
- ServiceTier: fields["service_tier"],
- Temperature: fields["temperature"],
- Text: fields["text"],
- ToolChoice: fields["tool_choice"],
- Tools: fields["tools"],
- TopP: fields["top_p"],
- Truncation: fields["truncation"],
- Usage: fields["usage"],
- Metadata: fields["metadata"],
- OutputText: fields["output_text"],
- ProviderFinishReason: fields["provider_finish_reason"],
- ProviderModel: fields["provider_model"],
- }
- }
- case "interactions":
- if mapString(fields, "object") == "interaction" {
- return interactionJSON{
- Created: fields["created"],
- EnvironmentID: fields["environment_id"],
- ID: fields["id"],
- Model: fields["model"],
- Object: fields["object"],
- PreviousInteractionID: fields["previous_interaction_id"],
- Status: fields["status"],
- Steps: fields["steps"],
- Updated: fields["updated"],
- Usage: fields["usage"],
- }
- }
- case "openai":
- if mapString(fields, "object") == "model" {
- return openAIModelJSON{
- ID: fields["id"],
- Object: fields["object"],
- Created: fields["created"],
- OwnedBy: fields["owned_by"],
- ShutdownDate: fields["shutdown_date"],
- AccessModes: fields["access_modes"],
- Capabilities: fields["capabilities"],
- CapabilityOptions: fields["capability_options"],
- Channels: fields["channels"],
- DefaultThinkingLevel: fields["default_thinking_level"],
- Description: fields["description"],
- InputTokenLimit: fields["input_token_limit"],
- Name: fields["name"],
- OutputTokenLimit: fields["output_token_limit"],
- Paid: fields["paid"],
- SupportedGenerationMethods: fields["supported_generation_methods"],
- ThinkingLevels: fields["thinking_levels"],
- }
- }
- }
- return orderedJSON{fields: fields, order: order, parent: parent}
-}
-
-// chatCompletionJSON 是 Chat 非流式响应
-type chatCompletionJSON struct {
- ID any `json:"id,omitempty"`
- Object any `json:"object,omitempty"`
- Created any `json:"created,omitempty"`
- Model any `json:"model,omitempty"`
- Choices any `json:"choices,omitempty"`
- Usage any `json:"usage,omitempty"`
- ServiceTier any `json:"service_tier,omitempty"`
- ProviderModel any `json:"provider_model,omitempty"`
- SystemFingerprint any `json:"system_fingerprint,omitempty"`
-}
-
-// chatChunkJSON 是 Chat 流式响应块
-type chatChunkJSON struct {
- ID any `json:"id,omitempty"`
- Object any `json:"object,omitempty"`
- Created any `json:"created,omitempty"`
- Model any `json:"model,omitempty"`
- SystemFingerprint any `json:"system_fingerprint,omitempty"`
- Choices any `json:"choices,omitempty"`
- ProviderModel any `json:"provider_model,omitempty"`
- Usage any `json:"usage,omitempty"`
-}
-
-// geminiGenerationJSON 是 Gemini 生成响应
-type geminiGenerationJSON struct {
- Candidates any `json:"candidates,omitempty"`
- PromptFeedback any `json:"promptFeedback,omitempty"`
- UsageMetadata any `json:"usageMetadata,omitempty"`
- ModelVersion any `json:"modelVersion,omitempty"`
- ResponseID any `json:"responseId,omitempty"`
- TurnToken any `json:"turnToken,omitempty"`
- DebugInfo any `json:"debugInfo,omitempty"`
-}
-
-// geminiCandidateJSON 是 Gemini 候选响应
-type geminiCandidateJSON struct {
- Content any `json:"content,omitempty"`
- FinishReason any `json:"finishReason,omitempty"`
- Index any `json:"index,omitempty"`
- FinishMessage any `json:"finishMessage,omitempty"`
- SafetyRatings any `json:"safetyRatings,omitempty"`
- CitationMetadata any `json:"citationMetadata,omitempty"`
- GroundingMetadata any `json:"groundingMetadata,omitempty"`
- DetailedFinishReason any `json:"detailedFinishReason,omitempty"`
- URLContextMetadata any `json:"urlContextMetadata,omitempty"`
-}
-
-// anthropicMessageJSON 是 Anthropic Message 响应
-type anthropicMessageJSON struct {
- ID any `json:"id,omitempty"`
- Type any `json:"type,omitempty"`
- Role any `json:"role,omitempty"`
- Content any `json:"content,omitempty"`
- Model any `json:"model,omitempty"`
- StopReason any `json:"stop_reason,omitempty"`
- StopSequence any `json:"stop_sequence,omitempty"`
- StopDetails any `json:"stop_details,omitempty"`
- Usage any `json:"usage,omitempty"`
- Container any `json:"container,omitempty"`
- ContextManagement any `json:"context_management,omitempty"`
- ProviderFinishReason any `json:"provider_finish_reason,omitempty"`
- ProviderModel any `json:"provider_model,omitempty"`
-}
-
-// responsesJSON 是 Responses 响应资源
-type responsesJSON struct {
- ID any `json:"id,omitempty"`
- Object any `json:"object,omitempty"`
- CreatedAt any `json:"created_at,omitempty"`
- Status any `json:"status,omitempty"`
- CompletedAt any `json:"completed_at,omitempty"`
- Background any `json:"background,omitempty"`
- Error any `json:"error,omitempty"`
- IncompleteDetails any `json:"incomplete_details,omitempty"`
- Instructions any `json:"instructions,omitempty"`
- MaxOutputTokens any `json:"max_output_tokens,omitempty"`
- MaxToolCalls any `json:"max_tool_calls,omitempty"`
- Model any `json:"model,omitempty"`
- Output any `json:"output,omitempty"`
- ParallelToolCalls any `json:"parallel_tool_calls,omitempty"`
- PreviousResponseID any `json:"previous_response_id,omitempty"`
- Reasoning any `json:"reasoning,omitempty"`
- ServiceTier any `json:"service_tier,omitempty"`
- Temperature any `json:"temperature,omitempty"`
- Text any `json:"text,omitempty"`
- ToolChoice any `json:"tool_choice,omitempty"`
- Tools any `json:"tools,omitempty"`
- TopP any `json:"top_p,omitempty"`
- Truncation any `json:"truncation,omitempty"`
- Usage any `json:"usage,omitempty"`
- Metadata any `json:"metadata,omitempty"`
- OutputText any `json:"output_text,omitempty"`
- ProviderFinishReason any `json:"provider_finish_reason,omitempty"`
- ProviderModel any `json:"provider_model,omitempty"`
-}
-
-// interactionJSON 是 Interactions 响应资源
-type interactionJSON struct {
- Created any `json:"created,omitempty"`
- EnvironmentID any `json:"environment_id,omitempty"`
- ID any `json:"id,omitempty"`
- Model any `json:"model,omitempty"`
- Object any `json:"object,omitempty"`
- // PreviousInteractionID 是续接的前序交互
- PreviousInteractionID any `json:"previous_interaction_id,omitempty"`
- Status any `json:"status,omitempty"`
- Steps any `json:"steps,omitempty"`
- Updated any `json:"updated,omitempty"`
- Usage any `json:"usage,omitempty"`
-}
-
-// openAIModelJSON 是 OpenAI 模型资源
-type openAIModelJSON struct {
- ID any `json:"id,omitempty"`
- Object any `json:"object,omitempty"`
- Created any `json:"created,omitempty"`
- OwnedBy any `json:"owned_by,omitempty"`
- ShutdownDate any `json:"shutdown_date,omitempty"`
- AccessModes any `json:"access_modes,omitempty"`
- Capabilities any `json:"capabilities,omitempty"`
- CapabilityOptions any `json:"capability_options,omitempty"`
- Channels any `json:"channels,omitempty"`
- DefaultThinkingLevel any `json:"default_thinking_level,omitempty"`
- Description any `json:"description,omitempty"`
- InputTokenLimit any `json:"input_token_limit,omitempty"`
- Name any `json:"name,omitempty"`
- OutputTokenLimit any `json:"output_token_limit,omitempty"`
- Paid any `json:"paid,omitempty"`
- SupportedGenerationMethods any `json:"supported_generation_methods,omitempty"`
- ThinkingLevels any `json:"thinking_levels,omitempty"`
-}
-
// ranksFor 返回对象所属种类的字段先后:Global 优先,否则按 type、object 或所在字段名查 Kinds
func (order *fieldOrder) ranksFor(object map[string]any, parent string) map[string]int {
if order.global != nil {
diff --git a/internal/api/field_order.json b/internal/api/field_order.json
index 96bdf904..ffbbd7f2 100644
--- a/internal/api/field_order.json
+++ b/internal/api/field_order.json
@@ -1059,6 +1059,7 @@
"model",
"stop_reason",
"stop_sequence",
+ "stop_details",
"usage"
],
"key:usage": [
diff --git a/internal/api/gemini.go b/internal/api/gemini.go
index 53240e34..4596bf03 100644
--- a/internal/api/gemini.go
+++ b/internal/api/gemini.go
@@ -391,7 +391,7 @@ func (s *server) handleGeminiModel(w http.ResponseWriter, r *http.Request) {
}
// geminiServedMethods 是本服务以 Gemini API 形式提供的模型方法
-var geminiServedMethods = []string{"generateContent", "countTokens", "createCachedContent", "embedContent", "batchEmbedContents", "predict", "predictLongRunning", "createDecision"}
+var geminiServedMethods = []string{"generateContent", "countTokens", "createCachedContent", "embedContent", "batchEmbedContents", "predict", "predictLongRunning", "createDecision", "bidiGenerateContent"}
func geminiModelObject(model aistudio.Model) map[string]any {
methods := make([]string, 0, len(model.Methods))
@@ -1389,8 +1389,8 @@ func (s *server) handleGeminiGenerate(w http.ResponseWriter, r *http.Request, re
s.streamGemini(w, r, request, candidates, output)
return
}
- results, err := candidates.run(func(_ int, events <-chan aistudio.Event) (generationResult, error) {
- result, err := consumeEvents(candidates.ctx, events)
+ results, err := candidates.run(func(_ int, stream eventStream) (generationResult, error) {
+ result, err := collectStreamEvents(candidates.ctx, stream, nil, false)
if err == nil && output.audio != nil {
err = result.convertAudio(*output.audio)
}
@@ -1661,7 +1661,10 @@ func geminiGroundingMetadata(metadata aistudio.GroundingMetadata) map[string]any
if support.Segment.Text != "" {
segment["text"] = support.Segment.Text
}
- value := map[string]any{"segment": segment, "groundingChunkIndices": support.ChunkIndices}
+ value := map[string]any{"segment": segment}
+ if len(support.ChunkIndices) > 0 {
+ value["groundingChunkIndices"] = support.ChunkIndices
+ }
if support.Origin != "" {
value["origin"] = support.Origin
}
@@ -1692,34 +1695,20 @@ func geminiGroundingMetadata(metadata aistudio.GroundingMetadata) map[string]any
return output
}
+var geminiUpperReasons = map[string]bool{
+ "max_tokens": true, "language": true, "other": true, "malformed_function_call": true,
+ "unexpected_tool_call": true, "too_many_tool_calls": true, "image_other": true,
+ "no_image": true, "missing_thought_signature": true, "malformed_response": true, "continuation": true,
+}
+
func geminiFinishReason(reason string) string {
- switch reason {
- case "", "stop", "stop_sequence":
+ switch {
+ case reason == "", reason == "stop", reason == "stop_sequence":
return "STOP"
- case "unspecified":
+ case reason == "unspecified":
return "FINISH_REASON_UNSPECIFIED"
- case "max_tokens":
- return "MAX_TOKENS"
- case "language":
- return "LANGUAGE"
- case "other":
- return "OTHER"
- case "malformed_function_call":
- return "MALFORMED_FUNCTION_CALL"
- case "unexpected_tool_call":
- return "UNEXPECTED_TOOL_CALL"
- case "too_many_tool_calls":
- return "TOO_MANY_TOOL_CALLS"
- case "image_other":
- return "IMAGE_OTHER"
- case "no_image":
- return "NO_IMAGE"
- case "missing_thought_signature":
- return "MISSING_THOUGHT_SIGNATURE"
- case "malformed_response":
- return "MALFORMED_RESPONSE"
- case "continuation":
- return "CONTINUATION"
+ case geminiUpperReasons[reason]:
+ return strings.ToUpper(reason)
}
if name, ok := strings.CutPrefix(reason, "provider_"); ok && strings.Trim(name, "abcdefghijklmnopqrstuvwxyz_") == "" {
return strings.ToUpper(name)
@@ -1861,14 +1850,33 @@ func (stream *geminiStream) write(value map[string]any) error {
return stream.writeJSON(data)
}
-// geminiTextChunk 返回只含一段正文的流式响应块,usage 与 turnToken 为空时省略,字节与按官方字段顺序编码的同一对象相同
-func geminiTextChunk(index int, text, model, responseID, turnToken string, usage *aistudio.Usage) ([]byte, error) {
- chunk := appendJSONString(append(make([]byte, 0, 256+len(text)), `{"candidates":[{"content":{"parts":[{"text":`...), text)
+// geminiTextChunk 返回只含一个文本 Part 的流式响应块;Part 只含 text、thought 与 thoughtSignature 时成立,否则 ok 为 false;usage 与 turnToken 为空时省略,字节与按官方字段顺序编码的同一对象相同
+func geminiTextChunk(index int, part map[string]any, model, responseID, turnToken string, usage *aistudio.Usage) (chunk []byte, ok bool, err error) {
+ text, textual := part["text"].(string)
+ thought, thinking := part["thought"].(bool)
+ signature, signed := part["thoughtSignature"].(string)
+ keys := 1
+ if thinking {
+ keys++
+ }
+ if signed {
+ keys++
+ }
+ if !textual || len(part) != keys {
+ return nil, false, nil
+ }
+ chunk = appendJSONString(append(make([]byte, 0, 256+len(text)+len(signature)), `{"candidates":[{"content":{"parts":[{"text":`...), text)
+ if thinking {
+ chunk = strconv.AppendBool(append(chunk, `,"thought":`...), thought)
+ }
+ if signed {
+ chunk = appendJSONString(append(chunk, `,"thoughtSignature":`...), signature)
+ }
chunk = append(strconv.AppendInt(append(chunk, `}],"role":"model"},"index":`...), int64(index), 10), "}]"...)
if usage != nil {
metadata, err := json.Marshal(geminiUsage(usage))
if err != nil {
- return nil, err
+ return nil, false, err
}
chunk = append(append(chunk, `,"usageMetadata":`...), metadata...)
}
@@ -1877,7 +1885,7 @@ func geminiTextChunk(index int, text, model, responseID, turnToken string, usage
if turnToken != "" {
chunk = appendJSONString(append(chunk, `,"turnToken":`...), turnToken)
}
- return append(chunk, '}'), nil
+ return append(chunk, '}'), true, nil
}
// writeJSON 写出一个已编码的响应块
@@ -1938,8 +1946,8 @@ func (s *server) streamGemini(w http.ResponseWriter, r *http.Request, request ai
}
defer stream.close()
write := stream.write
- finalParts := make([][]any, len(candidates.events))
- results, err := candidates.run(func(index int, events <-chan aistudio.Event) (generationResult, error) {
+ finalParts := make([][]any, len(candidates.streams))
+ results, err := candidates.run(func(index int, source eventStream) (generationResult, error) {
send := func(event aistudio.Event) error {
if !event.HasContent() {
return nil
@@ -1957,11 +1965,11 @@ func (s *server) streamGemini(w http.ResponseWriter, r *http.Request, request ai
if event.FrameUsage != nil {
usage = output.cache.usage(event.FrameUsage)
}
- if text, ok := part["text"].(string); ok && len(part) == 1 {
- chunk, err := geminiTextChunk(index, text, cmp.Or(event.ProviderModel, request.Model), cmp.Or(event.ResponseID, request.ID), event.TurnToken, usage)
- if err != nil {
- return err
- }
+ chunk, ok, err := geminiTextChunk(index, part, cmp.Or(event.ProviderModel, request.Model), cmp.Or(event.ResponseID, request.ID), event.TurnToken, usage)
+ if err != nil {
+ return err
+ }
+ if ok {
return stream.writeJSON(chunk)
}
candidate := map[string]any{"index": index, "content": map[string]any{"role": "model", "parts": []any{part}}}
@@ -1975,7 +1983,7 @@ func (s *server) streamGemini(w http.ResponseWriter, r *http.Request, request ai
return write(frame)
}
buffered := false
- result, err := collectStreamEvents(candidates.ctx, events, func(event aistudio.Event) error {
+ result, err := collectStreamEvents(candidates.ctx, source, func(event aistudio.Event) error {
if audio := output.audio; audio != nil && audioEvent(event) {
if output.delivery.audio || !audio.streams(*event.InlineData) {
buffered = true
diff --git a/internal/api/generate.go b/internal/api/generate.go
index dfe359e7..fe5460bd 100644
--- a/internal/api/generate.go
+++ b/internal/api/generate.go
@@ -138,29 +138,42 @@ func mergeURLContext(previous, next []aistudio.URLMetadata) []aistudio.URLMetada
return merged
}
-// awaitStreamStart 在写出流式响应头前等待首个事件,返回重放该事件的事件流与首个事件所在上游帧的用量;首个事件为错误时返回该错误,心跳间隔内没有事件时直接返回原事件流
-func awaitStreamStart(ctx context.Context, events <-chan aistudio.Event) (<-chan aistudio.Event, *aistudio.Usage, error) {
+// eventStream 是上游事件流:hasFirst 为真时先交付 awaitStreamStart 已读出的 first,再交付 ch 中的事件
+type eventStream struct {
+ first aistudio.Event
+ hasFirst bool
+ ch <-chan aistudio.Event
+}
+
+// awaitStreamStart 在写出流式响应头前等待首个事件,返回带该事件的事件流与首个事件所在上游帧的用量;首个事件为错误时返回该错误,心跳间隔内没有事件时返回不带预读事件的事件流
+func awaitStreamStart(ctx context.Context, events <-chan aistudio.Event) (eventStream, *aistudio.Usage, error) {
timer := time.NewTimer(streamHeartbeatInterval)
defer timer.Stop()
- var first aistudio.Event
select {
case <-ctx.Done():
- return nil, nil, ctx.Err()
+ return eventStream{}, nil, ctx.Err()
case <-timer.C:
- return events, nil, nil
+ return eventStream{ch: events}, nil, nil
case event, ok := <-events:
if !ok {
- return nil, nil, errIncompleteStream
+ return eventStream{}, nil, errIncompleteStream
}
if event.Kind == aistudio.EventError {
- return nil, nil, event.Err
+ return eventStream{}, nil, event.Err
}
- first = event
+ return eventStream{first: event, hasFirst: true, ch: events}, event.FrameUsage, nil
+ }
+}
+
+// channel 返回依次交付首个事件与其后事件的通道,没有预读事件时直接返回上游通道
+func (stream eventStream) channel(ctx context.Context) <-chan aistudio.Event {
+ if !stream.hasFirst {
+ return stream.ch
}
replay := make(chan aistudio.Event)
go func() {
defer close(replay)
- for event, ok := first, true; ok; event, ok = <-events {
+ for event, ok := stream.first, true; ok; event, ok = <-stream.ch {
select {
case replay <- event:
case <-ctx.Done():
@@ -168,7 +181,7 @@ func awaitStreamStart(ctx context.Context, events <-chan aistudio.Event) (<-chan
}
}
}()
- return replay, first.FrameUsage, nil
+ return replay
}
// consumeEvents 收集全部事件,不逐个转发
@@ -178,34 +191,46 @@ func consumeEvents(ctx context.Context, events <-chan aistudio.Event) (generatio
// consumeStreamEvents 收集事件并逐个交给 emit
func consumeStreamEvents(ctx context.Context, events <-chan aistudio.Event, emit func(aistudio.Event) error) (generationResult, error) {
- return collectStreamEvents(ctx, events, emit, false)
+ return collectStreamEvents(ctx, eventStream{ch: events}, emit, false)
}
// collectStreamEvents 收集事件并逐个交给 emit,streamed 为真时 emit 写出的正文、思考与内联媒体不留在结果中
-func collectStreamEvents(ctx context.Context, events <-chan aistudio.Event, emit func(aistudio.Event) error, streamed bool) (result generationResult, resultErr error) {
+func collectStreamEvents(ctx context.Context, stream eventStream, emit func(aistudio.Event) error, streamed bool) (result generationResult, resultErr error) {
result.streamed = streamed
defer func() {
SetAccessLogError(ctx, resultErr)
}()
+ handle := func(event aistudio.Event) error {
+ if err := result.apply(event); err != nil {
+ return err
+ }
+ if emit != nil {
+ return emit(event)
+ }
+ return nil
+ }
+ if stream.hasFirst {
+ if err := ctx.Err(); err != nil {
+ return result, err
+ }
+ if err := handle(stream.first); err != nil {
+ return result, err
+ }
+ }
for {
select {
case <-ctx.Done():
return result, ctx.Err()
- case event, ok := <-events:
+ case event, ok := <-stream.ch:
if !ok {
if !result.finished {
return result, errIncompleteStream
}
return result, nil
}
- if err := result.apply(event); err != nil {
+ if err := handle(event); err != nil {
return result, err
}
- if emit != nil {
- if err := emit(event); err != nil {
- return result, err
- }
- }
}
}
}
diff --git a/internal/api/interactions.go b/internal/api/interactions.go
index 9f4d9b19..0493bafb 100644
--- a/internal/api/interactions.go
+++ b/internal/api/interactions.go
@@ -133,7 +133,9 @@ func (s *server) handleInteraction(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(ctx)
events, err := s.generate(ctx, generate)
if err == nil && request.Stream {
- events, _, err = awaitStreamStart(ctx, events)
+ var stream eventStream
+ stream, _, err = awaitStreamStart(ctx, events)
+ events = stream.channel(ctx)
}
if err != nil {
if shouldWriteRequestError(r, err) {
diff --git a/internal/api/keepalive.go b/internal/api/keepalive.go
index 909d7698..6762af15 100644
--- a/internal/api/keepalive.go
+++ b/internal/api/keepalive.go
@@ -32,7 +32,9 @@ func (s *server) nonstreamKeepalive(w http.ResponseWriter, r *http.Request) (htt
return w, func() {}
}
writer := &keepaliveWriter{ResponseWriter: w, ctx: r.Context()}
+ writer.mu.Lock()
writer.timer = time.AfterFunc(streamHeartbeatInterval, writer.beat)
+ writer.mu.Unlock()
return writer, writer.stop
}
@@ -188,6 +190,23 @@ func (writer *streamKeepalive) Write(data []byte) (int, error) {
return writer.ResponseWriter.Write(data)
}
+// writeFrame 与心跳互斥地调用 build 并写出它返回的帧,把下一次心跳推迟到心跳间隔之后
+func (writer *streamKeepalive) writeFrame(build func() ([]byte, error)) error {
+ writer.mu.Lock()
+ defer writer.mu.Unlock()
+ frame, err := build()
+ if err != nil {
+ return err
+ }
+ if !writer.stopped {
+ writer.timer.Reset(streamHeartbeatInterval)
+ }
+ if _, err := writer.ResponseWriter.Write(frame); err != nil {
+ return err
+ }
+ return http.NewResponseController(writer.ResponseWriter).Flush()
+}
+
// FlushError 与心跳互斥地刷新底层 ResponseWriter
func (writer *streamKeepalive) FlushError() error {
writer.mu.Lock()
diff --git a/internal/api/live.go b/internal/api/live.go
index 5aa64813..0a982e10 100644
--- a/internal/api/live.go
+++ b/internal/api/live.go
@@ -17,10 +17,11 @@ import (
)
const (
- bidiWriteTimeout = 10 * time.Second
- bidiCloseTimeout = 5 * time.Second
- bidiSetupTimeout = 10 * time.Second
- bidiMaxClientFrame = 8 << 20
+ bidiWriteTimeout = 10 * time.Second
+ bidiCloseTimeout = 5 * time.Second
+ bidiCloseHandshakeTimeout = time.Second
+ bidiSetupTimeout = 10 * time.Second
+ bidiMaxClientFrame = 8 << 20
)
var bidiUpgrader = websocket.Upgrader{
@@ -36,6 +37,13 @@ type bidiClientMessage struct {
WeightedPrompts []aistudio.WeightedPrompt `json:"weighted_prompts,omitempty"`
MusicConfig json.RawMessage `json:"music_config,omitempty"`
PlaybackControl string `json:"playback_control,omitempty"`
+ // SystemInstruction、Tools 与 GoogleSearch 属于 context_update,字段缺省表示不更新
+ SystemInstruction *string `json:"system_instruction,omitempty"`
+ Tools *[]aistudio.FunctionDeclaration `json:"tools,omitempty"`
+ GoogleSearch *bool `json:"google_search,omitempty"`
+ // Turns 与 TurnComplete 属于 client_content,只由标准 Live 端点填写
+ Turns []aistudio.BidiTurn `json:"-"`
+ TurnComplete bool `json:"-"`
}
type bidiClientSetup struct {
@@ -53,6 +61,11 @@ type bidiClientSetup struct {
ThinkingLevel string `json:"thinking_level,omitempty"`
ContextWindow *aistudio.BidiContextWindow `json:"context_window_compression,omitempty"`
GoogleSearch bool `json:"google_search,omitempty"`
+ ProactiveAudio bool `json:"proactive_audio,omitempty"`
+ ProactiveVideo bool `json:"proactive_video,omitempty"`
+ AffectiveDialog bool `json:"enable_affective_dialog,omitempty"`
+ // TurnCoverage 为 only_activity、all_input 或 audio_activity_and_all_video
+ TurnCoverage string `json:"turn_coverage,omitempty"`
}
type bidiServerMessage struct {
@@ -71,6 +84,21 @@ type bidiServerMessage struct {
Code string `json:"code,omitempty"`
}
+// bidiClientCause 区分客户端输入或发送错误与父上下文的取消
+type bidiClientCause struct{ err error }
+
+func (cause bidiClientCause) Error() string { return cause.err.Error() }
+func (cause bidiClientCause) Unwrap() error { return cause.err }
+
+// bidiClientError 返回由客户端输入或发送失败记录的取消原因,正常取消返回 nil
+func bidiClientError(ctx context.Context) error {
+ var cause bidiClientCause
+ if errors.As(context.Cause(ctx), &cause) {
+ return cause.err
+ }
+ return nil
+}
+
// Hijack 让 WebSocket upgrade 穿过访问日志响应包装器
func (writer *accessLogResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
connection, readWriter, err := http.NewResponseController(writer.ResponseWriter).Hijack()
@@ -118,8 +146,8 @@ func (s *server) serveBidi(w http.ResponseWriter, r *http.Request, mode aistudio
}
_ = connection.SetReadDeadline(time.Time{})
startedAt := time.Now()
- ctx, cancel := context.WithCancel(r.Context())
- defer cancel()
+ ctx, cancel := context.WithCancelCause(r.Context())
+ defer cancel(nil)
clientMessages := make(chan bidiClientMessage, 8)
readerDone := make(chan struct{})
go readBidiClientMessages(ctx, cancel, connection, clientMessages, readerDone)
@@ -127,28 +155,50 @@ func (s *server) serveBidi(w http.ResponseWriter, r *http.Request, mode aistudio
if err != nil {
SetAccessLogError(r.Context(), err)
_ = writeBidiJSON(connection, bidiErrorMessage(err))
- _ = connection.Close()
- cancel()
- waitBidiRoutine(readerDone)
+ finishBidiSession(r, cancel, connection, nil, false, readerDone, nil)
return
}
- clientErrors := make(chan error, 1)
writerDone := make(chan struct{})
senderDone := make(chan struct{})
go s.writeBidiEvents(
- ctx, connection, r, session, startedAt, request.ModelAccessScope != "", clientErrors, writerDone,
+ ctx, connection, r, session.Model(), session.Events(), startedAt, writerDone,
)
go sendBidiClientMessages(
- ctx, cancel, session, inputModalities, len(request.Tools) > 0, clientMessages, clientErrors, senderDone,
+ ctx, cancel, session, inputModalities, len(request.Tools) > 0, clientMessages, senderDone,
)
<-writerDone
- cancel()
- if closeErr := session.Close(); closeErr != nil {
- SetAccessLogError(r.Context(), closeErr)
+ finishBidiSession(r, cancel, connection, session.Close, false, readerDone, senderDone)
+}
+
+// finishBidiSession 取消会话上下文、关闭上游会话并回收读写协程,waitClose 为 true 时先等待对端回应关闭帧至多 1 秒再关闭连接
+func finishBidiSession(
+ r *http.Request,
+ cancel context.CancelCauseFunc,
+ connection *websocket.Conn,
+ closeSession func() error,
+ waitClose bool,
+ readerDone <-chan struct{},
+ senderDone <-chan struct{},
+) {
+ cancel(nil)
+ if waitClose {
+ timer := time.NewTimer(bidiCloseHandshakeTimeout)
+ select {
+ case <-readerDone:
+ timer.Stop()
+ case <-timer.C:
+ }
}
_ = connection.Close()
+ if closeSession != nil {
+ if closeErr := closeSession(); closeErr != nil {
+ SetAccessLogError(r.Context(), closeErr)
+ }
+ }
waitBidiRoutine(readerDone)
- waitBidiRoutine(senderDone)
+ if senderDone != nil {
+ waitBidiRoutine(senderDone)
+ }
}
func bidiRequestFromSetup(
@@ -195,6 +245,16 @@ func bidiRequestFromSetup(
request.ThinkingLevel = strings.ToLower(strings.TrimSpace(setup.ThinkingLevel))
request.ContextWindow = setup.ContextWindow
request.GoogleSearch = setup.GoogleSearch
+ request.ProactiveAudio = setup.ProactiveAudio
+ request.ProactiveVideo = setup.ProactiveVideo
+ request.AffectiveDialog = setup.AffectiveDialog
+ if setup.TurnCoverage != "" {
+ coverage, ok := bidiTurnCoverages[strings.ToLower(strings.TrimSpace(setup.TurnCoverage))]
+ if !ok {
+ return aistudio.BidiRequest{}, nil, fmt.Errorf("%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video", aistudio.ErrInvalidArgument)
+ }
+ request.TurnCoverage = coverage
+ }
if input["audio"] || input["image"] {
request.ModelAccessScope = aistudio.ModelAccessKey("bidi-media", model)
}
@@ -208,8 +268,9 @@ func bidiRequestFromSetup(
if setup.Translation != nil || setup.Transcription != nil {
return aistudio.BidiRequest{}, nil, fmt.Errorf("%w: robotics 不支持 translation 或 transcription", aistudio.ErrInvalidArgument)
}
- if setup.SystemInstruction != "" || setup.Voice != "" || setup.MediaResolution != "" || setup.ThinkingLevel != "" || setup.ContextWindow != nil || setup.GoogleSearch {
- return aistudio.BidiRequest{}, nil, fmt.Errorf("%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search", aistudio.ErrInvalidArgument)
+ if setup.SystemInstruction != "" || setup.Voice != "" || setup.MediaResolution != "" || setup.ThinkingLevel != "" || setup.ContextWindow != nil || setup.GoogleSearch ||
+ setup.ProactiveAudio || setup.ProactiveVideo || setup.AffectiveDialog || setup.TurnCoverage != "" {
+ return aistudio.BidiRequest{}, nil, fmt.Errorf("%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage", aistudio.ErrInvalidArgument)
}
request.ModelAccessScope = aistudio.ModelAccessKey("bidi-media", model)
}
@@ -219,6 +280,9 @@ func bidiRequestFromSetup(
return request, input, nil
}
+// bidiTurnCoverages 是 turn_coverage 取值与上游 RealtimeInputConfig.turn_coverage 枚举值
+var bidiTurnCoverages = map[string]int64{"only_activity": 1, "all_input": 2, "audio_activity_and_all_video": 3}
+
func bidiModalitySet(values []string) (map[string]bool, error) {
if len(values) == 0 {
return nil, fmt.Errorf("%w: modality 列表不能为空", aistudio.ErrInvalidArgument)
@@ -236,19 +300,29 @@ func bidiModalitySet(values []string) (map[string]bool, error) {
func readBidiClientMessages(
ctx context.Context,
- cancel context.CancelFunc,
+ cancel context.CancelCauseFunc,
connection *websocket.Conn,
messages chan<- bidiClientMessage,
done chan<- struct{},
) {
defer close(done)
defer close(messages)
- defer cancel()
+ defer cancel(nil)
for {
var message bidiClientMessage
if err := connection.ReadJSON(&message); err != nil {
- if errors.Is(err, websocket.ErrReadLimit) {
+ var syntax *json.SyntaxError
+ var mismatch *json.UnmarshalTypeError
+ switch {
+ case errors.Is(err, websocket.ErrReadLimit):
closeBidiTooBig(connection)
+ case errors.As(err, &syntax), errors.As(err, &mismatch), errors.Is(err, io.ErrUnexpectedEOF):
+ cancel(bidiClientCause{err: fmt.Errorf("%w: invalid client message: %v", aistudio.ErrInvalidArgument, err)})
+ for {
+ if _, _, readErr := connection.ReadMessage(); readErr != nil {
+ return
+ }
+ }
}
return
}
@@ -275,12 +349,11 @@ func closeBidiTooBig(connection *websocket.Conn) {
func sendBidiClientMessages(
ctx context.Context,
- cancel context.CancelFunc,
+ cancel context.CancelCauseFunc,
session *aistudio.BidiSession,
inputModalities map[string]bool,
toolsEnabled bool,
messages <-chan bidiClientMessage,
- errors chan<- error,
done chan<- struct{},
) {
defer close(done)
@@ -330,6 +403,24 @@ func sendBidiClientMessages(
} else {
err = session.SendToolResponses(ctx, message.ToolResponses)
}
+ case "client_content":
+ if message.Turns == nil {
+ err = fmt.Errorf("%w: unsupported bidi message type %q", aistudio.ErrInvalidArgument, message.Type)
+ } else {
+ err = session.SendClientContent(ctx, message.Turns, message.TurnComplete)
+ }
+ case "context_update":
+ update := aistudio.BidiContextUpdate{SystemInstruction: message.SystemInstruction}
+ if message.Tools != nil || message.GoogleSearch != nil {
+ update.UpdateTools = true
+ if message.Tools != nil {
+ update.Tools = *message.Tools
+ }
+ update.GoogleSearch = message.GoogleSearch != nil && *message.GoogleSearch
+ }
+ if err = session.SendContextUpdate(ctx, update); err == nil && update.UpdateTools {
+ toolsEnabled = len(update.Tools) > 0
+ }
case "music_prompts":
err = session.SendMusicPrompts(ctx, message.WeightedPrompts)
case "music_config":
@@ -342,15 +433,14 @@ func sendBidiClientMessages(
err = session.SendPlaybackControl(ctx, message.PlaybackControl)
case "close":
_ = session.Close()
- cancel()
+ cancel(nil)
return
default:
err = fmt.Errorf("%w: unsupported bidi message type %q", aistudio.ErrInvalidArgument, message.Type)
}
if err != nil {
- select {
- case errors <- err:
- case <-ctx.Done():
+ if !errors.Is(err, context.Canceled) {
+ cancel(bidiClientCause{err: err})
}
return
}
@@ -362,25 +452,24 @@ func (s *server) writeBidiEvents(
ctx context.Context,
connection *websocket.Conn,
r *http.Request,
- session *aistudio.BidiSession,
+ model string,
+ events <-chan aistudio.BidiEvent,
startedAt time.Time,
- mediaScoped bool,
- clientErrors <-chan error,
done chan<- struct{},
) {
defer close(done)
- defer connection.Close()
- if err := writeBidiJSON(connection, bidiServerMessage{Type: "session_opened", Model: session.Model()}); err != nil {
+ if err := writeBidiJSON(connection, bidiServerMessage{Type: "session_opened", Model: model}); err != nil {
return
}
first := true
for {
select {
- case err := <-clientErrors:
- SetAccessLogError(r.Context(), err)
- _ = writeBidiJSON(connection, bidiErrorMessage(err))
- return
- case event, ok := <-session.Events():
+ case event, ok := <-events:
+ if err := bidiClientError(ctx); err != nil {
+ SetAccessLogError(r.Context(), err)
+ _ = writeBidiJSON(connection, bidiErrorMessage(err))
+ return
+ }
if !ok {
return
}
@@ -401,6 +490,10 @@ func (s *server) writeBidiEvents(
return
}
case <-ctx.Done():
+ if err := bidiClientError(ctx); err != nil {
+ SetAccessLogError(r.Context(), err)
+ _ = writeBidiJSON(connection, bidiErrorMessage(err))
+ }
return
}
}
diff --git a/internal/api/live_gemini.go b/internal/api/live_gemini.go
new file mode 100644
index 00000000..7ffbaaa8
--- /dev/null
+++ b/internal/api/live_gemini.go
@@ -0,0 +1,702 @@
+package api
+
+import (
+ "bytes"
+ "cmp"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "image"
+ "image/jpeg"
+ "mime"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/Mag1cFall/AIStudio2API/internal/aistudio"
+ "github.com/Mag1cFall/AIStudio2API/internal/resample"
+ "github.com/gorilla/websocket"
+)
+
+// geminiLiveCloseReasonLimit 是 WebSocket 关闭帧原因的最大字节数,控制帧载荷上限 125 字节减去 2 字节关闭码
+const geminiLiveCloseReasonLimit = 123
+
+// geminiInt64 按 proto3 JSON 读取 64 位整数,数字与带引号的数字字符串都接受
+type geminiInt64 int64
+
+func (value *geminiInt64) UnmarshalJSON(data []byte) error {
+ text := strings.Trim(string(data), `"`)
+ if text == "null" {
+ return nil
+ }
+ parsed, err := strconv.ParseInt(text, 10, 64)
+ if err != nil {
+ return fmt.Errorf("invalid integer %s", data)
+ }
+ *value = geminiInt64(parsed)
+ return nil
+}
+
+// geminiLiveClientMessage 是标准 BidiGenerateContent 的客户端消息,只有一个字段非空
+type geminiLiveClientMessage struct {
+ Setup *geminiLiveSetup `json:"setup"`
+ ClientContent *struct {
+ Turns []geminiContent `json:"turns"`
+ TurnComplete bool `json:"turnComplete"`
+ } `json:"clientContent"`
+ RealtimeInput *struct {
+ Audio *geminiBlobPart `json:"audio"`
+ Video *geminiBlobPart `json:"video"`
+ MediaChunks []geminiBlobPart `json:"mediaChunks"`
+ Text *string `json:"text"`
+ AudioStreamEnd bool `json:"audioStreamEnd"`
+ ActivityStart json.RawMessage `json:"activityStart"`
+ ActivityEnd json.RawMessage `json:"activityEnd"`
+ } `json:"realtimeInput"`
+ ToolResponse *struct {
+ FunctionResponses []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Response json.RawMessage `json:"response"`
+ WillContinue bool `json:"willContinue"`
+ } `json:"functionResponses"`
+ } `json:"toolResponse"`
+ ContextUpdate *struct {
+ SystemInstruction *geminiContent `json:"systemInstruction"`
+ Tools *struct {
+ Tools []map[string]json.RawMessage `json:"tools"`
+ } `json:"tools"`
+ } `json:"contextUpdate"`
+}
+
+// geminiLiveSetup 是标准 BidiGenerateContent 的 setup 消息,只含本服务读取的字段
+type geminiLiveSetup struct {
+ Model string `json:"model"`
+ GenerationConfig struct {
+ ResponseModalities []string `json:"responseModalities"`
+ MediaResolution string `json:"mediaResolution"`
+ SpeechConfig *struct {
+ VoiceConfig *struct {
+ geminiVoiceConfig
+ ReplicatedVoiceConfig json.RawMessage `json:"replicatedVoiceConfig"`
+ } `json:"voiceConfig"`
+ LanguageCode string `json:"languageCode"`
+ } `json:"speechConfig"`
+ ThinkingConfig *struct {
+ ThinkingLevel string `json:"thinkingLevel"`
+ } `json:"thinkingConfig"`
+ EnableAffectiveDialog bool `json:"enableAffectiveDialog"`
+ TranslationConfig *struct {
+ TargetLanguageCode string `json:"targetLanguageCode"`
+ EchoTargetLanguage bool `json:"echoTargetLanguage"`
+ } `json:"translationConfig"`
+ } `json:"generationConfig"`
+ SystemInstruction *geminiContent `json:"systemInstruction"`
+ Tools []map[string]json.RawMessage `json:"tools"`
+ RealtimeInputConfig *struct {
+ TurnCoverage string `json:"turnCoverage"`
+ AutomaticActivityDetection json.RawMessage `json:"automaticActivityDetection"`
+ ActivityHandling string `json:"activityHandling"`
+ } `json:"realtimeInputConfig"`
+ SessionResumption *struct {
+ Handle string `json:"handle"`
+ } `json:"sessionResumption"`
+ ContextWindowCompression *struct {
+ TriggerTokens geminiInt64 `json:"triggerTokens"`
+ SlidingWindow *struct {
+ TargetTokens geminiInt64 `json:"targetTokens"`
+ } `json:"slidingWindow"`
+ } `json:"contextWindowCompression"`
+ InputAudioTranscription *geminiLiveTranscription `json:"inputAudioTranscription"`
+ OutputAudioTranscription *geminiLiveTranscription `json:"outputAudioTranscription"`
+ Proactivity *struct {
+ ProactiveAudio bool `json:"proactiveAudio"`
+ ProactiveVideo bool `json:"proactiveVideo"`
+ } `json:"proactivity"`
+}
+
+// geminiLiveTranscription 是 inputAudioTranscription 与 outputAudioTranscription,对象存在即表示请求转写
+type geminiLiveTranscription struct {
+ LanguageCodes []string `json:"languageCodes"`
+ CustomVocabulary []string `json:"customVocabulary"`
+ Mode string `json:"mode"`
+}
+
+// geminiLiveFunction 是 Live 工具中的函数声明
+type geminiLiveFunction struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Parameters json.RawMessage `json:"parameters"`
+ ParametersJSONSchema json.RawMessage `json:"parametersJsonSchema"`
+ Behavior string `json:"behavior"`
+}
+
+// geminiLiveOutput 是 setup 中请求输出的可选服务端消息
+type geminiLiveOutput struct {
+ inputTranscription bool
+ outputTranscription bool
+ sessionResumption bool
+}
+
+// geminiLiveMediaResolutions 与 geminiLiveTurnCoverages 把标准枚举名换成 /v1/live setup 的取值
+var (
+ geminiLiveMediaResolutions = map[string]string{"MEDIA_RESOLUTION_UNSPECIFIED": "", "MEDIA_RESOLUTION_LOW": "low", "MEDIA_RESOLUTION_MEDIUM": "medium", "MEDIA_RESOLUTION_HIGH": "high"}
+ geminiLiveTurnCoverages = map[string]string{
+ "": "", "TURN_COVERAGE_UNSPECIFIED": "", "TURN_INCLUDES_ONLY_ACTIVITY": "only_activity",
+ "TURN_INCLUDES_ALL_INPUT": "all_input", "TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO": "audio_activity_and_all_video",
+ }
+)
+
+func (s *server) handleGeminiLiveStandard(w http.ResponseWriter, r *http.Request) {
+ service, ok := s.service.(aistudio.BidiService)
+ if !ok {
+ writeGeminiError(w, http.StatusNotImplemented, "UNIMPLEMENTED", "bidi service is unavailable")
+ return
+ }
+ connection, err := bidiUpgrader.Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+ connection.SetReadLimit(bidiMaxClientFrame)
+ _ = connection.SetReadDeadline(time.Now().Add(bidiSetupTimeout))
+ _, frame, err := connection.ReadMessage()
+ if err != nil {
+ if errors.Is(err, websocket.ErrReadLimit) {
+ closeBidiTooBig(connection)
+ return
+ }
+ _ = connection.Close()
+ return
+ }
+ request, output, err := geminiLiveRequest(frame)
+ if err != nil {
+ SetAccessLogError(r.Context(), err)
+ if closeGeminiLive(connection, err) == nil {
+ _ = connection.SetReadDeadline(time.Now().Add(bidiCloseHandshakeTimeout))
+ for {
+ if _, _, readErr := connection.ReadMessage(); readErr != nil {
+ break
+ }
+ }
+ }
+ _ = connection.Close()
+ return
+ }
+ _ = connection.SetReadDeadline(time.Time{})
+ startedAt := time.Now()
+ ctx, cancel := context.WithCancelCause(r.Context())
+ defer cancel(nil)
+ clientMessages := make(chan bidiClientMessage, 8)
+ readerDone := make(chan struct{})
+ go readGeminiLiveMessages(ctx, cancel, connection, clientMessages, readerDone)
+ session, err := service.OpenBidi(ctx, request)
+ if err != nil {
+ if clientErr := bidiClientError(ctx); clientErr != nil {
+ err = clientErr
+ }
+ SetAccessLogError(r.Context(), err)
+ waitClose := closeGeminiLive(connection, err) == nil
+ finishBidiSession(r, cancel, connection, nil, waitClose, readerDone, nil)
+ return
+ }
+ writerDone := make(chan bool, 1)
+ senderDone := make(chan struct{})
+ go s.writeGeminiLiveEvents(ctx, connection, r, session.Events(), startedAt, output, writerDone)
+ go sendBidiClientMessages(
+ ctx, cancel, session, map[string]bool{"text": true, "audio": true, "image": true}, len(request.Tools) > 0, clientMessages, senderDone,
+ )
+ waitClose := <-writerDone
+ finishBidiSession(r, cancel, connection, session.Close, waitClose, readerDone, senderDone)
+}
+
+// geminiLiveRequest 解码首帧 setup,返回会话请求与请求输出的可选消息
+func geminiLiveRequest(frame []byte) (aistudio.BidiRequest, geminiLiveOutput, error) {
+ var message geminiLiveClientMessage
+ if err := geminiLiveDecode(frame, &message); err != nil {
+ return aistudio.BidiRequest{}, geminiLiveOutput{}, err
+ }
+ if message.Setup == nil {
+ return aistudio.BidiRequest{}, geminiLiveOutput{}, fmt.Errorf("%w: 首帧必须是 setup 消息", aistudio.ErrInvalidArgument)
+ }
+ setup, err := geminiLiveBidiSetup(*message.Setup)
+ if err != nil {
+ return aistudio.BidiRequest{}, geminiLiveOutput{}, err
+ }
+ request, _, err := bidiRequestFromSetup(aistudio.BidiModeLive, setup)
+ output := geminiLiveOutput{
+ inputTranscription: message.Setup.InputAudioTranscription != nil, outputTranscription: message.Setup.OutputAudioTranscription != nil,
+ sessionResumption: message.Setup.SessionResumption != nil,
+ }
+ return request, output, err
+}
+
+// geminiLiveDecode 按 proto3 JSON 规则把客户端帧解码到 target,字段名接受下划线与驼峰两种写法
+func geminiLiveDecode(frame []byte, target any) error {
+ camel, err := geminiCamelKeys(frame)
+ if err == nil {
+ err = json.Unmarshal(camel, target)
+ }
+ if err != nil {
+ return fmt.Errorf("%w: 客户端消息无效: %v", aistudio.ErrInvalidArgument, err)
+ }
+ return nil
+}
+
+// geminiLiveBidiSetup 把标准 setup 换成 /v1/live 的 setup,AI Studio 的 Live 不提供的设置返回参数错误
+func geminiLiveBidiSetup(setup geminiLiveSetup) (bidiClientSetup, error) {
+ config := setup.GenerationConfig
+ converted := bidiClientSetup{
+ Type: "setup", Model: strings.TrimPrefix(setup.Model, "models/"), InputModalities: []string{"text", "audio", "image"}, OutputModalities: []string{"audio"},
+ AffectiveDialog: config.EnableAffectiveDialog,
+ }
+ if len(config.ResponseModalities) > 0 {
+ converted.OutputModalities = nil
+ for _, modality := range config.ResponseModalities {
+ converted.OutputModalities = append(converted.OutputModalities, strings.ToLower(modality))
+ }
+ }
+ converted.MediaResolution = geminiLiveEnum(geminiLiveMediaResolutions, config.MediaResolution)
+ if config.ThinkingConfig != nil && config.ThinkingConfig.ThinkingLevel != "THINKING_LEVEL_UNSPECIFIED" {
+ converted.ThinkingLevel = strings.ToLower(config.ThinkingConfig.ThinkingLevel)
+ }
+ if translation := config.TranslationConfig; translation != nil {
+ converted.Translation = &aistudio.BidiTranslationConfig{TargetLanguageCode: translation.TargetLanguageCode, EchoTargetLanguage: translation.EchoTargetLanguage}
+ }
+ if speech := config.SpeechConfig; speech != nil {
+ if speech.LanguageCode != "" && config.TranslationConfig == nil {
+ return bidiClientSetup{}, geminiLiveUnsupported("speechConfig.languageCode")
+ }
+ if voice := speech.VoiceConfig; voice != nil {
+ if rawJSONConfigured(voice.ReplicatedVoiceConfig) {
+ return bidiClientSetup{}, geminiLiveUnsupported("speechConfig.voiceConfig.replicatedVoiceConfig")
+ }
+ name, custom := voice.voices()
+ converted.Voice = cmp.Or(name, custom)
+ }
+ }
+ var err error
+ if converted.SystemInstruction, err = geminiLiveText(setup.SystemInstruction); err != nil {
+ return bidiClientSetup{}, err
+ }
+ if converted.Tools, converted.GoogleSearch, err = geminiLiveTools(setup.Tools); err != nil {
+ return bidiClientSetup{}, err
+ }
+ if input := setup.RealtimeInputConfig; input != nil {
+ if rawJSONConfigured(input.AutomaticActivityDetection) {
+ return bidiClientSetup{}, geminiLiveUnsupported("realtimeInputConfig.automaticActivityDetection")
+ }
+ if input.ActivityHandling != "" && input.ActivityHandling != "ACTIVITY_HANDLING_UNSPECIFIED" {
+ return bidiClientSetup{}, geminiLiveUnsupported("realtimeInputConfig.activityHandling")
+ }
+ converted.TurnCoverage = geminiLiveEnum(geminiLiveTurnCoverages, input.TurnCoverage)
+ }
+ if setup.SessionResumption != nil {
+ converted.SessionToken = setup.SessionResumption.Handle
+ }
+ if compression := setup.ContextWindowCompression; compression != nil {
+ window := aistudio.BidiContextWindow{TriggerTokens: int64(compression.TriggerTokens)}
+ if compression.SlidingWindow != nil {
+ window.TargetTokens = int64(compression.SlidingWindow.TargetTokens)
+ }
+ if window != (aistudio.BidiContextWindow{}) {
+ converted.ContextWindow = &window
+ }
+ }
+ if transcription := setup.InputAudioTranscription; transcription != nil {
+ smart := strings.EqualFold(transcription.Mode, "SMART")
+ if len(transcription.LanguageCodes) > 0 || len(transcription.CustomVocabulary) > 0 || smart {
+ converted.Transcription = &aistudio.BidiTranscriptionConfig{
+ LanguageCodes: transcription.LanguageCodes, CustomVocabulary: transcription.CustomVocabulary, Smart: smart,
+ }
+ }
+ }
+ if proactivity := setup.Proactivity; proactivity != nil {
+ converted.ProactiveAudio, converted.ProactiveVideo = proactivity.ProactiveAudio, proactivity.ProactiveVideo
+ }
+ return converted, nil
+}
+
+// geminiLiveEnum 返回标准枚举名对应的 /v1/live 取值,没有对应时返回小写的原名,由 setup 校验报告
+func geminiLiveEnum(values map[string]string, name string) string {
+ if value, ok := values[name]; ok {
+ return value
+ }
+ return strings.ToLower(name)
+}
+
+// geminiLiveUnsupported 返回 AI Studio 的 Live 不提供某项设置或消息的参数错误
+func geminiLiveUnsupported(name string) error {
+ return fmt.Errorf("%w: AI Studio 的 Live 不提供 %s", aistudio.ErrInvalidArgument, name)
+}
+
+// geminiLiveTexts 取出 Content 中的全部文本 part,遇到非文本 part 返回参数错误
+func geminiLiveTexts(content *geminiContent) ([]string, error) {
+ if content == nil {
+ return nil, nil
+ }
+ texts := make([]string, 0, len(content.Parts))
+ for _, part := range content.Parts {
+ if part.Text == nil {
+ return nil, fmt.Errorf("%w: Live 的指令与对话轮只支持文本 part", aistudio.ErrInvalidArgument)
+ }
+ texts = append(texts, *part.Text)
+ }
+ return texts, nil
+}
+
+// geminiLiveText 把 Content 中的文本 part 以换行连接,没有 Content 时为空
+func geminiLiveText(content *geminiContent) (string, error) {
+ texts, err := geminiLiveTexts(content)
+ if err != nil {
+ return "", err
+ }
+ return strings.Join(texts, "\n"), nil
+}
+
+// geminiLiveTools 取出标准 tools 中的函数声明与 googleSearch,其余工具返回参数错误,函数声明为空时返回空切片
+func geminiLiveTools(tools []map[string]json.RawMessage) ([]aistudio.FunctionDeclaration, bool, error) {
+ functions := []aistudio.FunctionDeclaration{}
+ search := false
+ for _, tool := range tools {
+ for name, raw := range tool {
+ if !rawJSONConfigured(raw) {
+ continue
+ }
+ switch name {
+ case "functionDeclarations":
+ var declarations []geminiLiveFunction
+ if err := json.Unmarshal(raw, &declarations); err != nil {
+ return nil, false, fmt.Errorf("%w: functionDeclarations 无效: %v", aistudio.ErrInvalidArgument, err)
+ }
+ for _, declaration := range declarations {
+ var parameters json.RawMessage
+ if rawJSONConfigured(declaration.ParametersJSONSchema) {
+ parameters = declaration.ParametersJSONSchema
+ } else if rawJSONConfigured(declaration.Parameters) {
+ parameters = declaration.Parameters
+ }
+ functions = append(functions, aistudio.FunctionDeclaration{
+ Name: declaration.Name, Description: declaration.Description, Parameters: parameters, Behavior: declaration.Behavior,
+ })
+ }
+ case "googleSearch":
+ search = true
+ default:
+ return nil, false, fmt.Errorf("%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s", aistudio.ErrInvalidArgument, name)
+ }
+ }
+ }
+ return functions, search, nil
+}
+
+// readGeminiLiveMessages 读取 setup 之后的标准客户端消息,换成 /v1/live 的消息交给发送循环,消息无效时记录取消原因;消息无效或会话已取消时排空直到对端回应关闭帧
+func readGeminiLiveMessages(
+ ctx context.Context,
+ cancel context.CancelCauseFunc,
+ connection *websocket.Conn,
+ messages chan<- bidiClientMessage,
+ done chan<- struct{},
+) {
+ defer close(done)
+ defer close(messages)
+ defer cancel(nil)
+ for {
+ _, frame, err := connection.ReadMessage()
+ if err != nil {
+ if errors.Is(err, websocket.ErrReadLimit) {
+ closeBidiTooBig(connection)
+ }
+ return
+ }
+ converted, err := geminiLiveMessages(frame)
+ if err != nil {
+ cancel(bidiClientCause{err: err})
+ for {
+ if _, _, readErr := connection.ReadMessage(); readErr != nil {
+ return
+ }
+ }
+ }
+ for _, message := range converted {
+ select {
+ case messages <- message:
+ case <-ctx.Done():
+ for {
+ if _, _, readErr := connection.ReadMessage(); readErr != nil {
+ return
+ }
+ }
+ }
+ }
+ }
+}
+
+// geminiLiveMessages 把一条标准客户端消息换成按顺序发送的 /v1/live 消息
+func geminiLiveMessages(frame []byte) ([]bidiClientMessage, error) {
+ var message geminiLiveClientMessage
+ if err := geminiLiveDecode(frame, &message); err != nil {
+ return nil, err
+ }
+ switch {
+ case message.Setup != nil:
+ return nil, fmt.Errorf("%w: setup 只能是首帧", aistudio.ErrInvalidArgument)
+ case message.ClientContent != nil:
+ turns := make([]aistudio.BidiTurn, 0, len(message.ClientContent.Turns))
+ for _, turn := range message.ClientContent.Turns {
+ texts, err := geminiLiveTexts(&turn)
+ if err != nil {
+ return nil, err
+ }
+ turns = append(turns, aistudio.BidiTurn{Role: turn.Role, Texts: texts})
+ }
+ return []bidiClientMessage{{Type: "client_content", Turns: turns, TurnComplete: message.ClientContent.TurnComplete}}, nil
+ case message.RealtimeInput != nil:
+ input := message.RealtimeInput
+ if rawJSONConfigured(input.ActivityStart) || rawJSONConfigured(input.ActivityEnd) {
+ return nil, geminiLiveUnsupported("realtimeInput.activityStart and activityEnd")
+ }
+ blobs := append([]geminiBlobPart(nil), input.MediaChunks...)
+ for _, blob := range []*geminiBlobPart{input.Audio, input.Video} {
+ if blob != nil {
+ blobs = append(blobs, *blob)
+ }
+ }
+ var converted []bidiClientMessage
+ for _, blob := range blobs {
+ media, err := geminiLiveMedia(blob)
+ if err != nil {
+ return nil, err
+ }
+ converted = append(converted, media)
+ }
+ if input.Text != nil {
+ converted = append(converted, bidiClientMessage{Type: "text", Text: *input.Text})
+ }
+ if input.AudioStreamEnd {
+ converted = append(converted, bidiClientMessage{Type: "media_end"})
+ }
+ return converted, nil
+ case message.ToolResponse != nil:
+ results := make([]aistudio.FunctionResult, 0, len(message.ToolResponse.FunctionResponses))
+ for _, response := range message.ToolResponse.FunctionResponses {
+ content := response.Response
+ if len(content) == 0 {
+ content = json.RawMessage("{}")
+ }
+ results = append(results, aistudio.FunctionResult{ID: response.ID, Name: response.Name, Content: content, WillContinue: response.WillContinue})
+ }
+ return []bidiClientMessage{{Type: "tool_response", ToolResponses: results}}, nil
+ case message.ContextUpdate != nil:
+ update := bidiClientMessage{Type: "context_update"}
+ if message.ContextUpdate.SystemInstruction != nil {
+ text, err := geminiLiveText(message.ContextUpdate.SystemInstruction)
+ if err != nil {
+ return nil, err
+ }
+ update.SystemInstruction = &text
+ }
+ if message.ContextUpdate.Tools != nil {
+ functions, search, err := geminiLiveTools(message.ContextUpdate.Tools.Tools)
+ if err != nil {
+ return nil, err
+ }
+ update.Tools, update.GoogleSearch = &functions, &search
+ }
+ return []bidiClientMessage{update}, nil
+ }
+ return nil, fmt.Errorf("%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate", aistudio.ErrInvalidArgument)
+}
+
+// geminiLiveAudioRate 是 /v1/live 音频消息的采样率
+const geminiLiveAudioRate = 16000
+
+// geminiLiveMedia 把标准 realtimeInput 的媒体换成 /v1/live 的音频或图像消息:单声道 audio/pcm 按 rate 参数重采样到 16 kHz,PNG 与 WebP 图片转成 JPEG
+func geminiLiveMedia(blob geminiBlobPart) (bidiClientMessage, error) {
+ mediaType, parameters, err := mime.ParseMediaType(blob.MIMEType)
+ data, decodeErr := decodeBase64Flexible(blob.Data)
+ if err != nil || decodeErr != nil || len(data) == 0 {
+ return bidiClientMessage{}, fmt.Errorf("%w: realtimeInput 的媒体需要 mimeType 与 base64 data", aistudio.ErrInvalidArgument)
+ }
+ switch mediaType {
+ case "audio/pcm":
+ rate := geminiLiveAudioRate
+ if value := parameters["rate"]; value != "" {
+ rate, err = strconv.Atoi(value)
+ }
+ if err == nil && rate > 0 {
+ if rate != geminiLiveAudioRate {
+ data = resample.PCM(data, 1, rate, geminiLiveAudioRate)
+ }
+ return bidiClientMessage{Type: "audio", MIMEType: mediaType, Data: data}, nil
+ }
+ case "image/jpeg":
+ return bidiClientMessage{Type: "image", MIMEType: mediaType, Data: data}, nil
+ case "image/png", "image/webp":
+ if decoded, _, err := image.Decode(bytes.NewReader(data)); err == nil {
+ var encoded bytes.Buffer
+ if err := jpeg.Encode(&encoded, decoded, &jpeg.Options{Quality: 92}); err == nil {
+ return bidiClientMessage{Type: "image", MIMEType: "image/jpeg", Data: encoded.Bytes()}, nil
+ }
+ }
+ }
+ return bidiClientMessage{}, fmt.Errorf("%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片", aistudio.ErrInvalidArgument)
+}
+
+func (s *server) writeGeminiLiveEvents(
+ ctx context.Context,
+ connection *websocket.Conn,
+ r *http.Request,
+ events <-chan aistudio.BidiEvent,
+ startedAt time.Time,
+ output geminiLiveOutput,
+ done chan<- bool,
+) {
+ waitClose := false
+ defer func() { done <- waitClose }()
+ closeWith := func(err error) {
+ if err != nil {
+ SetAccessLogError(r.Context(), err)
+ }
+ waitClose = closeGeminiLive(connection, err) == nil
+ }
+ first := true
+ for {
+ select {
+ case event, ok := <-events:
+ if err := bidiClientError(ctx); err != nil {
+ closeWith(err)
+ return
+ }
+ if !ok {
+ if ctx.Err() == nil {
+ closeWith(nil)
+ }
+ return
+ }
+ if first {
+ SetAccessLogFirstEvent(r.Context(), time.Since(startedAt), 0)
+ first = false
+ }
+ if event.Err != nil {
+ closeWith(event.Err)
+ return
+ }
+ if event.Kind == aistudio.BidiEventClosed {
+ closeWith(nil)
+ return
+ }
+ message, ok := geminiLiveEventMessage(event, output)
+ if !ok {
+ continue
+ }
+ payload, err := json.Marshal(message)
+ if err == nil {
+ err = connection.SetWriteDeadline(time.Now().Add(bidiWriteTimeout))
+ }
+ if err == nil {
+ err = connection.WriteMessage(websocket.BinaryMessage, payload)
+ }
+ if err != nil {
+ return
+ }
+ case <-ctx.Done():
+ if err := bidiClientError(ctx); err != nil {
+ closeWith(err)
+ }
+ return
+ }
+ }
+}
+
+// geminiLiveEventMessage 把会话事件换成标准服务端消息,没有对应消息或客户端没有请求时返回 false
+func geminiLiveEventMessage(event aistudio.BidiEvent, output geminiLiveOutput) (map[string]any, bool) {
+ content := func(fields map[string]any) (map[string]any, bool) {
+ return map[string]any{"serverContent": fields}, true
+ }
+ transcript := func() map[string]any {
+ fields := map[string]any{"text": event.Text}
+ if transcription := event.Transcription; transcription != nil {
+ if transcription.Finished {
+ fields["finished"] = true
+ }
+ if transcription.LanguageCode != "" {
+ fields["languageCode"] = transcription.LanguageCode
+ }
+ }
+ return fields
+ }
+ modelTurn := func(part map[string]any) (map[string]any, bool) {
+ return content(map[string]any{"modelTurn": map[string]any{"parts": []any{part}}})
+ }
+ switch event.Kind {
+ case aistudio.BidiEventSetupComplete:
+ return map[string]any{"setupComplete": map[string]any{}}, true
+ case aistudio.BidiEventText:
+ return modelTurn(map[string]any{"text": event.Text})
+ case aistudio.BidiEventMedia:
+ return modelTurn(map[string]any{"inlineData": map[string]any{"mimeType": event.Media.MIME, "data": event.Media.Data}})
+ case aistudio.BidiEventInputTranscription:
+ if output.inputTranscription {
+ return content(map[string]any{"inputTranscription": transcript()})
+ }
+ case aistudio.BidiEventInterimInputTranscription:
+ if output.inputTranscription {
+ return content(map[string]any{"interimInputTranscription": transcript()})
+ }
+ case aistudio.BidiEventOutputTranscription:
+ if output.outputTranscription {
+ return content(map[string]any{"outputTranscription": transcript()})
+ }
+ case aistudio.BidiEventGenerationComplete:
+ return content(map[string]any{"generationComplete": true})
+ case aistudio.BidiEventTurnComplete:
+ return content(map[string]any{"turnComplete": true})
+ case aistudio.BidiEventInterrupted:
+ return content(map[string]any{"interrupted": true})
+ case aistudio.BidiEventToolCall:
+ call := event.ToolCall
+ return map[string]any{"toolCall": map[string]any{"functionCalls": []any{map[string]any{"id": call.ID, "name": call.Name, "args": call.Arguments}}}}, true
+ case aistudio.BidiEventToolCallCancellation:
+ return map[string]any{"toolCallCancellation": map[string]any{"ids": event.ToolCallIDs}}, true
+ case aistudio.BidiEventSessionResumption:
+ if output.sessionResumption {
+ return map[string]any{"sessionResumptionUpdate": map[string]any{"newHandle": event.SessionToken, "resumable": event.Resumable}}, true
+ }
+ }
+ return nil, false
+}
+
+// closeGeminiLive 发送官方 Live API 的关闭控制帧:err 为空时正常关闭,否则按错误状态选关闭码并附英文原因
+// 约束:关闭帧原因不超过 geminiLiveCloseReasonLimit 字节;不等待对端回应关闭帧,也不修改连接读期限
+func closeGeminiLive(connection *websocket.Conn, err error) error {
+ code, reason := websocket.CloseNormalClosure, ""
+ if err != nil {
+ code = websocket.CloseInternalServerErr
+ switch statusFromError(err) {
+ case http.StatusBadRequest:
+ code = websocket.CloseInvalidFramePayloadData
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
+ code = websocket.ClosePolicyViolation
+ }
+ reason = geminiLiveCloseReason(publicReason(err))
+ }
+ return connection.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(code, reason), time.Now().Add(bidiWriteTimeout))
+}
+
+// geminiLiveCloseReason 把原因缩到关闭帧上限以内:保留放得下的完整句子,没有句末时按字符截断
+func geminiLiveCloseReason(reason string) string {
+ if len(reason) <= geminiLiveCloseReasonLimit {
+ return reason
+ }
+ head := reason[:geminiLiveCloseReasonLimit]
+ if end := strings.LastIndex(head, ". "); end >= 0 {
+ return head[:end+1]
+ }
+ for !utf8.ValidString(head) {
+ head = head[:len(head)-1]
+ }
+ return head
+}
diff --git a/internal/api/media.go b/internal/api/media.go
index 0f25e29a..b9560516 100644
--- a/internal/api/media.go
+++ b/internal/api/media.go
@@ -233,8 +233,8 @@ func (s *server) generateImages(ctx context.Context, request aistudio.GenerateRe
images.settle(ctx)
return nil, err
}
- results, err := images.run(func(_ int, events <-chan aistudio.Event) (generationResult, error) {
- return consumeEvents(images.ctx, events)
+ results, err := images.run(func(_ int, stream eventStream) (generationResult, error) {
+ return collectStreamEvents(images.ctx, stream, nil, false)
})
images.settle(ctx)
images.record(ctx, results)
diff --git a/internal/api/openai.go b/internal/api/openai.go
index bc0ea7d8..f8041340 100644
--- a/internal/api/openai.go
+++ b/internal/api/openai.go
@@ -285,8 +285,8 @@ func (s *server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
s.streamChatCompletion(w, r, request, requestID, created, choices, media)
return
}
- results, err := choices.run(func(_ int, events <-chan aistudio.Event) (generationResult, error) {
- return consumeEvents(choices.ctx, events)
+ results, err := choices.run(func(_ int, stream eventStream) (generationResult, error) {
+ return collectStreamEvents(choices.ctx, stream, nil, false)
})
if err != nil {
choices.settle(r.Context())
@@ -1240,15 +1240,15 @@ func (s *server) streamChatCompletion(w http.ResponseWriter, r *http.Request, re
defer writing.Unlock()
return writeChatChunk(w, id, created, request.Model, index, delta, finish, request.StreamOptions.IncludeUsage)
}
- for index := range choices.events {
+ for index := range choices.streams {
if err := write(index, map[string]any{"role": "assistant", "content": ""}, nil); err != nil {
return
}
}
format, _, _ := request.audioOutput()
- results, err := choices.run(func(index int, events <-chan aistudio.Event) (generationResult, error) {
+ results, err := choices.run(func(index int, stream eventStream) (generationResult, error) {
choice := &chatStreamChoice{server: s, tools: request.Tools, index: index, write: write, media: media, audioFormat: format, audioID: newID("audio")}
- result, err := consumeStreamEvents(choices.ctx, events, choice.emit)
+ result, err := collectStreamEvents(choices.ctx, stream, choice.emit, false)
if err == nil {
err = choice.finishAudio(result)
}
@@ -1375,8 +1375,12 @@ func (choice *chatStreamChoice) emit(event aistudio.Event) error {
}
func writeChatChunk(w http.ResponseWriter, id string, created int64, model string, index int, delta map[string]any, finish *string, includeUsage bool) error {
- if content, ok := delta["content"].(string); ok && len(delta) == 1 && finish == nil {
- return writeSSEFrame(w, chatTextChunk(id, created, model, index, content, includeUsage))
+ if len(delta) == 1 && finish == nil {
+ for field, value := range delta {
+ if text, ok := value.(string); ok && (field == "content" || field == "reasoning_content") {
+ return writeSSEFrame(w, chatDeltaChunk(id, created, model, index, field, text, includeUsage))
+ }
+ }
}
choice := map[string]any{
"index": index,
@@ -1400,13 +1404,14 @@ func writeChatChunk(w http.ResponseWriter, id string, created int64, model strin
return writeSSE(w, "", officialOrder("chat", chunk))
}
-// chatTextChunk 返回只含正文增量的 chat.completion.chunk SSE 帧,字节与按官方字段顺序编码的同一对象相同
-func chatTextChunk(id string, created int64, model string, index int, content string, includeUsage bool) []byte {
- frame := appendJSONString(append(sseFrameStart("", 160+len(content)), `{"id":`...), id)
+// chatDeltaChunk 返回只含 content 或 reasoning_content 增量的 chat.completion.chunk SSE 帧,字节与按官方字段顺序编码的同一对象相同
+func chatDeltaChunk(id string, created int64, model string, index int, field, value string, includeUsage bool) []byte {
+ frame := appendJSONString(append(sseFrameStart("", 160+len(value)), `{"id":`...), id)
frame = strconv.AppendInt(append(frame, `,"object":"chat.completion.chunk","created":`...), created, 10)
frame = appendJSONString(append(frame, `,"model":`...), model)
frame = strconv.AppendInt(append(frame, `,"choices":[{"index":`...), int64(index), 10)
- frame = append(appendJSONString(append(frame, `,"delta":{"content":`...), content), `},"finish_reason":null}]`...)
+ frame = appendJSONString(append(append(append(frame, `,"delta":{"`...), field...), `":`...), value)
+ frame = append(frame, `},"finish_reason":null}]`...)
if includeUsage {
frame = append(frame, `,"usage":null`...)
}
diff --git a/internal/api/responses.go b/internal/api/responses.go
index fdbdff29..e8ab9d59 100644
--- a/internal/api/responses.go
+++ b/internal/api/responses.go
@@ -456,10 +456,16 @@ func (store *responseStateStore) Store(id string, previous responseHistory, resu
saved, removed := []string{id}, []string(nil)
for len(store.order) > responseStateCapacity {
evicted := store.order[0]
+ store.order[0] = ""
store.order = store.order[1:]
saved = append(saved, store.removeLocked(evicted)...)
removed = append(removed, evicted)
}
+ if cap(store.order) > responseStateCapacity*2 && len(store.order) <= responseStateCapacity {
+ compacted := make([]string, len(store.order), responseStateCapacity+1)
+ copy(compacted, store.order)
+ store.order = compacted
+ }
commit := store.persistLocked(saved, removed)
store.mu.Unlock()
commit()
@@ -470,20 +476,31 @@ func (store *responseStateStore) removeLocked(id string) []string {
parent, _ := store.stateLocked(id)
var children []string
for childID, parentID := range store.parents {
- if parentID != id {
- continue
+ if parentID == id {
+ children = append(children, childID)
}
+ }
+ singleChild := len(children) == 1
+ for _, childID := range children {
child, _ := store.stateLocked(childID)
child.ParentID = parent.ParentID
- child.Contents = append(cloneResponseContents(parent.Contents), child.Contents...)
- child.InlineInstructions = append(append([]string(nil), parent.InlineInstructions...), child.InlineInstructions...)
+ if singleChild {
+ child.Contents = append(parent.Contents, child.Contents...)
+ child.InlineInstructions = append(parent.InlineInstructions, child.InlineInstructions...)
+ } else {
+ child.Contents = append(cloneResponseContents(parent.Contents), child.Contents...)
+ child.InlineInstructions = append(append([]string(nil), parent.InlineInstructions...), child.InlineInstructions...)
+ }
if child.Record != nil && parent.Record != nil {
merged := *child.Record
- merged.Input = append(append(append([]storedItem(nil), parent.Record.Input...), parent.Record.Output...), child.Record.Input...)
+ if singleChild {
+ merged.Input = append(append(parent.Record.Input, parent.Record.Output...), child.Record.Input...)
+ } else {
+ merged.Input = append(append(append([]storedItem(nil), parent.Record.Input...), parent.Record.Output...), child.Record.Input...)
+ }
child.Record = &merged
}
store.putLocked(childID, child)
- children = append(children, childID)
}
delete(store.states, id)
delete(store.parents, id)
@@ -740,8 +757,9 @@ func (s *server) handleResponses(w http.ResponseWriter, r *http.Request) {
generateRequest := prepared.generate
generateRequest.Unary = !request.Stream || s.responseModes().FakeStream
events, err := s.generate(r.Context(), generateRequest)
+ var stream eventStream
if err == nil && request.Stream {
- events, _, err = awaitStreamStart(r.Context(), events)
+ stream, _, err = awaitStreamStart(r.Context(), events)
}
if err != nil {
if shouldWriteRequestError(r, err) {
@@ -751,7 +769,7 @@ func (s *server) handleResponses(w http.ResponseWriter, r *http.Request) {
}
created := time.Now().Unix()
if request.Stream {
- s.streamResponses(w, r, request, prepared, responseID, created, events, compaction)
+ s.streamResponses(w, r, request, prepared, responseID, created, stream, compaction)
return
}
result, err := consumeEvents(r.Context(), events)
@@ -2124,6 +2142,9 @@ func (o *responsesOutput) addSearch(queries []string, grounding *aistudio.Ground
return
}
sources, _ := o.search["sources"].([]map[string]any)
+ if sources == nil {
+ sources = []map[string]any{}
+ }
for _, source := range responseWebSearchSources(*grounding) {
if !slices.ContainsFunc(sources, func(known map[string]any) bool { return known["url"] == source["url"] }) {
sources = append(sources, source)
@@ -2201,7 +2222,7 @@ func newResponsesWriter(w http.ResponseWriter, id string, created int64, request
}
}
-func (s *server) streamResponses(w http.ResponseWriter, r *http.Request, request responsesRequest, prepared responsesPreparation, id string, created int64, events <-chan aistudio.Event, compaction map[string]any) {
+func (s *server) streamResponses(w http.ResponseWriter, r *http.Request, request responsesRequest, prepared responsesPreparation, id string, created int64, events eventStream, compaction map[string]any) {
stream, err := openStream(w, sseHeartbeat)
defer stream.stop()
if err != nil {
@@ -2219,7 +2240,7 @@ func (s *server) streamResponses(w http.ResponseWriter, r *http.Request, request
}
// streamOutput 写出输出项事件与终止事件并保存最终响应,report 决定生成出错时是否写出 response.failed;返回生成或写出的错误
-func (s *server) streamOutput(ctx context.Context, writer *responsesStreamWriter, prepared responsesPreparation, events <-chan aistudio.Event, compaction map[string]any, report func(error) bool) error {
+func (s *server) streamOutput(ctx context.Context, writer *responsesStreamWriter, prepared responsesPreparation, events eventStream, compaction map[string]any, report func(error) bool) error {
writer.prefix = outputPrefix(compaction, prepared)
for index, item := range writer.prefix {
if item["type"] == "mcp_call" {
@@ -2235,7 +2256,7 @@ func (s *server) streamOutput(ctx context.Context, writer *responsesStreamWriter
return err
}
}
- result, err := consumeStreamEvents(ctx, events, writer.live)
+ result, err := collectStreamEvents(ctx, events, writer.live, false)
if err != nil {
if report(err) {
_ = writer.failed(err)
@@ -2273,25 +2294,57 @@ func (writer *responsesStreamWriter) emit(eventType string, payload map[string]a
payload["response"] = responseView(response, writer.request.Include)
}
payload["type"] = eventType
- payload["sequence_number"] = writer.sequence.Add(1) - 1
if writer.w == nil {
+ payload["sequence_number"] = writer.sequence.Add(1) - 1
return nil
}
- return writeSSE(writer.w, eventType, officialOrder("responses", payload))
+ return writer.write(func(sequence int64) ([]byte, error) {
+ payload["sequence_number"] = sequence
+ data, err := json.Marshal(officialOrder("responses", payload))
+ if err != nil {
+ return nil, err
+ }
+ return append(append(sseFrameStart(eventType, len(data)), data...), "\n\n"...), nil
+ })
+}
+
+// write 取下一个序号交给 build 生成帧并写出;流式响应在与心跳互斥的写锁内取号,序号的先后与写出的先后一致
+func (writer *responsesStreamWriter) write(build func(sequence int64) ([]byte, error)) error {
+ next := func() ([]byte, error) { return build(writer.sequence.Add(1) - 1) }
+ if stream, ok := writer.w.(*streamKeepalive); ok {
+ return stream.writeFrame(next)
+ }
+ frame, err := next()
+ if err != nil {
+ return err
+ }
+ return writeSSEFrame(writer.w, frame)
}
-// textDelta 写出正文的 response.output_text.delta 事件,字节与按官方字段顺序编码的同一事件相同
+// textDelta 写出正文的 response.output_text.delta 事件
func (writer *responsesStreamWriter) textDelta(text string) error {
- sequence := writer.sequence.Add(1) - 1
+ return writer.deltaEvent("response.output_text.delta", writer.output.message, `,"content_index":0,"delta":`, text, `,"logprobs":[]`)
+}
+
+// reasoningDelta 写出思考摘要的 response.reasoning_summary_text.delta 事件
+func (writer *responsesStreamWriter) reasoningDelta(text string) error {
+ return writer.deltaEvent("response.reasoning_summary_text.delta", writer.output.reasoning, `,"summary_index":0,"delta":`, text, "")
+}
+
+// deltaEvent 写出 item 的文本增量事件,字节与按官方字段顺序编码的同一事件相同;field 为 sequence_number 之前的字段,tail 为其后的字段
+func (writer *responsesStreamWriter) deltaEvent(eventType string, item map[string]any, field, text, tail string) error {
if writer.w == nil {
+ writer.sequence.Add(1)
return nil
}
- frame := sseFrameStart("response.output_text.delta", 192+len(text))
- frame = appendJSONString(append(frame, `{"type":"response.output_text.delta","item_id":`...), writer.output.message["id"].(string))
- frame = strconv.AppendInt(append(frame, `,"output_index":`...), int64(writer.index(writer.output.message)), 10)
- frame = appendJSONString(append(frame, `,"content_index":0,"delta":`...), text)
- frame = strconv.AppendInt(append(frame, `,"sequence_number":`...), sequence, 10)
- return writeSSEFrame(writer.w, append(frame, `,"logprobs":[]}`+"\n\n"...))
+ return writer.write(func(sequence int64) ([]byte, error) {
+ frame := sseFrameStart(eventType, 192+len(text))
+ frame = appendJSONString(append(append(append(frame, `{"type":"`...), eventType...), `","item_id":`...), item["id"].(string))
+ frame = strconv.AppendInt(append(frame, `,"output_index":`...), int64(writer.index(item)), 10)
+ frame = appendJSONString(append(frame, field...), text)
+ frame = strconv.AppendInt(append(frame, `,"sequence_number":`...), sequence, 10)
+ return append(append(frame, tail...), "}\n\n"...), nil
+ })
}
// index 返回输出项在响应 output 中的位置
@@ -2327,9 +2380,7 @@ func (writer *responsesStreamWriter) live(event aistudio.Event) error {
if event.Text == "" {
return nil
}
- return writer.emit("response.reasoning_summary_text.delta", map[string]any{
- "item_id": writer.output.reasoning["id"], "output_index": writer.index(writer.output.reasoning), "summary_index": 0, "delta": event.Text,
- })
+ return writer.reasoningDelta(event.Text)
case aistudio.EventText:
return writer.textDelta(event.Text)
case aistudio.EventGrounding:
diff --git a/internal/api/responses_background.go b/internal/api/responses_background.go
index 2f2f6590..5f019dbf 100644
--- a/internal/api/responses_background.go
+++ b/internal/api/responses_background.go
@@ -131,7 +131,7 @@ func (s *server) streamBackground(w http.ResponseWriter, r *http.Request, reques
inProgress := responseShell(id, created, "in_progress", request)
s.storeResponse(id, request, prepared, generationResult{}, inProgress)
_ = writer.emit("response.in_progress", map[string]any{"response": inProgress})
- err = s.streamOutput(ctx, writer, prepared, events, compaction, reported)
+ err = s.streamOutput(ctx, writer, prepared, eventStream{ch: events}, compaction, reported)
} else if reported(err) {
_ = writer.failed(err)
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 788ffd55..dd8ec1c6 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -130,6 +130,9 @@ func NewHandler(service aistudio.Service, config Config) http.Handler {
public.HandleFunc("POST /v1/audio/transcriptions", s.handleOpenAITranscription)
public.HandleFunc("POST /v1/audio/translations", s.handleOpenAITranslation)
public.HandleFunc("GET /v1/live", s.handleGeminiLive)
+ for _, version := range []string{"v1beta", "v1alpha", "v1"} {
+ public.HandleFunc("GET /ws/google.ai.generativelanguage."+version+".GenerativeService.BidiGenerateContent", s.handleGeminiLiveStandard)
+ }
public.HandleFunc("GET /v1/robotics/stream", s.handleRoboticsStream)
public.HandleFunc("POST /v1/videos", s.handleOpenAIVideoCreate)
public.HandleFunc("GET /v1/videos", s.handleOpenAIVideoList)
@@ -145,6 +148,7 @@ func NewHandler(service aistudio.Service, config Config) http.Handler {
public.HandleFunc("POST /v1beta/decisions", s.handleDecision)
public.HandleFunc("GET /v1beta/voices", s.handleVoiceList)
public.HandleFunc("POST /v1beta/voices", s.handleVoiceCreate)
+ public.HandleFunc("POST /v1beta/voices:improvePrompt", s.handleVoiceImprove)
public.HandleFunc("GET /v1beta/voices/{voice}", s.handleVoiceGet)
public.HandleFunc("DELETE /v1beta/voices/{voice}", s.handleVoiceDelete)
public.HandleFunc("POST /upload/v1beta/files", s.handleGeminiFileUpload)
@@ -174,6 +178,7 @@ func NewHandler(service aistudio.Service, config Config) http.Handler {
loggedHandler := requestLoggingMiddleware(config.Admin, corsMiddleware(publicHandler))
root.Handle("/v1/", loggedHandler)
root.Handle("/v1beta/", loggedHandler)
+ root.Handle("/ws/", loggedHandler)
root.Handle("/upload/", requestLoggingMiddleware(config.Admin, corsMiddleware(s.geminiUploadHandler(publicHandler))))
s.adminAuth = newAdminAuth(config)
root.Handle("/api/", s.adminAuth.handler(control))
diff --git a/internal/api/voice_store.go b/internal/api/voice_store.go
new file mode 100644
index 00000000..b7ffd752
--- /dev/null
+++ b/internal/api/voice_store.go
@@ -0,0 +1,126 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+)
+
+// voiceStore 是自定义声音目录:每个声音为 .json 与试听音频 .wav
+// 约束:mu 保护目录中文件的读取、写入与删除,避免并发删除时出现部分文件或 Windows 删除挂起错误
+type voiceStore struct {
+ dir string
+ mu sync.RWMutex
+}
+
+// list 返回全部自定义声音,最新的在前
+func (store *voiceStore) list() ([]storedVoice, error) {
+ store.mu.RLock()
+ defer store.mu.RUnlock()
+ entries, err := os.ReadDir(store.dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ voices := make([]storedVoice, 0, len(entries))
+ for _, entry := range entries {
+ if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
+ continue
+ }
+ voice, err := store.read(strings.TrimSuffix(entry.Name(), ".json"))
+ if errors.Is(err, errVoiceNotFound) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ voices = append(voices, voice)
+ }
+ slices.SortFunc(voices, func(a, b storedVoice) int { return b.CreateTime.Compare(a.CreateTime) })
+ return voices, nil
+}
+
+// validVoiceID 判断声音 ID 格式有效且不含路径分隔符
+func validVoiceID(id string) bool {
+ return strings.HasPrefix(id, "voice_") && !strings.ContainsAny(id, `/\.`)
+}
+
+// read 读取一个自定义声音,调用方须持有 store.mu
+func (store *voiceStore) read(id string) (storedVoice, error) {
+ var voice storedVoice
+ if !validVoiceID(id) {
+ return voice, errVoiceNotFound
+ }
+ data, err := os.ReadFile(filepath.Join(store.dir, id+".json"))
+ if errors.Is(err, os.ErrNotExist) {
+ return voice, errVoiceNotFound
+ }
+ if err != nil {
+ return voice, err
+ }
+ return voice, json.Unmarshal(data, &voice)
+}
+
+// get 读取一个自定义声音
+func (store *voiceStore) get(id string) (storedVoice, error) {
+ store.mu.RLock()
+ defer store.mu.RUnlock()
+ return store.read(id)
+}
+
+// getWithSample 读取一个自定义声音与它的试听音频
+func (store *voiceStore) getWithSample(id string) (storedVoice, []byte, error) {
+ store.mu.RLock()
+ defer store.mu.RUnlock()
+ voice, err := store.read(id)
+ if err != nil {
+ return storedVoice{}, nil, err
+ }
+ data, err := os.ReadFile(filepath.Join(store.dir, id+".wav"))
+ if errors.Is(err, os.ErrNotExist) {
+ return storedVoice{}, nil, errVoiceNotFound
+ }
+ return voice, data, err
+}
+
+// save 写入一个自定义声音与它的试听音频
+func (store *voiceStore) save(voice storedVoice, sample []byte) error {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ if err := os.MkdirAll(store.dir, 0o755); err != nil {
+ return err
+ }
+ data, err := json.MarshalIndent(voice, "", " ")
+ if err != nil {
+ return err
+ }
+ if err := os.WriteFile(filepath.Join(store.dir, voice.ID+".wav"), sample, 0o644); err != nil {
+ return err
+ }
+ return os.WriteFile(filepath.Join(store.dir, voice.ID+".json"), data, 0o644)
+}
+
+// remove 删除一个自定义声音
+func (store *voiceStore) remove(id string) error {
+ if !validVoiceID(id) {
+ return errVoiceNotFound
+ }
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ if err := os.Remove(filepath.Join(store.dir, id+".json")); err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return errVoiceNotFound
+ }
+ return err
+ }
+ if err := os.Remove(filepath.Join(store.dir, id+".wav")); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+}
diff --git a/internal/api/voices.go b/internal/api/voices.go
index 2851292a..eb1b59f7 100644
--- a/internal/api/voices.go
+++ b/internal/api/voices.go
@@ -3,14 +3,10 @@ package api
import (
"cmp"
"context"
- "crypto/rand"
- "encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
- "os"
- "path/filepath"
"slices"
"strings"
"sync"
@@ -29,8 +25,10 @@ const voiceSampleText = "Hello! I'm ready to bring your story to life."
var errVoiceNotFound = errors.New("voice not found")
// storedVoice 是本地保存的一个自定义声音:描述作为风格提示,在 BaseVoice 预置音色上生成语音
+// 约束:Type 为空表示 prompted,复刻声音为 replicated,两者的描述都是生成时的风格
type storedVoice struct {
ID string `json:"id"`
+ Type string `json:"type,omitempty"`
DisplayName string `json:"display_name"`
Input string `json:"input"`
BaseVoice string `json:"base_voice"`
@@ -56,91 +54,6 @@ type voiceRankings struct {
entries map[string]*voiceRanking
}
-// voiceStore 是自定义声音目录:每个声音为 .json 与试听音频 .wav
-// 约束:mu 保护目录中文件的写入与删除
-type voiceStore struct {
- dir string
- mu sync.Mutex
-}
-
-// list 返回全部自定义声音,最新的在前
-func (store *voiceStore) list() ([]storedVoice, error) {
- entries, err := os.ReadDir(store.dir)
- if errors.Is(err, os.ErrNotExist) {
- return nil, nil
- }
- if err != nil {
- return nil, err
- }
- voices := make([]storedVoice, 0, len(entries))
- for _, entry := range entries {
- if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
- continue
- }
- voice, err := store.get(strings.TrimSuffix(entry.Name(), ".json"))
- if err != nil {
- return nil, err
- }
- voices = append(voices, voice)
- }
- slices.SortFunc(voices, func(a, b storedVoice) int { return b.CreateTime.Compare(a.CreateTime) })
- return voices, nil
-}
-
-// get 读取一个自定义声音
-func (store *voiceStore) get(id string) (storedVoice, error) {
- var voice storedVoice
- if !strings.HasPrefix(id, "voice_") || strings.ContainsAny(id, `/\.`) {
- return voice, errVoiceNotFound
- }
- data, err := os.ReadFile(filepath.Join(store.dir, id+".json"))
- if errors.Is(err, os.ErrNotExist) {
- return voice, errVoiceNotFound
- }
- if err != nil {
- return voice, err
- }
- return voice, json.Unmarshal(data, &voice)
-}
-
-// sample 读取自定义声音的试听音频
-func (store *voiceStore) sample(id string) ([]byte, error) {
- return os.ReadFile(filepath.Join(store.dir, id+".wav"))
-}
-
-// save 写入一个自定义声音与它的试听音频
-func (store *voiceStore) save(voice storedVoice, sample []byte) error {
- store.mu.Lock()
- defer store.mu.Unlock()
- if err := os.MkdirAll(store.dir, 0o755); err != nil {
- return err
- }
- data, err := json.MarshalIndent(voice, "", " ")
- if err != nil {
- return err
- }
- if err := os.WriteFile(filepath.Join(store.dir, voice.ID+".wav"), sample, 0o644); err != nil {
- return err
- }
- return os.WriteFile(filepath.Join(store.dir, voice.ID+".json"), data, 0o644)
-}
-
-// remove 删除一个自定义声音
-func (store *voiceStore) remove(id string) error {
- if _, err := store.get(id); err != nil {
- return err
- }
- store.mu.Lock()
- defer store.mu.Unlock()
- if err := os.Remove(filepath.Join(store.dir, id+".json")); err != nil {
- return err
- }
- if err := os.Remove(filepath.Join(store.dir, id+".wav")); err != nil && !errors.Is(err, os.ErrNotExist) {
- return err
- }
- return nil
-}
-
// voiceID 去掉声音资源名的 voices/ 前缀
func voiceID(name string) string {
return strings.TrimPrefix(strings.TrimSpace(name), "voices/")
@@ -273,7 +186,7 @@ type voiceAudioData struct {
// customVoiceObject 返回自定义声音的 Voice 资源,sample 非空时带试听音频
func customVoiceObject(voice storedVoice, sample []byte) voiceObject {
object := voiceObject{
- ID: voice.ID, Type: "prompted", DisplayName: voice.DisplayName, Model: "models/" + voice.Model,
+ ID: voice.ID, Type: cmp.Or(voice.Type, "prompted"), DisplayName: voice.DisplayName, Model: "models/" + voice.Model,
LanguageCode: voice.LanguageCode, Prompted: &promptedVoice{Input: voice.Input}, BaseVoice: voice.BaseVoice,
CreateTime: voice.CreateTime.UTC().Format(time.RFC3339),
}
@@ -379,16 +292,11 @@ func (s *server) handleVoiceList(w http.ResponseWriter, r *http.Request) {
// handleVoiceGet 返回一个自定义声音与它的试听音频
func (s *server) handleVoiceGet(w http.ResponseWriter, r *http.Request) {
id := voiceID(r.PathValue("voice"))
- voice, err := s.voices.get(id)
+ voice, sample, err := s.voices.getWithSample(id)
if err != nil {
writeVoiceError(w, id, err)
return
}
- sample, err := s.voices.sample(id)
- if err != nil {
- writeGeminiError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
- return
- }
writeJSON(w, http.StatusOK, customVoiceObject(voice, sample))
}
@@ -411,7 +319,8 @@ func writeVoiceError(w http.ResponseWriter, id string, err error) {
writeGeminiError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
}
-// handleVoiceCreate 按 Gemini API CreateVoice 创建 prompted 声音:挑选最贴近描述的预置音色,以描述为风格生成试听音频后保存
+// handleVoiceCreate 按 Gemini API CreateVoice 创建 prompted 或 replicated 声音:prompted 挑选最贴近描述的预置音色,以描述为风格生成试听音频后保存
+// 约束:voice.base_voice 是服务扩展字段,指定 remix 的基础预置音色或已保存的自定义声音,不指定时按描述挑选
func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
var request struct {
Store *bool `json:"store"`
@@ -420,6 +329,7 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
DisplayName string `json:"display_name"`
Model string `json:"model"`
LanguageCode string `json:"language_code"`
+ BaseVoice string `json:"base_voice"`
Prompted *promptedVoice `json:"prompted"`
Replicated json.RawMessage `json:"replicated"`
} `json:"voice"`
@@ -428,13 +338,17 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", fmt.Sprintf("Invalid JSON payload: %v", err))
return
}
+ if request.Store != nil && !*request.Store {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", "store must be true.")
+ return
+ }
switch strings.ToLower(strings.TrimSpace(request.Voice.Type)) {
case "prompted":
case "replicated":
- writeGeminiError(w, http.StatusBadRequest, "FAILED_PRECONDITION", "Voice replication runs on the Gemini API paid tier and is not available with Google AI plan accounts; create a prompted voice instead.")
+ s.createReplicatedVoice(w, r, request.Voice.DisplayName, request.Voice.Model, request.Voice.LanguageCode, request.Voice.Replicated)
return
default:
- writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", `voice.type must be "prompted".`)
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", `voice.type must be "prompted" or "replicated".`)
return
}
input := ""
@@ -445,10 +359,6 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", "voice.prompted.input is required.")
return
}
- if request.Store != nil && !*request.Store {
- writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", `store must be true when voice.type is "prompted".`)
- return
- }
models, err := s.service.Models(r.Context())
if err != nil {
if shouldWriteRequestError(r, err) {
@@ -461,6 +371,13 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error())
return
}
+ remixed := ""
+ if remix := voiceID(request.Voice.BaseVoice); remix != "" {
+ if remixed, input, err = s.remixBase(model, remix, input); err != nil {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error())
+ return
+ }
+ }
base, line, err := s.pickVoice(r.Context(), model, input)
if err != nil {
if shouldWriteRequestError(r, err) {
@@ -468,6 +385,7 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
}
return
}
+ base = cmp.Or(remixed, base)
sample, err := s.voiceSample(r.Context(), model.ID, base, input, line, request.Voice.LanguageCode)
if err != nil {
if shouldWriteRequestError(r, err) {
@@ -475,10 +393,8 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
}
return
}
- random := make([]byte, 8)
- _, _ = rand.Read(random)
voice := storedVoice{
- ID: "voice_" + hex.EncodeToString(random), DisplayName: cmp.Or(strings.TrimSpace(request.Voice.DisplayName), "Custom Voice"),
+ ID: newCustomVoiceID(), DisplayName: cmp.Or(strings.TrimSpace(request.Voice.DisplayName), "Custom Voice"),
Input: input, BaseVoice: base, Model: model.ID, LanguageCode: strings.TrimSpace(request.Voice.LanguageCode), CreateTime: time.Now(),
}
if err := s.voices.save(voice, sample); err != nil {
@@ -489,6 +405,7 @@ func (s *server) handleVoiceCreate(w http.ResponseWriter, r *http.Request) {
}
// pickVoice 返回这次创建使用的预置音色与试听台词:同一描述首次创建时排名,之后的创建依次取排名中的下一个音色
+// 约束:排名不随发起它的请求取消;请求取消时立即返回,不占用排名中的音色
func (s *server) pickVoice(ctx context.Context, model aistudio.Model, input string) (string, string, error) {
key := model.ID + "\n" + input
rankings := &s.voiceRankings
@@ -503,20 +420,30 @@ func (s *server) pickVoice(ctx context.Context, model aistudio.Model, input stri
}
rankings.mu.Unlock()
if !found {
- ranking.voices, ranking.line, ranking.err = s.rankVoices(ctx, model, input)
- if ranking.err != nil {
- rankings.mu.Lock()
- delete(rankings.entries, key)
- rankings.mu.Unlock()
- }
- close(ranking.ready)
+ detached := context.WithoutCancel(ctx)
+ go func() {
+ ranking.voices, ranking.line, ranking.err = s.rankVoices(detached, model, input)
+ if ranking.err != nil {
+ rankings.mu.Lock()
+ delete(rankings.entries, key)
+ rankings.mu.Unlock()
+ }
+ close(ranking.ready)
+ }()
+ }
+ select {
+ case <-ranking.ready:
+ case <-ctx.Done():
+ return "", "", ctx.Err()
}
- <-ranking.ready
if ranking.err != nil {
return "", "", ranking.err
}
rankings.mu.Lock()
defer rankings.mu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return "", "", err
+ }
voice := ranking.voices[ranking.next%len(ranking.voices)]
ranking.next++
return voice, ranking.line, nil
@@ -525,12 +452,7 @@ func (s *server) pickVoice(ctx context.Context, model aistudio.Model, input stri
// rankVoices 让文本模型从 TTS 模型的目录音色中选出最贴近描述的三个互不相同的预置音色,并写一句符合人设、与描述同语言的试听台词
// 约束:模型给出的不同音色不足三个时,依次补入与第一个音色同性别、再其余的目录音色
func (s *server) rankVoices(ctx context.Context, model aistudio.Model, input string) ([]string, string, error) {
- names := make([]string, 0, len(model.VoiceDetails))
- var catalog strings.Builder
- for _, voice := range model.VoiceDetails {
- names = append(names, voice.Name)
- fmt.Fprintf(&catalog, "%s | %s | pitch %s | %s | %s | %s\n", voice.Name, voice.Gender, voice.Pitch, voice.Accent, strings.Join(voice.Descriptions, " "), voice.Trait)
- }
+ names, catalog := voiceCatalog(model)
if len(names) == 0 {
return nil, "", fmt.Errorf("model %s has no prebuilt voices", model.ID)
}
@@ -539,7 +461,7 @@ func (s *server) rankVoices(ctx context.Context, model aistudio.Model, input str
schema := fmt.Sprintf(`{"type":"object","properties":{"voices":{"type":"array","items":{"type":"string","enum":%s},"minItems":%d,"maxItems":%d},"sample":{"type":"string"}},"required":["voices","sample"]}`, encoded, count, count)
prompt := fmt.Sprintf("Choose the %d different prebuilt TTS voices whose gender, age, pitch and timbre best match the voice description, best match first. ", count) +
"Also write one or two short sentences this character would say to introduce themselves, in the same language as the description.\n\n" +
- "Voice description:\n" + input + "\n\nPrebuilt voices (name | gender | pitch | accent | description | trait):\n" + catalog.String()
+ "Voice description:\n" + input + "\n\nPrebuilt voices (name | gender | pitch | accent | description | trait):\n" + catalog
events, err := s.service.Generate(ctx, aistudio.GenerateRequest{
ID: newID("voice"), Unary: true, Model: voicePickModel,
Contents: []aistudio.Content{{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: prompt}}}},
diff --git a/internal/api/voices_extra.go b/internal/api/voices_extra.go
new file mode 100644
index 00000000..832a55e3
--- /dev/null
+++ b/internal/api/voices_extra.go
@@ -0,0 +1,182 @@
+package api
+
+import (
+ "cmp"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/Mag1cFall/AIStudio2API/internal/aistudio"
+)
+
+// voiceImproveInstruction 是改写声音描述的指令,对应官网 Voice Design 的 Improve my prompt
+const voiceImproveInstruction = "Rewrite this voice description for a text-to-speech voice design model. Keep the character and the language of the description, and make it more specific: timbre and weight, age, gender, pitch, pacing, accent, tone and delivery quirks. Answer with the rewritten description only, as one paragraph.\n\nVoice description:\n"
+
+// voiceReplicaLine 是复刻声音创建完成后的试听台词,与官网复刻视图相同
+const voiceReplicaLine = "Hi there! I am your newly replicated voice ready for text-to-speech."
+
+// newCustomVoiceID 返回一个新的自定义声音 ID
+func newCustomVoiceID() string {
+ random := make([]byte, 8)
+ _, _ = rand.Read(random)
+ return "voice_" + hex.EncodeToString(random)
+}
+
+// voiceCatalog 返回 TTS 模型目录音色的名称与逐行说明,供文本模型挑选
+func voiceCatalog(model aistudio.Model) ([]string, string) {
+ names := make([]string, 0, len(model.VoiceDetails))
+ var catalog strings.Builder
+ for _, voice := range model.VoiceDetails {
+ names = append(names, voice.Name)
+ fmt.Fprintf(&catalog, "%s | %s | pitch %s | %s | %s | %s\n", voice.Name, voice.Gender, voice.Pitch, voice.Accent, strings.Join(voice.Descriptions, " "), voice.Trait)
+ }
+ return names, catalog.String()
+}
+
+// handleVoiceImprove 把声音描述改写得更具体,文本模型没有返回正文时原样返回描述
+func (s *server) handleVoiceImprove(w http.ResponseWriter, r *http.Request) {
+ var request struct {
+ Input string `json:"input"`
+ }
+ if err := decodeJSON(r, &request); err != nil {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", fmt.Sprintf("Invalid JSON payload: %v", err))
+ return
+ }
+ input := strings.TrimSpace(request.Input)
+ if input == "" {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", "input is required.")
+ return
+ }
+ events, err := s.service.Generate(r.Context(), aistudio.GenerateRequest{
+ ID: newID("voice"), Unary: true, Model: voicePickModel,
+ Contents: []aistudio.Content{{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: voiceImproveInstruction + input}}}},
+ })
+ if err == nil {
+ var result generationResult
+ if result, err = consumeEvents(r.Context(), events); err == nil {
+ writeJSON(w, http.StatusOK, map[string]string{"input": cmp.Or(strings.TrimSpace(result.text.String()), input)})
+ return
+ }
+ }
+ if shouldWriteRequestError(r, err) {
+ writeGeminiRequestError(w, err)
+ }
+}
+
+// remixBase 返回 remix 使用的预置音色与风格:基础是预置音色时风格为新描述,基础是已保存的自定义声音时在它的风格上叠加新描述
+func (s *server) remixBase(model aistudio.Model, base, input string) (string, string, error) {
+ if storedVoiceID(base) {
+ stored, err := s.voices.get(base)
+ if err != nil {
+ return "", "", fmt.Errorf("voice.base_voice %q was not found", base)
+ }
+ return stored.BaseVoice, stored.Input + "\n" + input, nil
+ }
+ if !slices.ContainsFunc(model.VoiceDetails, func(voice aistudio.VoiceDetail) bool { return voice.Name == base }) {
+ return "", "", fmt.Errorf("voice.base_voice %q is not a prebuilt voice of model %s", base, model.ID)
+ }
+ return base, input, nil
+}
+
+// replicatedAudio 是复刻声音请求中的一段录音
+type replicatedAudio struct {
+ Data []byte `json:"data"`
+ MIMEType string `json:"mime_type"`
+}
+
+// createReplicatedVoice 按 Gemini API CreateVoice 的 replicated 声音创建声音:文本模型听取样本录音,写出描述并选出最接近的预置音色,之后与 prompted 声音相同
+// 约束:确认录音只检查存在
+func (s *server) createReplicatedVoice(w http.ResponseWriter, r *http.Request, displayName, requestedModel, language string, raw json.RawMessage) {
+ var replicated struct {
+ SourceAudio *replicatedAudio `json:"source_audio"`
+ ConsentAudio *replicatedAudio `json:"consent_audio"`
+ }
+ if len(raw) > 0 {
+ if err := json.Unmarshal(raw, &replicated); err != nil {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", fmt.Sprintf("Invalid voice.replicated: %v", err))
+ return
+ }
+ }
+ if replicated.SourceAudio == nil || len(replicated.SourceAudio.Data) == 0 {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", "voice.replicated.source_audio is required.")
+ return
+ }
+ if replicated.ConsentAudio == nil || len(replicated.ConsentAudio.Data) == 0 {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", "voice.replicated.consent_audio is required.")
+ return
+ }
+ models, err := s.service.Models(r.Context())
+ if err != nil {
+ if shouldWriteRequestError(r, err) {
+ writeGeminiRequestError(w, err)
+ }
+ return
+ }
+ model, err := voiceDesignModel(models, requestedModel)
+ if err != nil {
+ writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error())
+ return
+ }
+ base, description, err := s.describeVoiceSample(r, model, replicated.SourceAudio)
+ if err != nil {
+ if shouldWriteRequestError(r, err) {
+ writeGeminiRequestError(w, err)
+ }
+ return
+ }
+ sample, err := s.voiceSample(r.Context(), model.ID, base, description, voiceReplicaLine, language)
+ if err != nil {
+ if shouldWriteRequestError(r, err) {
+ writeGeminiRequestError(w, err)
+ }
+ return
+ }
+ voice := storedVoice{
+ ID: newCustomVoiceID(), Type: "replicated", DisplayName: cmp.Or(strings.TrimSpace(displayName), "Custom Voice"),
+ Input: description, BaseVoice: base, Model: model.ID, LanguageCode: strings.TrimSpace(language), CreateTime: time.Now(),
+ }
+ if err := s.voices.save(voice, sample); err != nil {
+ writeGeminiError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, customVoiceObject(voice, sample))
+}
+
+// describeVoiceSample 让文本模型听取录音,返回最接近说话人的预置音色与以英文写成的声音描述
+func (s *server) describeVoiceSample(r *http.Request, model aistudio.Model, audio *replicatedAudio) (string, string, error) {
+ names, catalog := voiceCatalog(model)
+ if len(names) == 0 {
+ return "", "", fmt.Errorf("model %s has no prebuilt voices", model.ID)
+ }
+ encoded, _ := json.Marshal(names)
+ schema := fmt.Sprintf(`{"type":"object","properties":{"voice":{"type":"string","enum":%s},"description":{"type":"string"}},"required":["voice","description"]}`, encoded)
+ prompt := "Listen to the voice sample. Describe the speaker's voice as a text-to-speech voice design prompt in two or three English sentences: gender, approximate age, pitch, timbre and weight, accent, pacing, tone and delivery habits. " +
+ "Also choose the prebuilt TTS voice whose gender, age, pitch and timbre are closest to the speaker.\n\nPrebuilt voices (name | gender | pitch | accent | description | trait):\n" + catalog
+ events, err := s.service.Generate(r.Context(), aistudio.GenerateRequest{
+ ID: newID("voice"), Unary: true, Model: voicePickModel,
+ Contents: []aistudio.Content{{Role: aistudio.RoleUser, Parts: []aistudio.Part{
+ {InlineData: &aistudio.Blob{MIME: cmp.Or(audio.MIMEType, "audio/wav"), Data: audio.Data}}, {Text: prompt},
+ }}},
+ Config: aistudio.GenerationConfig{ResponseMIMEType: "application/json", ResponseSchema: json.RawMessage(schema)},
+ })
+ if err != nil {
+ return "", "", err
+ }
+ result, err := consumeEvents(r.Context(), events)
+ if err != nil {
+ return "", "", err
+ }
+ var output struct {
+ Voice string `json:"voice"`
+ Description string `json:"description"`
+ }
+ if json.Unmarshal(result.text.Bytes(), &output) != nil || !slices.Contains(names, output.Voice) || strings.TrimSpace(output.Description) == "" {
+ return "", "", fmt.Errorf("AI Studio could not describe the voice sample: %q", result.text.String())
+ }
+ return output.Voice, strings.TrimSpace(output.Description), nil
+}
diff --git a/internal/app/admin.go b/internal/app/admin.go
index e17db0cf..0a27608d 100644
--- a/internal/app/admin.go
+++ b/internal/app/admin.go
@@ -135,17 +135,24 @@ func (admin *runtimeAdmin) Status(context.Context) (api.AdminStatus, error) {
return status, nil
}
-// Accounts 返回各账户的状态,无法载入的账户目录列为不可用,原因写明出错的文件
-func (admin *runtimeAdmin) Accounts(context.Context) ([]api.AdminAccount, error) {
- statuses := admin.pool.Status()
+// adminAccountsSnapshot 返回账户池脱敏状态与 store 中无法载入的账户目录
+func adminAccountsSnapshot(pool *aistudio.AccountPool, store *aistudio.AccountStore) []api.AdminAccount {
+ statuses := pool.AdminStatus()
accounts := make([]api.AdminAccount, 0, len(statuses))
for _, status := range statuses {
accounts = append(accounts, adminAccountDTO(status))
}
- for _, failure := range admin.store.Failures() {
- accounts = append(accounts, api.AdminAccount{ID: failure.ID, Label: failure.ID, State: string(aistudio.AccountUnavailable), Models: []string{}, Message: failure.Err.Error()})
+ if store != nil {
+ for _, failure := range store.Failures() {
+ accounts = append(accounts, api.AdminAccount{ID: failure.ID, Label: failure.ID, State: string(aistudio.AccountUnavailable), Models: []string{}, CallableModels: []string{}, Message: failure.Err.Error()})
+ }
}
- return accounts, nil
+ return accounts
+}
+
+// Accounts 返回各账户的状态,无法载入的账户目录列为不可用,原因写明出错的文件
+func (admin *runtimeAdmin) Accounts(context.Context) ([]api.AdminAccount, error) {
+ return adminAccountsSnapshot(admin.pool, admin.store), nil
}
// AccountExits 并发查询各账户出口代理的公网 IP 与地理位置,每个代理一行,查询失败的代理带原因
@@ -1582,18 +1589,15 @@ func (admin *runtimeAdmin) publishRuntimeSnapshot(ctx context.Context) api.Admin
defer admin.publishMu.Unlock()
status, _ := admin.Status(ctx)
models, _ := admin.CatalogModels(ctx)
- accounts, _ := admin.Accounts(ctx)
admin.requests.publish(api.AdminEvent{Type: "status", Data: status})
admin.requests.publish(api.AdminEvent{Type: "models", Data: map[string]any{"models": models}})
- admin.requests.publish(api.AdminEvent{Type: "accounts", Data: map[string]any{"accounts": accounts}})
+ admin.requests.publishAccounts(admin.pool, admin.store)
return status
}
func (admin *runtimeAdmin) account(accountID string) (api.AdminAccount, error) {
- for _, status := range admin.pool.Status() {
- if status.ID == accountID {
- return adminAccountDTO(status), nil
- }
+ if status, ok := admin.pool.AdminAccountStatus(accountID); ok {
+ return adminAccountDTO(status), nil
}
return api.AdminAccount{}, accountOperationError(fmt.Errorf("%w: %s", aistudio.ErrAccountNotFound, accountID))
}
@@ -1685,13 +1689,14 @@ func adminAccountDTO(status aistudio.AccountStatus) api.AdminAccount {
account := api.AdminAccount{
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,
+ Models: append([]string{}, 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,
VerificationRequired: status.VerificationRequired,
DeviceBoundSession: status.DeviceBoundSession && !hasPairingRenewal(status.Directory),
MigratedModels: status.MigratedModels,
+ CallableModels: append([]string{}, status.CallableModels...),
}
if status.Transition != "" {
account.TransitionSince = &status.TransitionSince
@@ -1760,6 +1765,10 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt
if err != nil {
return api.RuntimeConfig{}, invalidConfigError(fmt.Errorf("REQUEST_TIMEOUT 无效: %w", err))
}
+ buildChatProtocol := strings.ToLower(strings.TrimSpace(value.BuildChatProtocol))
+ if buildChatProtocol == "" {
+ buildChatProtocol = saved.BuildChatProtocol
+ }
cfg := config.Config{
AutoStart: value.AutoStart,
HideDockIcon: value.HideDockIcon,
@@ -1789,7 +1798,7 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt
WAABackend: value.WAABackend,
MediaOutput: strings.ToLower(strings.TrimSpace(value.MediaOutput)),
MediaBaseURL: strings.TrimSpace(value.MediaBaseURL),
- BuildChatModels: value.BuildChatModels, HideModels: strings.TrimSpace(value.HideModels),
+ BuildChatModels: value.BuildChatModels, BuildChatProtocol: buildChatProtocol, HideModels: strings.TrimSpace(value.HideModels),
GenerateContentAccounts: strings.TrimSpace(value.GenerateContentAccounts), SillyTavernAPIKeys: strings.TrimSpace(value.SillyTavernAPIKeys),
}.KeepEnvironment(saved)
if err := cfg.Validate(); err != nil {
@@ -1881,8 +1890,7 @@ func (admin *runtimeAdmin) ClearCooldown(ctx context.Context, accountID string,
admin.requests.log(account.Label, "INFO", "冷却已手动清除", "scope", scope)
cooldowns, _ := admin.Cooldowns(ctx)
admin.requests.publish(api.AdminEvent{Type: "cooldowns", Data: cooldowns})
- accounts, _ := admin.Accounts(ctx)
- admin.requests.publish(api.AdminEvent{Type: "accounts", Data: map[string]any{"accounts": accounts}})
+ admin.requests.publishAccounts(admin.pool, admin.store)
return nil
}
@@ -2151,7 +2159,7 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig {
MediaBaseURL: cfg.MediaBaseURL,
Environment: append([]string{}, cfg.Environment...),
Invalid: invalidConfigDTO(cfg.Invalid),
- BuildChatModels: cfg.BuildChatModels, HideModels: cfg.HideModels,
+ BuildChatModels: cfg.BuildChatModels, BuildChatProtocol: cfg.BuildChatProtocol, HideModels: cfg.HideModels,
GenerateContentAccounts: cfg.GenerateContentAccounts, SillyTavernAPIKeys: cfg.SillyTavernAPIKeys,
}
}
diff --git a/internal/app/app.go b/internal/app/app.go
index 74549c3b..bd791925 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -376,10 +376,21 @@ func rootHandler(apiHandler http.Handler) http.Handler {
root.Handle("/api/", compressAdmin(apiHandler))
root.Handle("/v1/", apiHandler)
root.Handle("/v1beta/", apiHandler)
+ root.Handle("/ws/", apiHandler)
root.Handle("/upload/", apiHandler)
root.Handle("/media/", apiHandler)
root.Handle("/", webui.Handler())
- return securityHeaders(root)
+ return securityHeaders(cleanLivePath(root))
+}
+
+// cleanLivePath 去掉 //ws/ 开头路径多出的斜杠,官方 SDK 以带尾斜杠的基础地址拼出这样的 Live 路径,ServeMux 对它返回重定向而 WebSocket 客户端不跟随
+func cleanLivePath(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasPrefix(r.URL.Path, "//ws/") {
+ r.URL.Path, r.URL.RawPath = r.URL.Path[1:], ""
+ }
+ next.ServeHTTP(w, r)
+ })
}
// compressAdmin 以 gzip 压缩管理接口发给接受 gzip 的客户端的 JSON、CSV 与事件流响应,媒体流原样输出以支持 Range
diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go
index ce32c840..35632386 100644
--- a/internal/app/auth_retry.go
+++ b/internal/app/auth_retry.go
@@ -25,6 +25,7 @@ const boundRefreshThreshold = 2 * time.Minute
// authRuntimeRefresher 使用账户保存的 Chrome OAuth 材料原地续签
type authRuntimeRefresher struct {
pool *aistudio.AccountPool
+ store *aistudio.AccountStore
refresh chromeCookieRefreshFunc
importCurrent func(context.Context, aistudio.AuthSource, aistudio.ChromeOAuthMaterial, string) (aistudio.StorageState, error)
reset func(string) error
@@ -166,9 +167,15 @@ func (transport *authRetryTransport) ReadDriveFile(ctx context.Context, accountI
transport.transport.(aistudio.DriveFileReader).ReadDriveFile(ctx, accountID, token, fileID)
}
-// UploadAssistantFile 将写代码助手附件上传委托给同一认证传输
+// UploadAssistantFile 将写代码助手附件上传委托给同一认证传输,上传前刷新即将到期的 DBSC 会话,401 后续签同一账户并重放一次
func (transport *authRetryTransport) UploadAssistantFile(ctx context.Context, accountID string, blob aistudio.Blob) (string, error) {
- return transport.transport.(aistudio.AssistantUploader).UploadAssistantFile(ctx, accountID, blob)
+ var path string
+ _, err := transport.refresher.do(ctx, "Upload", func() (*aistudio.RPCResponse, error) {
+ var err error
+ path, err = transport.transport.(aistudio.AssistantUploader).UploadAssistantFile(ctx, accountID, blob)
+ return &aistudio.RPCResponse{StatusCode: http.StatusOK}, err
+ })
+ return path, err
}
// newAuthRuntimeRefresher 创建生产环境认证续签器
@@ -228,12 +235,7 @@ func (refresher *authRuntimeRefresher) markAuthenticationRequired(ctx context.Co
return cause
}
err := lease.ConfirmAuthenticationFailure(ctx, cause)
- statuses := refresher.pool.Status()
- accounts := make([]api.AdminAccount, 0, len(statuses))
- for _, status := range statuses {
- accounts = append(accounts, adminAccountDTO(status))
- }
- refresher.requests.publish(api.AdminEvent{Type: "accounts", Data: map[string]any{"accounts": accounts}})
+ refresher.requests.publishAccounts(refresher.pool, refresher.store)
return errors.Join(cause, err)
}
@@ -500,19 +502,19 @@ func (refresher *authRuntimeRefresher) ensureBoundAccount(ctx context.Context, a
if refresher.pool == nil {
return nil
}
- account, err := refresher.pool.Account(accountID)
+ proxy, err := refresher.pool.EffectiveProxy(accountID, refresher.currentGlobalProxy())
if err != nil {
return err
}
return refresher.ensureBoundWith(
ctx,
- account.ID,
- account.EffectiveProxy(refresher.currentGlobalProxy()),
+ accountID,
+ proxy,
func() (aistudio.StorageState, error) {
- return refresher.pool.ReloadStorageState(account.ID)
+ return refresher.pool.ReloadStorageState(accountID)
},
func(headers []string, requestURL string, now time.Time) error {
- return refresher.pool.MergeSetCookieHeaders(account.ID, headers, requestURL, now)
+ return refresher.pool.MergeSetCookieHeaders(accountID, headers, requestURL, now)
},
)
}
diff --git a/internal/app/dispatch.go b/internal/app/dispatch.go
index 8fe2298b..78ce64d4 100644
--- a/internal/app/dispatch.go
+++ b/internal/app/dispatch.go
@@ -119,14 +119,43 @@ func (queue *dispatchQueue) wakeHeads() {
queue.wakeTurnLocked("")
}
-// wakeTurnLocked 唤醒条件为 key 的请求中轮到取号的请求,key 为空时唤醒全部条件
+// wakeTurnLocked 唤醒条件为 key 的请求中轮到取号的请求,key 为空时唤醒全部条件;按队列顺序单遍扫描,结果与逐个请求调用 turnLocked 相同
func (queue *dispatchQueue) wakeTurnLocked(key string) {
+ // claim 按条件记录排在前面、不在等 Worker 启动的请求:anyAccount 表示其中有请求可用全部账户,reserved 是其余请求可用的账户
+ type claim struct {
+ anyAccount bool
+ reserved map[string]struct{}
+ }
+ claims := make(map[string]*claim)
for _, waiter := range queue.waiters {
if waiter.starting || key != "" && waiter.key != key {
continue
}
- if _, ok := queue.turnLocked(waiter); ok {
+ ahead := claims[waiter.key]
+ if ahead == nil {
+ ahead = &claim{}
+ claims[waiter.key] = ahead
+ }
+ switch {
+ case waiter.accounts != nil && len(waiter.accounts) == 0:
+ waiter.signal()
+ case ahead.anyAccount:
+ case waiter.accounts == nil:
waiter.signal()
+ ahead.anyAccount = true
+ default:
+ if slices.ContainsFunc(waiter.accounts, func(accountID string) bool {
+ _, taken := ahead.reserved[accountID]
+ return !taken
+ }) {
+ waiter.signal()
+ }
+ if ahead.reserved == nil {
+ ahead.reserved = make(map[string]struct{}, len(waiter.accounts))
+ }
+ for _, accountID := range waiter.accounts {
+ ahead.reserved[accountID] = struct{}{}
+ }
}
}
}
diff --git a/internal/app/files.go b/internal/app/files.go
index 647253b4..b6c8d418 100644
--- a/internal/app/files.go
+++ b/internal/app/files.go
@@ -7,67 +7,52 @@ import (
"github.com/Mag1cFall/AIStudio2API/internal/api"
)
-// UploadFile 上传文件并记录实际账户
-func (service *trackedService) UploadFile(ctx context.Context, request aistudio.UploadRequest) (aistudio.FileRef, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
+// observedRequest 在追踪与访问日志上下文内执行单次非流式数据请求
+func observedRequest[T any](service *trackedService, ctx context.Context, model string, call func(context.Context) (T, error)) (T, error) {
+ requestCtx, cancel, err := service.observedDataRequestContext(ctx, model)
if err != nil {
- return aistudio.FileRef{}, err
+ var zero T
+ return zero, err
}
defer cancel()
- file, requestErr := service.service.(aistudio.FileService).UploadFile(requestCtx, request)
+ result, requestErr := call(requestCtx)
requestErr = endedRequestError(requestCtx, requestErr)
api.SetAccessLogError(requestCtx, requestErr)
- return file, requestErr
+ return result, requestErr
+}
+
+// UploadFile 上传文件并记录实际账户
+func (service *trackedService) UploadFile(ctx context.Context, request aistudio.UploadRequest) (aistudio.FileRef, error) {
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) (aistudio.FileRef, error) {
+ return service.service.(aistudio.FileService).UploadFile(reqCtx, request)
+ })
}
// FileMetadata 返回上传文件的持久元数据
func (service *trackedService) FileMetadata(ctx context.Context, fileID string) (aistudio.FileMetadata, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return aistudio.FileMetadata{}, err
- }
- defer cancel()
- metadata, requestErr := service.service.(aistudio.FileService).FileMetadata(requestCtx, fileID)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return metadata, requestErr
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) (aistudio.FileMetadata, error) {
+ return service.service.(aistudio.FileService).FileMetadata(reqCtx, fileID)
+ })
}
// ListFiles 列出上传文件
func (service *trackedService) ListFiles(ctx context.Context) ([]aistudio.FileMetadata, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return nil, err
- }
- defer cancel()
- list, requestErr := service.service.(aistudio.FileService).ListFiles(requestCtx)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return list, requestErr
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) ([]aistudio.FileMetadata, error) {
+ return service.service.(aistudio.FileService).ListFiles(reqCtx)
+ })
}
// DeleteFile 删除上传文件并记录结果
func (service *trackedService) DeleteFile(ctx context.Context, fileID string) error {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return err
- }
- defer cancel()
- requestErr := service.service.(aistudio.FileService).DeleteFile(requestCtx, fileID)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return requestErr
+ _, err := observedRequest(service, ctx, "", func(reqCtx context.Context) (struct{}, error) {
+ return struct{}{}, service.service.(aistudio.FileService).DeleteFile(reqCtx, fileID)
+ })
+ return err
}
// VideoFrameTokens 统计视频文件按视频设置抽帧后的 token 数并记录实际账户
func (service *trackedService) VideoFrameTokens(ctx context.Context, request aistudio.VideoFramesRequest) (int64, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return 0, err
- }
- defer cancel()
- tokens, requestErr := service.service.(aistudio.VideoFrameService).VideoFrameTokens(requestCtx, request)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return tokens, requestErr
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) (int64, error) {
+ return service.service.(aistudio.VideoFrameService).VideoFrameTokens(reqCtx, request)
+ })
}
diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go
index 1fbeff30..d69cb563 100644
--- a/internal/app/lifecycle.go
+++ b/internal/app/lifecycle.go
@@ -291,18 +291,10 @@ func (manager *runtimeManager) startService(ctx context.Context) (api.AdminStatu
}
manager.overrides.Apply(&saved)
next.admin.ApplyAccountSelection(saved)
- next.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts))
- next.service.ApplyCapacity(saved.WarmWorkerLimit, saved.MaxActiveWorkers, saved.WarmStartupConcurrency, saved.PerAccountConcurrency)
- mapping, _ := config.ParseModelMapping(saved.ModelMapping)
- next.service.SetRequestPolicy(mapping, saved.MaxAccountSwitches)
- next.service.ApplyHotConfig(saved)
- next.service.ApplyChannelsAndHidden(saved)
+ manager.applyGenerationHotConfig(next, saved)
if saved.Proxy != next.config.Proxy {
_ = next.admin.ApplyProxy(saved.Proxy)
}
- manager.setAPIKey(saved.ProxyAPIKey)
- manager.setEgressProxy(saved.Proxy)
- manager.settings.Store(requestSettingsOf(saved))
manager.mu.Lock()
current = manager.current
manager.current = next
@@ -840,28 +832,31 @@ func (manager *runtimeManager) UpdateRuntimeConfig(ctx context.Context, value ap
return updated, err
}
manager.overrides.Apply(&saved)
- manager.setAPIKey(saved.ProxyAPIKey)
- manager.setEgressProxy(saved.Proxy)
manager.activeManagement.ProxyAPIKey = saved.ProxyAPIKey
manager.activeManagement.AdminAuthEnabled = saved.AdminAuthEnabled
manager.activeManagement.AdminUsername = saved.AdminUsername
manager.activeManagement.AdminPassword = saved.AdminPassword
- current.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts))
- current.service.ApplyCapacity(
- saved.WarmWorkerLimit, saved.MaxActiveWorkers, saved.WarmStartupConcurrency, saved.PerAccountConcurrency,
- )
- mapping, _ := config.ParseModelMapping(saved.ModelMapping)
- current.service.SetRequestPolicy(mapping, saved.MaxAccountSwitches)
- current.service.ApplyHotConfig(saved)
- current.service.ApplyChannelsAndHidden(saved)
+ manager.applyGenerationHotConfig(current, saved)
proxyErr := current.admin.ApplyProxy(saved.Proxy)
updated.ActiveProxy, updated.ProxyPool = current.admin.ProxyState()
- manager.settings.Store(requestSettingsOf(saved))
updated = manager.decorateRuntimeConfig(updated, current.config)
manager.ledger.SetBodyCapture(saved.RequestBodyLog)
return updated, errors.Join(proxyErr, manager.logs.set(saved.LogFile, saved.LogMaxTotalMB))
}
+// applyGenerationHotConfig 把保存后立即生效的配置应用到生成服务与管理器
+func (manager *runtimeManager) applyGenerationHotConfig(gen *runtimeGeneration, saved config.Config) {
+ gen.service.SetAPIKeyAccounts(apiKeyAccounts(saved.ProxyAPIKey, saved.APIKeyAccounts))
+ gen.service.ApplyCapacity(saved.WarmWorkerLimit, saved.MaxActiveWorkers, saved.WarmStartupConcurrency, saved.PerAccountConcurrency)
+ mapping, _ := config.ParseModelMapping(saved.ModelMapping)
+ gen.service.SetRequestPolicy(mapping, saved.MaxAccountSwitches)
+ gen.service.ApplyHotConfig(saved)
+ gen.service.ApplyChannelsAndHidden(saved)
+ manager.setAPIKey(saved.ProxyAPIKey)
+ manager.setEgressProxy(saved.Proxy)
+ manager.settings.Store(requestSettingsOf(saved))
+}
+
// Cooldowns 返回当前生成服务冷却状态
func (manager *runtimeManager) Cooldowns(ctx context.Context) ([]api.AdminCooldown, error) {
current, done := manager.generation()
diff --git a/internal/app/request_logging.go b/internal/app/request_logging.go
index f19e63ac..29a31a8d 100644
--- a/internal/app/request_logging.go
+++ b/internal/app/request_logging.go
@@ -129,7 +129,7 @@ func requestProtocol(path string) string {
return "interactions"
case strings.Contains(path, "/files"):
return "files"
- case strings.HasPrefix(path, "/v1beta/"), strings.HasPrefix(path, "/v1/models/") && strings.Contains(path, ":"), strings.HasPrefix(path, "/v1/cachedContents"):
+ case strings.HasPrefix(path, "/v1beta/"), strings.HasPrefix(path, "/ws/"), strings.HasPrefix(path, "/v1/models/") && strings.Contains(path, ":"), strings.HasPrefix(path, "/v1/cachedContents"):
return "gemini"
case strings.HasPrefix(path, "/v1/images/"):
return "images"
diff --git a/internal/app/request_registry.go b/internal/app/request_registry.go
index 18696f48..1b4f49fe 100644
--- a/internal/app/request_registry.go
+++ b/internal/app/request_registry.go
@@ -25,6 +25,8 @@ type requestRegistry struct {
consoleDone chan struct{}
// firstEvents 是各模型与通道近期原请求的首事件等待,生成服务重启后保留
firstEvents *firstEventStats
+ // accountsPublishMu 串行化管理端账户快照的读取与发布
+ accountsPublishMu sync.Mutex
}
type eventSubscriber struct {
@@ -33,6 +35,10 @@ type eventSubscriber struct {
events chan api.AdminEvent
wake chan struct{}
pending []api.AdminEvent
+ head int
+ baseSeq int
+ singletonSeq map[string]int
+ requestSeq map[string]int
pendingLogs int
pendingRequests int
}
@@ -282,8 +288,12 @@ func (registry *requestRegistry) clearLogs() {
// newEventSubscriber 创建管理页有界事件队列
func newEventSubscriber(ctx context.Context) *eventSubscriber {
return &eventSubscriber{
- ctx: ctx, events: make(chan api.AdminEvent, 16), wake: make(chan struct{}, 1),
- pending: make([]api.AdminEvent, 0, 256),
+ ctx: ctx,
+ events: make(chan api.AdminEvent, 16),
+ wake: make(chan struct{}, 1),
+ pending: make([]api.AdminEvent, 0, 256),
+ singletonSeq: make(map[string]int, 4),
+ requestSeq: make(map[string]int, 64),
}
}
@@ -297,32 +307,43 @@ func (subscriber *eventSubscriber) enqueue(event api.AdminEvent) {
func (subscriber *eventSubscriber) enqueueLocked(event api.AdminEvent) {
switch event.Type {
case "status", "models", "accounts", "cooldowns":
- for index := len(subscriber.pending) - 1; index >= 0; index-- {
- if subscriber.pending[index].Type == event.Type {
+ if seq, ok := subscriber.singletonSeq[event.Type]; ok {
+ index := subscriber.head + (seq - subscriber.baseSeq)
+ if index >= subscriber.head && index < len(subscriber.pending) {
subscriber.pending[index] = event
return
}
}
+ seq := subscriber.baseSeq + (len(subscriber.pending) - subscriber.head)
+ subscriber.pending = append(subscriber.pending, event)
+ subscriber.singletonSeq[event.Type] = seq
+ return
case "request":
request := event.Data.(api.AdminRequest)
- for index := len(subscriber.pending) - 1; index >= 0; index-- {
- pending := subscriber.pending[index]
- if pending.Type == "request" && pending.Data.(api.AdminRequest).ID == request.ID {
+ if seq, ok := subscriber.requestSeq[request.ID]; ok {
+ index := subscriber.head + (seq - subscriber.baseSeq)
+ if index >= subscriber.head && index < len(subscriber.pending) {
subscriber.pending[index] = event
return
}
}
+ seq := subscriber.baseSeq + (len(subscriber.pending) - subscriber.head)
+ subscriber.pending = append(subscriber.pending, event)
+ subscriber.requestSeq[request.ID] = seq
subscriber.pendingRequests++
+ if subscriber.pendingRequests >= adminRequestCompactAt {
+ subscriber.trimPendingLocked("request", adminRequestRetain)
+ }
+ return
case "log":
+ subscriber.pending = append(subscriber.pending, event)
subscriber.pendingLogs++
+ if subscriber.pendingLogs >= adminLogCompactAt {
+ subscriber.trimPendingLocked("log", adminLogRetain)
+ }
+ return
}
subscriber.pending = append(subscriber.pending, event)
- if subscriber.pendingLogs >= adminLogCompactAt {
- subscriber.trimPendingLocked("log", adminLogRetain)
- }
- if subscriber.pendingRequests >= adminRequestCompactAt {
- subscriber.trimPendingLocked("request", adminRequestRetain)
- }
}
func (subscriber *eventSubscriber) trimPendingLocked(eventType string, retain int) {
@@ -331,15 +352,28 @@ func (subscriber *eventSubscriber) trimPendingLocked(eventType string, retain in
count = subscriber.pendingRequests
}
drop := count - retain
- compacted := subscriber.pending[:0]
- for _, event := range subscriber.pending {
+ active := subscriber.pending[subscriber.head:]
+ write := 0
+ clear(subscriber.singletonSeq)
+ clear(subscriber.requestSeq)
+ for _, event := range active {
if event.Type == eventType && drop > 0 {
drop--
continue
}
- compacted = append(compacted, event)
+ subscriber.pending[write] = event
+ switch event.Type {
+ case "status", "models", "accounts", "cooldowns":
+ subscriber.singletonSeq[event.Type] = write
+ case "request":
+ subscriber.requestSeq[event.Data.(api.AdminRequest).ID] = write
+ }
+ write++
}
- subscriber.pending = compacted
+ clear(subscriber.pending[write:])
+ subscriber.pending = subscriber.pending[:write]
+ subscriber.head = 0
+ subscriber.baseSeq = 0
if eventType == "request" {
subscriber.pendingRequests = retain
} else {
@@ -349,8 +383,13 @@ func (subscriber *eventSubscriber) trimPendingLocked(eventType string, retain in
func (subscriber *eventSubscriber) activate(initial []api.AdminEvent) {
subscriber.mu.Lock()
- buffered := append([]api.AdminEvent(nil), subscriber.pending...)
+ buffered := append([]api.AdminEvent(nil), subscriber.pending[subscriber.head:]...)
+ clear(subscriber.pending)
subscriber.pending = subscriber.pending[:0]
+ subscriber.head = 0
+ subscriber.baseSeq = 0
+ clear(subscriber.singletonSeq)
+ clear(subscriber.requestSeq)
subscriber.pendingLogs = 0
subscriber.pendingRequests = 0
for _, event := range initial {
@@ -375,20 +414,37 @@ func (subscriber *eventSubscriber) notify() {
func (subscriber *eventSubscriber) next() (api.AdminEvent, bool) {
subscriber.mu.Lock()
defer subscriber.mu.Unlock()
- if len(subscriber.pending) == 0 {
+ if subscriber.head >= len(subscriber.pending) {
return api.AdminEvent{}, false
}
- event := subscriber.pending[0]
- subscriber.pending[0] = api.AdminEvent{}
- subscriber.pending = subscriber.pending[1:]
- if event.Type == "log" {
- subscriber.pendingLogs--
- }
- if event.Type == "request" {
+ seq := subscriber.baseSeq
+ event := subscriber.pending[subscriber.head]
+ subscriber.pending[subscriber.head] = api.AdminEvent{}
+ subscriber.head++
+ subscriber.baseSeq++
+ switch event.Type {
+ case "status", "models", "accounts", "cooldowns":
+ if subscriber.singletonSeq[event.Type] == seq {
+ delete(subscriber.singletonSeq, event.Type)
+ }
+ case "request":
+ id := event.Data.(api.AdminRequest).ID
+ if subscriber.requestSeq[id] == seq {
+ delete(subscriber.requestSeq, id)
+ }
subscriber.pendingRequests--
+ case "log":
+ subscriber.pendingLogs--
}
- if len(subscriber.pending) == 0 {
- subscriber.pending = nil
+ if subscriber.head >= len(subscriber.pending) {
+ subscriber.pending = subscriber.pending[:0]
+ subscriber.head = 0
+ subscriber.baseSeq = 0
+ } else if subscriber.head >= 256 && subscriber.head*2 >= len(subscriber.pending) {
+ remaining := copy(subscriber.pending, subscriber.pending[subscriber.head:])
+ clear(subscriber.pending[remaining:])
+ subscriber.pending = subscriber.pending[:remaining]
+ subscriber.head = 0
}
return event, true
}
@@ -471,3 +527,10 @@ func (registry *requestRegistry) publish(event api.AdminEvent) {
registry.publishLocked(event)
registry.mu.Unlock()
}
+
+// publishAccounts 串行读取当前账户快照并推送给管理页订阅者,避免旧快照晚于新快照到达
+func (registry *requestRegistry) publishAccounts(pool *aistudio.AccountPool, store *aistudio.AccountStore) {
+ registry.accountsPublishMu.Lock()
+ defer registry.accountsPublishMu.Unlock()
+ registry.publish(api.AdminEvent{Type: "accounts", Data: map[string]any{"accounts": adminAccountsSnapshot(pool, store)}})
+}
diff --git a/internal/app/runtime.go b/internal/app/runtime.go
index 0bb9546e..609042f1 100644
--- a/internal/app/runtime.go
+++ b/internal/app/runtime.go
@@ -112,6 +112,7 @@ func newRuntime(
Transport: transport, Workers: workers, SetupTimeout: cfg.InitTimeout,
})
refresher := newAuthRuntimeRefresher(workers, requests, globalProxy)
+ refresher.store = store
workers.refresher = refresher
client := aistudio.NewClient(aistudio.ClientOptions{
Transport: &authRetryTransport{transport: transport, refresher: refresher},
@@ -123,6 +124,7 @@ func newRuntime(
pooled := aistudio.NewPooledService(pool, client)
service := newTrackedService(lifecycle, pooled, pool, requests, workers, cfg.RequestTimeout)
service.pooled = pooled
+ service.store = store
service.transport = transport
service.protected = protected
service.refresher = refresher
@@ -173,6 +175,7 @@ type trackedService struct {
service aistudio.Service
catalog modelCatalogService
pool *aistudio.AccountPool
+ store *aistudio.AccountStore
requests *requestRegistry
workers *accountWorkerManager
state atomic.Int32
@@ -337,6 +340,7 @@ func (service *trackedService) ApplyHotConfig(cfg config.Config) {
if service.pooled != nil {
service.pooled.SetRequestOptions(aistudio.RequestOptions{
BuildNativeNonstream: cfg.BuildNativeNonstream,
+ BuildChatProtocol: cfg.BuildChatProtocol,
YouTubeLinks: cfg.YouTubeLinks,
DiscoverHiddenModels: cfg.DiscoverHiddenModels,
StripThoughtSignatures: cfg.StripThoughtSignatures,
@@ -928,16 +932,7 @@ func (service *trackedService) Stop() (bool, error) {
service.lifecycleMu.Unlock()
transitionErr := waitServiceTransition(done, serviceTransitionShutdownTimeout, "生成服务切换停止")
if done != nil {
- service.lifecycleMu.Lock()
- cleanupErr := service.transitionErr
- if transitionErr == nil {
- service.transitionErr = nil
- service.transitionTimedOut = false
- } else {
- service.transitionTimedOut = true
- }
- service.lifecycleMu.Unlock()
- return false, errors.Join(transitionErr, cleanupErr)
+ return false, service.finishTransitionWait(transitionErr)
}
resetErr := service.workers.ResetAll()
service.lifecycleMu.Lock()
@@ -957,16 +952,7 @@ func (service *trackedService) Stop() (bool, error) {
dataCancel()
transitionErr := waitServiceTransition(done, serviceTransitionShutdownTimeout, "生成服务启动停止")
service.requests.cancelAll()
- service.lifecycleMu.Lock()
- cleanupErr := service.transitionErr
- if transitionErr == nil {
- service.transitionErr = nil
- service.transitionTimedOut = false
- } else {
- service.transitionTimedOut = true
- }
- service.lifecycleMu.Unlock()
- return true, errors.Join(transitionErr, cleanupErr)
+ return true, service.finishTransitionWait(transitionErr)
}
transitionDone := make(chan struct{})
service.transitionDone = transitionDone
@@ -979,6 +965,11 @@ func (service *trackedService) Stop() (bool, error) {
dataCancel()
go service.finishStop(transitionDone, modelRefreshDone)
transitionErr := waitServiceTransition(transitionDone, serviceTransitionShutdownTimeout, "生成服务停止")
+ return true, service.finishTransitionWait(transitionErr)
+}
+
+// finishTransitionWait 在服务切换等待结束后记下是否超时并清除已完成切换的残留错误,返回等待错误与切换清理错误的合并
+func (service *trackedService) finishTransitionWait(transitionErr error) error {
service.lifecycleMu.Lock()
cleanupErr := service.transitionErr
if transitionErr == nil {
@@ -988,7 +979,7 @@ func (service *trackedService) Stop() (bool, error) {
service.transitionTimedOut = true
}
service.lifecycleMu.Unlock()
- return true, errors.Join(transitionErr, cleanupErr)
+ return errors.Join(transitionErr, cleanupErr)
}
// finishStop 完成运行态服务的后台清理
@@ -1080,12 +1071,7 @@ func (service *trackedService) publishModelAccess() {
if service.lifecycle.Err() != nil {
return
}
- statuses := service.pool.Status()
- accounts := make([]api.AdminAccount, 0, len(statuses))
- for _, status := range statuses {
- accounts = append(accounts, adminAccountDTO(status))
- }
- service.requests.publish(api.AdminEvent{Type: "accounts", Data: map[string]any{"accounts": accounts}})
+ service.requests.publishAccounts(service.pool, service.store)
service.requests.publish(api.AdminEvent{Type: "models", Data: map[string]any{"models": service.catalogModels()}})
}
@@ -1717,15 +1703,9 @@ func (service *trackedService) CountTokens(ctx context.Context, request aistudio
if err := service.modelUnavailable(request.Model); err != nil {
return aistudio.TokenCount{}, err
}
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, request.Model)
- if err != nil {
- return aistudio.TokenCount{}, err
- }
- defer cancel()
- count, requestErr := service.service.CountTokens(requestCtx, request)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return count, requestErr
+ return observedRequest(service, ctx, request.Model, func(reqCtx context.Context) (aistudio.TokenCount, error) {
+ return service.service.CountTokens(reqCtx, request)
+ })
}
// GenerateTitle 生成试用页页头标题
@@ -1746,15 +1726,9 @@ func (service *trackedService) GenerateImage(ctx context.Context, request aistud
if err := service.modelUnavailable(request.Model); err != nil {
return nil, err
}
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, request.Model)
- if err != nil {
- return nil, err
- }
- defer cancel()
- images, requestErr := service.service.(aistudio.ImageService).GenerateImage(requestCtx, request)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return images, requestErr
+ return observedRequest(service, ctx, request.Model, func(reqCtx context.Context) ([]aistudio.GeneratedImage, error) {
+ return service.service.(aistudio.ImageService).GenerateImage(reqCtx, request)
+ })
}
// CreateDecision 回答决策问题并登记请求目标与账户,每次请求在运行日志中提醒该模型在 AI Studio 官网中隐藏
@@ -1859,41 +1833,24 @@ func (service *trackedService) recoverWorkerOnce(
// GetGenerateVideoOperation 读取视频长任务状态
func (service *trackedService) GetGenerateVideoOperation(ctx context.Context, operationID string) (aistudio.VideoOperation, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return aistudio.VideoOperation{}, err
- }
- defer cancel()
- operation, requestErr := service.service.(aistudio.VideoService).GetGenerateVideoOperation(requestCtx, operationID)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return operation, requestErr
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) (aistudio.VideoOperation, error) {
+ return service.service.(aistudio.VideoService).GetGenerateVideoOperation(reqCtx, operationID)
+ })
}
// ListVideos 列出视频任务
func (service *trackedService) ListVideos(ctx context.Context) ([]aistudio.VideoOperation, error) {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return nil, err
- }
- defer cancel()
- videos, requestErr := service.service.(aistudio.VideoService).ListVideos(requestCtx)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return videos, requestErr
+ return observedRequest(service, ctx, "", func(reqCtx context.Context) ([]aistudio.VideoOperation, error) {
+ return service.service.(aistudio.VideoService).ListVideos(reqCtx)
+ })
}
// DeleteVideo 删除视频任务及其结果文件
func (service *trackedService) DeleteVideo(ctx context.Context, operationID string) error {
- requestCtx, cancel, err := service.observedDataRequestContext(ctx, "")
- if err != nil {
- return err
- }
- defer cancel()
- requestErr := service.service.(aistudio.VideoService).DeleteVideo(requestCtx, operationID)
- requestErr = endedRequestError(requestCtx, requestErr)
- api.SetAccessLogError(requestCtx, requestErr)
- return requestErr
+ _, err := observedRequest(service, ctx, "", func(reqCtx context.Context) (struct{}, error) {
+ return struct{}{}, service.service.(aistudio.VideoService).DeleteVideo(reqCtx, operationID)
+ })
+ return err
}
// DownloadFile 下载生成任务绑定的 Drive 文件
@@ -1937,7 +1894,11 @@ func (closer *trackedMediaReadCloser) Close() error {
return closer.err
}
+// pageReadyLeaseKey 标记请求带有要上传的附件,acquireWarmLease 对冷启动的 Worker 在页面载入完成时就交出租约,附件上传与 WAA 启动同时进行
+type pageReadyLeaseKey struct{}
+
// acquireWarmLease 取得 Worker 已就绪的账户租约,可用账户重叠的同条件请求按到达先后取用共同的账户
+// ctx 带 pageReadyLeaseKey 时冷启动的租约在 Worker 页面载入完成、WAA 尚未就绪时返回,runAttempt 在取 proof 前等 Worker 启动结束
// 全部账户冷却时排队等待恢复,一个请求累计等待不超过 cooldownQueueLimit,cooled 是它已等的时长
// 最早恢复的是权限拒绝冷却或晚于请求期限时不排队
// quotaFallback 为 true 时停止排队后改用套餐限额、每日限额或权限拒绝冷却中的账户
@@ -2074,8 +2035,16 @@ func (service *trackedService) acquireWarmLease(ctx context.Context, selection a
}
workersChanged := service.workers.schedulingChanged()
dispatch.setStarting(waiter, true)
- _, promoteErr := service.workers.ensureWorker(aistudio.ContextWithAccountLease(ctx, lease), accountID, selection.ModelID, false, false)
+ starting := startWorker(aistudio.ContextWithAccountLease(ctx, lease), ctx.Value(pageReadyLeaseKey{}) != nil, func(startCtx context.Context) error {
+ _, err := service.workers.ensureWorker(startCtx, accountID, selection.ModelID, false, false)
+ return err
+ })
dispatch.setStarting(waiter, false)
+ if !starting.finished() {
+ service.workers.holdStartup(lease, starting)
+ return lease, nil
+ }
+ promoteErr := starting.err
if promoteErr == nil {
return lease, nil
}
@@ -2596,14 +2565,18 @@ func (service *trackedService) generateWithRetry(
service.requests.logRequestProgress(request.ID, "request", "WARN", "排队等待", "waited", waited, "model", modelID)
})
quotaFallback := selection.ResourceID == ""
- lease, acquireErr := service.acquireWarmLease(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled)
+ leaseCtx := requestCtx
+ if mediaCount, _ := inlineMediaInput(request.Contents); resourceID != "" || mediaCount > 0 {
+ leaseCtx = context.WithValue(requestCtx, pageReadyLeaseKey{}, true)
+ }
+ lease, acquireErr := service.acquireWarmLease(leaseCtx, selection, quotaFallback, &retry.failures, &retry.cooled)
var buildCooling *aistudio.AllCoolingError
if acquireErr != nil && selection.Channel == aistudio.ChannelBuild && requestCtx.Err() == nil && !aistudio.RequestBuildOnly(request) &&
(errors.Is(acquireErr, aistudio.ErrNoEligibleAccount) || errors.As(acquireErr, &buildCooling)) {
// 没有账户能经 Build 服务时改用 Playground,Playground 无法表达的设置按其最接近的形式发送
selection.Channel = ""
fallbackReason = "Build 通道没有可用账户"
- lease, acquireErr = service.acquireWarmLease(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled)
+ lease, acquireErr = service.acquireWarmLease(leaseCtx, selection, quotaFallback, &retry.failures, &retry.cooled)
}
queueDelayed := queueWait.finish()
if acquireErr == nil && selection.PreferredChannel == aistudio.ChannelBuild && lease.Channel() != aistudio.ChannelBuild {
@@ -2910,6 +2883,9 @@ func (service *trackedService) runAttempt(
service.requests.logRequestProgress(request.ID, accountLabel, "WARN", "内联附件处理失败", append(mediaFields, "error", err)...)
}
}
+ if err == nil {
+ err = service.workers.awaitStartup(ctx, lease)
+ }
prepareStartedAt := time.Now()
prepareTiming := newRequestPreparationTiming(prepareStartedAt)
prepareWait := startWaitReporter(func(waited time.Duration) {
diff --git a/internal/app/worker_manager.go b/internal/app/worker_manager.go
index 0b1ca865..ea945718 100644
--- a/internal/app/worker_manager.go
+++ b/internal/app/worker_manager.go
@@ -37,6 +37,8 @@ type accountWorkerManager struct {
lifecycle context.Context
cancel context.CancelFunc
closed bool
+ // renewals 在后台续签循环退出后结束等待
+ renewals sync.WaitGroup
signalMu sync.Mutex
signal chan struct{}
dispatch *dispatchQueue
@@ -50,6 +52,8 @@ type accountWorkerManager struct {
pageHeaders map[string]http.Header
// warming 表示一轮预热已开始而还没有给出第一个结果
warming atomic.Bool
+ // startups 是在 Worker 页面就绪时提前交给请求的租约与该 Worker 的启动结果,键为 *aistudio.AccountLease,值为 *workerStartup,租约归还后移除
+ startups sync.Map
}
type accountWorker struct {
@@ -219,6 +223,7 @@ func newAccountWorkerManager(
}
go manager.forwardPoolChanges()
go manager.reapIdleWorkers()
+ manager.renewals.Go(func() { manager.renewBoundSessions(boundRenewInterval) })
return manager
}
@@ -406,6 +411,59 @@ func (manager *accountWorkerManager) runtimeAvailable(accountIDs []string) ([]st
// workerIdleTimeout 为超出热池目标的 Worker 空闲多久后关闭
const workerIdleTimeout = 5 * time.Minute
+// boundRenewInterval 为后台检查常驻 Worker DBSC 绑定会话剩余有效期的间隔
+var boundRenewInterval = 30 * time.Second
+
+// renewBoundSessions 定期在常驻 Worker 的 DBSC 绑定 Cookie 到期前于后台刷新并推给页面
+func (manager *accountWorkerManager) renewBoundSessions(interval time.Duration) {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ rejected := make(map[string]uint64)
+ for {
+ select {
+ case <-manager.lifecycle.Done():
+ return
+ case <-ticker.C:
+ manager.renewBoundOnce(rejected)
+ }
+ }
+}
+
+// renewBoundOnce 为常驻 Worker 中即将到期的 DBSC 会话执行一次后台刷新,会话被拒的 Worker 代际不再重复请求
+func (manager *accountWorkerManager) renewBoundOnce(rejected map[string]uint64) {
+ warm := manager.WarmAccountIDs()
+ if len(warm) == 0 || manager.refresher == nil {
+ clear(rejected)
+ return
+ }
+ for id := range rejected {
+ if !slices.Contains(warm, id) {
+ delete(rejected, id)
+ }
+ }
+ for _, accountID := range warm {
+ if manager.lifecycle.Err() != nil {
+ return
+ }
+ generation := manager.WorkerGeneration(accountID)
+ if rejectedGen, ok := rejected[accountID]; ok && rejectedGen == generation {
+ continue
+ }
+ err := manager.refresher.ensureBoundAccount(manager.lifecycle, accountID)
+ if err == nil {
+ delete(rejected, accountID)
+ continue
+ }
+ if manager.lifecycle.Err() != nil {
+ return
+ }
+ if errors.Is(err, camoufoxnative.ErrAuthenticationRequired) {
+ rejected[accountID] = generation
+ }
+ manager.requests.log(manager.accountLabel(accountID), "WARN", "后台刷新绑定会话失败", "error", err)
+ }
+}
+
// reapIdleWorkers 定期关闭超出热池目标且空闲超时的 Worker
func (manager *accountWorkerManager) reapIdleWorkers() {
ticker := time.NewTicker(workerIdleTimeout / 10)
@@ -1221,6 +1279,7 @@ func (manager *accountWorkerManager) startReservedWorker(
options.StartupProgress = func(stage camoufoxnative.StartupStage) {
logStep(workerStartupProgress(stage))
}
+ options.PageReady, _ = ctx.Value(workerPageReadyKey{}).(func())
if manager.refresher != nil {
options.RefreshCookies = func(refreshCtx context.Context) error {
return manager.refresher.ensureBoundAccount(refreshCtx, account.id)
@@ -1669,6 +1728,65 @@ type workerReloadKey struct{}
// workerStartupRenewalKey 标记 Worker 启动中的认证续签,结果由启动日志报告
type workerStartupRenewalKey struct{}
+// workerPageReadyKey 携带 Worker 启动的页面就绪回调,值为 func(),Worker 页面载入完成而 WAA 尚未就绪时调用,可重复调用
+type workerPageReadyKey struct{}
+
+// workerStartup 是一次 Worker 启动的结果:done 关闭后 err 为启动结果
+type workerStartup struct {
+ done chan struct{}
+ err error
+}
+
+// finished 返回启动是否已经结束
+func (startup *workerStartup) finished() bool {
+ select {
+ case <-startup.done:
+ return true
+ default:
+ return false
+ }
+}
+
+// startWorker 运行 Worker 启动 run:early 为 false 时等到启动结束才返回;为 true 时 run 调用 ctx 中的页面就绪回调后即返回,此时租约已可上传附件,取 proof 要等 startup.done
+func startWorker(ctx context.Context, early bool, run func(context.Context) error) *workerStartup {
+ startup := &workerStartup{done: make(chan struct{})}
+ ready := make(chan struct{})
+ if early {
+ var once sync.Once
+ ctx = context.WithValue(ctx, workerPageReadyKey{}, func() { once.Do(func() { close(ready) }) })
+ }
+ go func() {
+ startup.err = run(ctx)
+ close(startup.done)
+ }()
+ select {
+ case <-ready:
+ case <-startup.done:
+ }
+ return startup
+}
+
+// holdStartup 记下提前交出的租约对应的 Worker 启动,awaitStartup 凭租约取用,租约归还后移除
+func (manager *accountWorkerManager) holdStartup(lease *aistudio.AccountLease, startup *workerStartup) {
+ manager.startups.Store(lease, startup)
+ lease.AfterRelease(func() { manager.startups.Delete(lease) })
+}
+
+// awaitStartup 等 lease 对应的 Worker 启动结束并返回启动结果,lease 不是提前交出的租约时立即返回
+func (manager *accountWorkerManager) awaitStartup(ctx context.Context, lease *aistudio.AccountLease) error {
+ held, ok := manager.startups.Load(lease)
+ if !ok {
+ return nil
+ }
+ startup := held.(*workerStartup)
+ select {
+ case <-startup.done:
+ return startup.err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
// startAuthenticatedWorker 在启动锁释放后恢复同一账户的认证
func (manager *accountWorkerManager) startAuthenticatedWorker(ctx context.Context, accountID, model string) (*accountWorkerPreparer, error) {
lease, leased := aistudio.AccountLeaseFromContext(ctx)
@@ -1961,6 +2079,7 @@ func (manager *accountWorkerManager) Close() error {
accounts = append(accounts, account)
}
manager.mu.Unlock()
+ manager.renewals.Wait()
manager.waitPrewarm()
closeResults := make(chan error, len(accounts))
var closes sync.WaitGroup
diff --git a/internal/camoufoxnative/bidi.go b/internal/camoufoxnative/bidi.go
index 24772946..339b0b9b 100644
--- a/internal/camoufoxnative/bidi.go
+++ b/internal/camoufoxnative/bidi.go
@@ -63,6 +63,10 @@ type pageLoad struct {
image bool
// bundle 是页面载入的官网前端主程序(boq-makersuite 的 m=_b 模块)地址
bundle string
+ // accessTokenRequest、accessTokenStatus 与 accessTokenAt 是冷启动期间 GenerateAccessToken 的请求 ID、状态码与完成时刻
+ accessTokenRequest string
+ accessTokenStatus int
+ accessTokenAt time.Time
}
// bidiPending 是等待响应的一条命令
@@ -301,7 +305,17 @@ func (client *bidiClient) observe(message map[string]any) {
if parsed.Path == accessTokenPath {
response, _ := params["response"].(map[string]any)
if status, ok := number(response["status"]); ok && method == "network.responseCompleted" {
- client.accessTokenStatus.Store(int64(status))
+ code := int(status)
+ client.accessTokenStatus.Store(int64(code))
+ if load != nil {
+ load.accessTokenStatus = code
+ load.accessTokenAt = time.Now()
+ if code == http.StatusOK {
+ load.accessTokenRequest, _ = request["request"].(string)
+ } else {
+ load.accessTokenRequest = ""
+ }
+ }
}
}
if load == nil {
@@ -714,6 +728,51 @@ func (client *bidiClient) pageCatalog(ctx context.Context, contextID, collector
return PageCatalog{Logging: bodies["GetLoggingContext"], Tier: bodies["GetAiStudioBenefitTier"], Models: bodies["ListModels"], Bundle: bundle}, nil
}
+// parseAccessToken 解析 GenerateAccessToken 响应数组首槽中的 OAuth access token,非字符串数组时返回空串
+func parseAccessToken(body []byte) string {
+ var fields []json.RawMessage
+ if json.Unmarshal(body, &fields) != nil || len(fields) == 0 {
+ return ""
+ }
+ var token string
+ if json.Unmarshal(fields[0], &token) != nil {
+ return ""
+ }
+ return strings.TrimSpace(token)
+}
+
+// pageAccessToken 在页面载入结束前经 collector 读取冷启动期间已完成的 GenerateAccessToken 响应,不额外等待;未授权(401)时返回 denied=true,读取失败不阻断启动
+func (client *bidiClient) pageAccessToken(ctx context.Context, contextID, collector string) (string, time.Time, bool) {
+ client.mu.Lock()
+ load := client.loads[contextID]
+ var status int
+ var requestID string
+ var at time.Time
+ if load != nil {
+ status, requestID, at = load.accessTokenStatus, load.accessTokenRequest, load.accessTokenAt
+ }
+ client.mu.Unlock()
+ if status == http.StatusUnauthorized {
+ return "", at, true
+ }
+ if status != http.StatusOK || requestID == "" {
+ return "", time.Time{}, false
+ }
+ data, err := client.command(ctx, "network.getData", map[string]any{"request": requestID, "dataType": "response", "collector": collector})
+ if err != nil {
+ return "", time.Time{}, false
+ }
+ raw, err := remoteBytes(data["bytes"])
+ if err != nil {
+ return "", time.Time{}, false
+ }
+ token := parseAccessToken(raw)
+ if token == "" {
+ return "", time.Time{}, false
+ }
+ return token, at, false
+}
+
// remoteBytes 按 Firefox network.getData 的编码还原响应正文:正文先按 UTF-8 解码为文本,base64 值是文本逐字符取 Latin-1 字节的编码,文本含 U+00FF 以上字符时值为文本本身
func remoteBytes(value any) ([]byte, error) {
item, _ := value.(map[string]any)
diff --git a/internal/camoufoxnative/drive.go b/internal/camoufoxnative/drive.go
index b437562e..9edb1544 100644
--- a/internal/camoufoxnative/drive.go
+++ b/internal/camoufoxnative/drive.go
@@ -17,10 +17,10 @@ const accessTokenPath = "/$rpc/google.internal.alkali.applications.makersuite.v1
// driveConsentTimeout 为一次 Drive 授权流程的最长耗时
const driveConsentTimeout = 3 * time.Minute
-// driveAccessButtonExpression 返回 History 页未被遮挡的 Allow Drive access 按钮
-const driveAccessButtonExpression = `[...document.querySelectorAll('button[aria-label="Allow Drive access"]')].find(button => {
+// driveAccessButtonExpression 返回 History 页或授权对话框中未被遮挡的 Allow Drive access 按钮(优先语言无关结构选择,兼容英文 aria-label)
+const driveAccessButtonExpression = `[...document.querySelectorAll('ms-auth-request-dialog mat-dialog-actions button:not([variant="borderless"]), button[aria-label="Allow Drive access"]')].find(button => {
const box = button.getBoundingClientRect();
- return button.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2));
+ return box.width > 0 && box.height > 0 && button.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2));
}) || null`
// driveApproveExpression 返回 OAuth 同意页的 Allow 按钮
diff --git a/internal/camoufoxnative/fingerprint.go b/internal/camoufoxnative/fingerprint.go
index 95b71d69..767fa0c5 100644
--- a/internal/camoufoxnative/fingerprint.go
+++ b/internal/camoufoxnative/fingerprint.go
@@ -309,7 +309,8 @@ var windowsProfileJSON []byte
// windowsProfileData 为解析后的 Windows 字体清单
type windowsProfileData struct {
- Fonts []string `json:"fonts"`
+ Fonts []string `json:"fonts"`
+ LegacyLocalizedFonts []string `json:"legacy_localized_fonts"`
}
var windowsProfile = func() windowsProfileData {
@@ -449,14 +450,14 @@ func fontList(value any) []string {
return fonts
}
-// windowsFonts 判断字体列表是否全部来自官方 Windows 字体清单或该语言的 Windows 补充字体
+// windowsFonts 判断字体列表是否全部来自官方 Windows 字体清单、该语言的 Windows 补充字体或旧版指纹中已保存的 Windows 本地化字体名
func windowsFonts(value any, locale string) bool {
fonts := fontList(value)
if len(fonts) == 0 {
return false
}
for _, font := range fonts {
- if !slices.Contains(windowsProfile.Fonts, font) && !slices.Contains(localeFonts(locale), font) {
+ if !slices.Contains(windowsProfile.Fonts, font) && !slices.Contains(localeFonts(locale), font) && !slices.Contains(windowsProfile.LegacyLocalizedFonts, font) {
return false
}
}
@@ -658,7 +659,7 @@ func clampWindowDimensions(config map[string]any) {
}
}
-// clampWindowPosition 保证窗口除两侧边框外位于所报告的屏幕内
+// clampWindowPosition 保证窗口除两侧边框外位于 Windows 工作区内:水平在屏幕内,垂直底边不超过屏幕高减 windowsTaskbarMin 加边框
func clampWindowPosition(config map[string]any) {
border := windowBorder(config)
for axis, key := range map[string]string{"Width": "window.screenX", "Height": "window.screenY"} {
@@ -668,6 +669,10 @@ func clampWindowPosition(config map[string]any) {
if !ok || screen == 0 || outer == 0 {
continue
}
- config[key] = max(-border, min(position, screen-outer+border))
+ limit := screen - outer + border
+ if axis == "Height" {
+ limit -= windowsTaskbarMin
+ }
+ config[key] = max(-border, min(position, limit))
}
}
diff --git a/internal/camoufoxnative/fingerprint_hardware.go b/internal/camoufoxnative/fingerprint_hardware.go
index c353656f..6b513396 100644
--- a/internal/camoufoxnative/fingerprint_hardware.go
+++ b/internal/camoufoxnative/fingerprint_hardware.go
@@ -134,12 +134,12 @@ func windowsMediaDevices() map[string]any {
return map[string]any{"mediaDevices:enabled": true, "mediaDevices:micros": counts[0], "mediaDevices:webcams": counts[1], "mediaDevices:speakers": counts[2]}
}
-// windowsLocaleFonts 是 Windows 以该语言为显示语言时自动安装的补充字体,英文名与本地化名都列出
+// windowsLocaleFonts 是 Windows 以该语言为显示语言时自动安装的补充字体与预装东亚字体的本地化族名,英文名与本地化名都列出
var windowsLocaleFonts = map[string][]string{
- "zh-TW": {"DFKai-SB", "標楷體", "MingLiU", "細明體", "PMingLiU", "新細明體", "MingLiU_HKSCS", "細明體_HKSCS"},
- "zh-CN": {"DengXian", "等线", "DengXian Light", "等线 Light", "FangSong", "仿宋", "KaiTi", "楷体", "SimHei", "黑体"},
- "ja": {"Meiryo", "メイリオ", "Meiryo UI", "MS Mincho", "MS 明朝", "MS PMincho", "MS P明朝", "Yu Mincho", "游明朝"},
- "ko": {"Batang", "바탕", "BatangChe", "바탕체", "Dotum", "돋움", "DotumChe", "돋움체", "Gulim", "굴림", "GulimChe", "굴림체", "Gungsuh", "궁서", "GungsuhChe", "궁서체"},
+ "zh-TW": {"DFKai-SB", "標楷體", "MingLiU", "細明體", "PMingLiU", "新細明體", "MingLiU_HKSCS", "細明體_HKSCS", "微軟正黑體", "微軟正黑體 Light", "細明體-ExtB", "新細明體-ExtB", "細明體_HKSCS-ExtB"},
+ "zh-CN": {"DengXian", "等线", "DengXian Light", "等线 Light", "FangSong", "仿宋", "KaiTi", "楷体", "SimHei", "黑体", "宋体", "新宋体", "微软雅黑", "微软雅黑 Light"},
+ "ja": {"Meiryo", "メイリオ", "Meiryo UI", "MS Mincho", "MS 明朝", "MS PMincho", "MS P明朝", "Yu Mincho", "游明朝", "游ゴシック", "游ゴシック Light", "游ゴシック Medium", "MS ゴシック", "MS Pゴシック"},
+ "ko": {"Batang", "바탕", "BatangChe", "바탕체", "Dotum", "돋움", "DotumChe", "돋움체", "Gulim", "굴림", "GulimChe", "굴림체", "Gungsuh", "궁서", "GungsuhChe", "궁서체", "맑은 고딕", "맑은 고딕 Semilight"},
}
// localeFonts 返回语言对应的 Windows 补充字体,繁体中文地区共用 zh-TW
diff --git a/internal/camoufoxnative/generate.go b/internal/camoufoxnative/generate.go
index 75768284..03c172fa 100644
--- a/internal/camoufoxnative/generate.go
+++ b/internal/camoufoxnative/generate.go
@@ -378,16 +378,21 @@ func (worker *Worker) generate(ctx context.Context, tab *chatTab, unboost func()
turned := make(chan error, 1)
go func() {
defer worker.inputMu.Unlock()
- turnCtx, cancel := context.WithTimeoutCause(ctx, turnInputTimeout, errTurnInputTimeout)
+ // input 是界面操作使用的上下文,只在 turnInputTimeout 到期时结束;turnCtx 是它的子上下文,另随 ctx 结束
+ input, cancelInput := context.WithTimeoutCause(context.WithoutCancel(ctx), turnInputTimeout, errTurnInputTimeout)
+ turnCtx, cancelTurn := context.WithCancelCause(input)
+ stop := context.AfterFunc(ctx, func() { cancelTurn(context.Cause(ctx)) })
current := StepSelectTab
- err := worker.startTurn(turnCtx, tab, turn, contents, prompt, requestID, func(step GenerateStep) {
+ err := worker.startTurn(turnCtx, input, tab, turn, contents, prompt, requestID, func(step GenerateStep) {
current = step
turn.report(step)
})
- if err != nil && context.Cause(turnCtx) == errTurnInputTimeout {
+ if err != nil && context.Cause(input) == errTurnInputTimeout {
err = fmt.Errorf("%w: %w", stepTimeout(current, turnInputTimeout), err)
}
- cancel()
+ stop()
+ cancelTurn(nil)
+ cancelInput()
turned <- err
}()
sent, err := worker.waitSent(ctx, tab, turn, requestID, channel, turned)
@@ -432,15 +437,9 @@ func (worker *Worker) generate(ctx context.Context, tab *chatTab, unboost func()
var errTurnInputTimeout = errors.New("界面输入超时")
// startTurn 在标签页上关闭页面启动后出现的已知弹层,完成本轮的界面输入(输入框没有焦点时先点击输入框;函数结果在最后一轮的函数调用块中输入并提交),安装一次性钩子后点击 Run 或 Rerun,指针仍停在 Run 上时原地点击,进入每个界面步骤时调用 step;调用方持有 inputMu
-func (worker *Worker) startTurn(ctx context.Context, tab *chatTab, turn GenerateTurn, contents []json.RawMessage, prompt string, requestID string, step func(GenerateStep)) error {
+// input 是界面操作使用的上下文:ctx 被取消只在两次操作之间生效,页面不会停在确认弹窗等操作中途
+func (worker *Worker) startTurn(ctx, input context.Context, tab *chatTab, turn GenerateTurn, contents []json.RawMessage, prompt string, requestID string, step func(GenerateStep)) error {
client := worker.client
- // input 是界面操作使用的上下文:ctx 被取消只在两次操作之间生效,页面不会停在确认弹窗等操作中途;ctx 的期限照常约束每个操作
- input := context.WithoutCancel(ctx)
- if deadline, ok := ctx.Deadline(); ok {
- var cancel context.CancelFunc
- input, cancel = context.WithDeadline(input, deadline)
- defer cancel()
- }
step(StepSelectTab)
if err := worker.selectChat(input, tab); err != nil {
return err
@@ -700,11 +699,11 @@ func (worker *Worker) newChat(ctx context.Context, tab *chatTab) error {
if err := worker.click(ctx, tab.contextID, newChatButtonSelector, "", "官网 New chat 按钮", pointerMoveDuration); err != nil {
return err
}
- discard := fmt.Sprintf(`[...document.querySelectorAll('button')].some(node => node.checkVisibility({visibilityProperty: true}) && new RegExp(%q, 'i').test(node.innerText.trim()))`, discardButtonPattern)
+ discard := fmt.Sprintf(`[...document.querySelectorAll(%q)].some(node => node.checkVisibility({visibilityProperty: true}))`, discardButtonSelector)
if err := client.waitFor(ctx, tab.contextID, discard, 5*time.Second); err != nil {
return fmt.Errorf("等待官网新对话确认: %w", err)
}
- if err := worker.click(ctx, tab.contextID, "button", discardButtonPattern, "官网 Discard and continue 按钮", pointerMoveDuration); err != nil {
+ if err := worker.click(ctx, tab.contextID, discardButtonSelector, "", "官网 Discard and continue 按钮", pointerMoveDuration); err != nil {
return err
}
if err := client.waitFor(ctx, tab.contextID, chatEmptyExpression, 10*time.Second); err != nil {
diff --git a/internal/camoufoxnative/launcher.go b/internal/camoufoxnative/launcher.go
index 45582778..921cb920 100644
--- a/internal/camoufoxnative/launcher.go
+++ b/internal/camoufoxnative/launcher.go
@@ -675,6 +675,8 @@ func firefoxPreferences(proxyValue, bypass string) (map[string]any, error) {
"media.sanity-test.disabled": true,
// browser.opaqueResponseBlocking.javascriptValidator 为 false 时不单独启动校验不透明响应的 JS 校验 utility 进程
"browser.opaqueResponseBlocking.javascriptValidator": false,
+ // media.gmp-manager.updateEnabled 为 false 时关闭 GMP 插件自动更新,避免后台请求 aus5 并重复下载 OpenH264 与 Widevine 插件
+ "media.gmp-manager.updateEnabled": false,
}
proxyValue = strings.TrimSpace(proxyValue)
if proxyValue == "" {
diff --git a/internal/camoufoxnative/page.go b/internal/camoufoxnative/page.go
index e465bc25..c3d083c6 100644
--- a/internal/camoufoxnative/page.go
+++ b/internal/camoufoxnative/page.go
@@ -96,36 +96,27 @@ const proofFunction = `async (page, prompt, digest) => {
// clipboardWriteFunction 把参数文本写入剪贴板,调用时带用户激活
const clipboardWriteFunction = `text => navigator.clipboard.writeText(text)`
-// 官网现场中 Firefox 在 BiDi 停顿之外为各组事件多用的毫秒数:Control 到 V、V 按住、V 抬起到 Control 抬起、指针移到按下与按下到抬起
-const (
- controlOverhead = 4.5
- keyOverhead = 9.5
- releaseOverhead = 3
- pressOverhead = 8
- holdOverhead = 8
-)
-
// pause 返回让 Firefox 派发的两组事件相隔 interval 毫秒的 BiDi 停顿动作
-func pause(interval, overhead float64) map[string]any {
- return map[string]any{"type": "pause", "duration": int(math.Round(max(interval-overhead, 0)))}
+func pause(interval float64) map[string]any {
+ return map[string]any{"type": "pause", "duration": int(math.Round(interval))}
}
// pasteKeyActions 返回按账户节奏在官网输入框按 Ctrl+V 的可信键盘动作:按下 Control 与 V,按住后依次抬起;shift 为真时在 Control 之后按下 Shift、抬起 V 之后抬起 Shift,以 Ctrl+Shift+V 粘贴
func pasteKeyActions(account rhythm.Rhythm, shift bool) []map[string]any {
if !shift {
return []map[string]any{
- {"type": "keyDown", "value": "\uE009"}, pause(account.Control, controlOverhead),
- {"type": "keyDown", "value": "v"}, pause(account.Key, keyOverhead),
- {"type": "keyUp", "value": "v"}, pause(account.Release, releaseOverhead),
+ {"type": "keyDown", "value": "\uE009"}, pause(account.Control),
+ {"type": "keyDown", "value": "v"}, pause(account.Key),
+ {"type": "keyUp", "value": "v"}, pause(account.Release),
{"type": "keyUp", "value": "\uE009"},
}
}
return []map[string]any{
- {"type": "keyDown", "value": "\uE009"}, pause(account.Control, controlOverhead),
- {"type": "keyDown", "value": "\uE008"}, pause(account.Control, controlOverhead),
- {"type": "keyDown", "value": "v"}, pause(account.Key, keyOverhead),
- {"type": "keyUp", "value": "v"}, pause(account.Release, releaseOverhead),
- {"type": "keyUp", "value": "\uE008"}, pause(account.Release, releaseOverhead),
+ {"type": "keyDown", "value": "\uE009"}, pause(account.Control),
+ {"type": "keyDown", "value": "\uE008"}, pause(account.Control),
+ {"type": "keyDown", "value": "v"}, pause(account.Key),
+ {"type": "keyUp", "value": "v"}, pause(account.Release),
+ {"type": "keyUp", "value": "\uE008"}, pause(account.Release),
{"type": "keyUp", "value": "\uE009"},
}
}
@@ -277,13 +268,13 @@ const (
// runButtonSelector 是生成前显示 Run、生成中显示 Stop 的按钮
runButtonSelector = "ms-run-button button"
// newChatButtonSelector 是顶栏的 New chat 按钮
- newChatButtonSelector = `ms-playground-toolbar button[aria-label="New chat"]`
- // discardButtonPattern 是 New chat 确认弹窗中丢弃当前对话的按钮文字
- discardButtonPattern = "^Discard and continue$"
+ newChatButtonSelector = `ms-playground-toolbar button[data-test-clear="outside"]`
+ // discardButtonSelector 是 New chat 确认弹窗中丢弃当前对话的按钮
+ discardButtonSelector = `ms-confirm-clear-dialog mat-dialog-actions button:not([variant="borderless"]), ms-confirm-clear-dialog button[cdkfocusinitial]`
// lastTurnSelector 是最后一个对话轮次,指针悬停其上时显示 Rerun 按钮
lastTurnSelector = "ms-chat-turn:last-of-type"
// rerunButtonSelector 是最后一个对话轮次的 Rerun 按钮
- rerunButtonSelector = `ms-chat-turn:last-of-type button[aria-label^="Rerun" i]`
+ rerunButtonSelector = `ms-chat-turn:last-of-type button[name="rerun-button"], ms-chat-turn:last-of-type button.rerun-button`
)
// pointerTargetFunction 把 selector 匹配且文字或 aria-label 匹配 pattern 的第一个可见元素滚动到视口内,返回其中心坐标 JSON,没有时返回空字符串
@@ -314,7 +305,7 @@ func (client *bidiClient) pointer(ctx context.Context, contextID, selector, patt
}
actions := []map[string]any{{"type": "pointerMove", "x": target.X, "y": target.Y, "duration": move}}
if click {
- actions = append(actions, pause(client.rhythm.Press, pressOverhead), map[string]any{"type": "pointerDown", "button": 0}, pause(client.rhythm.Hold, holdOverhead), map[string]any{"type": "pointerUp", "button": 0})
+ actions = append(actions, pause(client.rhythm.Press), map[string]any{"type": "pointerDown", "button": 0}, pause(client.rhythm.Hold), map[string]any{"type": "pointerUp", "button": 0})
}
_, err = client.command(ctx, "input.performActions", map[string]any{
"context": contextID,
@@ -323,7 +314,7 @@ func (client *bidiClient) pointer(ctx context.Context, contextID, selector, patt
return true, err
}
-// dismissOverlaysExpression 关闭官网已知且可交互的启动弹层:G1 欢迎对话框、引导浏览浮层与 Cookie 提示条,提示条有拒绝按钮时拒绝,只有确认按钮时确认
+// dismissOverlaysExpression 返回当前可见且可交互的官网已知启动弹层按钮选择器列表:G1 欢迎对话框、引导浏览浮层与 Cookie 提示条,提示条有拒绝按钮时拒绝,只有确认按钮时确认
const dismissOverlaysExpression = `(() => {` + pageDOMHelpers + `
const selectors = [
'ms-g1-welcome-dialog button',
@@ -331,23 +322,35 @@ const dismissOverlaysExpression = `(() => {` + pageDOMHelpers + `
'#glue-cookie-notification-bar-1 .glue-cookie-notification-bar__reject',
'#glue-cookie-notification-bar-1:not(:has(.glue-cookie-notification-bar__reject)) .glue-cookie-notification-bar__accept'
];
- let clicked = 0;
+ const targets = [];
for (const selector of selectors) {
const button = uniqueVisible(selector, '启动弹层按钮');
if (button && buttonEnabled(button)) {
- button.click();
- clicked++;
+ targets.push(selector);
}
}
- return clicked;
+ return JSON.stringify(targets);
})()`
-// dismissKnownOverlays 关闭官网已知启动弹层,返回点击的按钮数
+// dismissKnownOverlays 以可信指针点击关闭官网已知启动弹层,返回点击的按钮数
func dismissKnownOverlays(ctx context.Context, client *bidiClient, contextID string) (int, error) {
- clicked, err := client.evaluate(ctx, contextID, dismissOverlaysExpression)
+ raw, err := client.evaluateString(ctx, contextID, dismissOverlaysExpression)
if err != nil {
return 0, fmt.Errorf("处理 AI Studio 启动覆盖层: %w", err)
}
- count, _ := number(clicked["value"])
- return int(count), nil
+ var selectors []string
+ if err := json.Unmarshal([]byte(raw), &selectors); err != nil {
+ return 0, fmt.Errorf("解析 AI Studio 启动覆盖层: %w", err)
+ }
+ clicked := 0
+ for _, selector := range selectors {
+ found, err := client.pointer(ctx, contextID, selector, "", true, pointerMoveDuration)
+ if err != nil {
+ return clicked, fmt.Errorf("点击 AI Studio 启动覆盖层: %w", err)
+ }
+ if found {
+ clicked++
+ }
+ }
+ return clicked, nil
}
diff --git a/internal/camoufoxnative/page_flags.go b/internal/camoufoxnative/page_flags.go
new file mode 100644
index 00000000..9bbf692e
--- /dev/null
+++ b/internal/camoufoxnative/page_flags.go
@@ -0,0 +1,67 @@
+package camoufoxnative
+
+import (
+ "encoding/json"
+ "regexp"
+ "strings"
+)
+
+// buildAgencyFlagID 是官网前端决定 Build 对话走 agency(StreamRunAgentTask)还是旧接口(CodeAssistantOffline)的标志号
+const buildAgencyFlagID = 45831005
+
+// pageWIZScriptPattern 匹配官网页面以 application/json 脚本内联的 WIZ 数据
+var pageWIZScriptPattern = regexp.MustCompile(`(?s)`)
+
+// pageTSDtVExpression 从官网页面读取 WIZ 数据中的 TSDtV 字符串,与官网前端读取 TSDtV 的方式相同
+const pageTSDtVExpression = `(() => {
+ if (window.WIZ_global_data && typeof window.WIZ_global_data.TSDtV === "string") return window.WIZ_global_data.TSDtV;
+ for (const script of document.querySelectorAll('script[type="application/json"]')) {
+ try {
+ const data = JSON.parse(script.textContent || "");
+ if (data && typeof data.TSDtV === "string") return data.TSDtV;
+ } catch {}
+ }
+ return "";
+})()`
+
+// BuildAgencyFromTSDtV 读取 TSDtV 中标志 45831005 的布尔取值,标志缺失或取值不是布尔时返回 nil
+// TSDtV 以 %.@. 开头,其后是数组,root[0][0][1] 的每一项为 [标志号, null, 取值, ...]
+func BuildAgencyFromTSDtV(tsdtv string) *bool {
+ rest, ok := strings.CutPrefix(strings.TrimSpace(tsdtv), "%.@.")
+ if !ok {
+ return nil
+ }
+ var root [][][]json.RawMessage
+ if json.Unmarshal([]byte("["+rest), &root) != nil || len(root) == 0 || len(root[0]) == 0 || len(root[0][0]) < 2 {
+ return nil
+ }
+ var flags [][]json.RawMessage
+ if json.Unmarshal(root[0][0][1], &flags) != nil {
+ return nil
+ }
+ for _, flag := range flags {
+ var id int64
+ if len(flag) < 3 || json.Unmarshal(flag[0], &id) != nil || id != buildAgencyFlagID {
+ continue
+ }
+ var value bool
+ if json.Unmarshal(flag[2], &value) != nil {
+ return nil
+ }
+ return &value
+ }
+ return nil
+}
+
+// BuildAgencyFromHTML 读取官网页面 HTML 内联的 WIZ 数据 TSDtV 中标志 45831005 的布尔取值,缺失或取值不是布尔时返回 nil
+func BuildAgencyFromHTML(body []byte) *bool {
+ for _, match := range pageWIZScriptPattern.FindAllSubmatch(body, -1) {
+ var data struct {
+ TSDtV string `json:"TSDtV"`
+ }
+ if json.Unmarshal(match[1], &data) == nil && data.TSDtV != "" {
+ return BuildAgencyFromTSDtV(data.TSDtV)
+ }
+ }
+ return nil
+}
diff --git a/internal/camoufoxnative/protected.go b/internal/camoufoxnative/protected.go
index 6952475d..17422ed3 100644
--- a/internal/camoufoxnative/protected.go
+++ b/internal/camoufoxnative/protected.go
@@ -201,12 +201,22 @@ func (worker *Worker) sendProtected(ctx context.Context, client *bidiClient, con
if headers.Get("Priority") == "u=0" {
activate = "keydown"
}
+ if activate != "" {
+ // 挂捕获阶段键盘监听并派发 Pause 键须与页面键盘输入(如 Ctrl+V)串行,避免吞掉并发按键
+ if err := worker.lockInputWithin(ctx, 5*time.Second); err != nil {
+ client.closeChannel(requestID)
+ return nil, fmt.Errorf("浏览器发送受保护请求: %w", err)
+ }
+ }
startCtx, cancelStart := context.WithTimeout(ctx, 5*time.Second)
_, err = client.callFunction(startCtx, contextID, protectedSend, page, requestID, rawURL, string(encodedHeaders), string(body), activate, bidiChannelArgument(requestID))
if err == nil && activate != "" {
_, err = client.command(startCtx, "input.performActions", map[string]any{"context": contextID, "actions": protectedSendKey})
}
cancelStart()
+ if activate != "" {
+ worker.inputMu.Unlock()
+ }
if err != nil {
return nil, worker.abandonProtectedRequest(ctx, contextID, page, requestID, fmt.Errorf("浏览器发送受保护请求: %w", err))
}
diff --git a/internal/camoufoxnative/types.go b/internal/camoufoxnative/types.go
index f6762c36..819f1b81 100644
--- a/internal/camoufoxnative/types.go
+++ b/internal/camoufoxnative/types.go
@@ -123,6 +123,8 @@ type Options struct {
ReadyTimeout time.Duration
Log io.Writer
StartupProgress func(StartupStage)
+ // PageReady 在 SpiderMonkey 后端的页面载入完成、公共协议头与目录可用而 WAA 尚未就绪时调用一次,调用前账户页面已登记到页面注册表,为空时跳过
+ PageReady func()
// RefreshCookies 在重建 WAA VM 前刷新即将到期的 DBSC 绑定 Cookie,为空时跳过
RefreshCookies func(context.Context) error
// liveView 表示无头画面实时显示在管理页登录窗口,页面保持 Firefox 默认刷新帧率
@@ -193,4 +195,6 @@ type PageCatalog struct {
Models []byte
// Bundle 是页面载入的官网前端主程序地址
Bundle string
+ // BuildAgency 是页面启动数据 TSDtV 中标志 45831005 的取值,未出现或非布尔时为 nil
+ BuildAgency *bool
}
diff --git a/internal/camoufoxnative/windows_profile.json b/internal/camoufoxnative/windows_profile.json
index b646fd4a..454f6bbb 100644
--- a/internal/camoufoxnative/windows_profile.json
+++ b/internal/camoufoxnative/windows_profile.json
@@ -1,111 +1,113 @@
{
- "fonts": [
- "Arial",
- "Arial Black",
- "Bahnschrift",
- "Calibri",
- "Calibri Light",
- "Cambria",
- "Cambria Math",
- "Candara",
- "Candara Light",
- "Comic Sans MS",
- "Consolas",
- "Constantia",
- "Corbel",
- "Corbel Light",
- "Courier New",
- "Ebrima",
- "Franklin Gothic Medium",
- "Gabriola",
- "Gadugi",
- "Georgia",
- "HoloLens MDL2 Assets",
- "Impact",
- "Ink Free",
- "Javanese Text",
- "Leelawadee UI",
- "Leelawadee UI Semilight",
- "Lucida Console",
- "Lucida Sans Unicode",
- "MS Gothic",
- "MS PGothic",
- "MS UI Gothic",
- "MV Boli",
- "Malgun Gothic",
- "Malgun Gothic Semilight",
- "Marlett",
- "Microsoft Himalaya",
- "Microsoft JhengHei",
- "Microsoft JhengHei Light",
- "Microsoft JhengHei UI",
- "Microsoft JhengHei UI Light",
- "Microsoft New Tai Lue",
- "Microsoft PhagsPa",
- "Microsoft Sans Serif",
- "Microsoft Tai Le",
- "Microsoft YaHei",
- "Microsoft YaHei Light",
- "Microsoft YaHei UI",
- "Microsoft YaHei UI Light",
- "Microsoft Yi Baiti",
- "MingLiU-ExtB",
- "MingLiU_HKSCS-ExtB",
- "Mongolian Baiti",
- "Myanmar Text",
- "NSimSun",
- "Nirmala UI",
- "Nirmala UI Semilight",
- "PMingLiU-ExtB",
- "Palatino Linotype",
- "Segoe Fluent Icons",
- "Segoe MDL2 Assets",
- "Segoe Print",
- "Segoe Script",
- "Segoe UI",
- "Segoe UI Black",
- "Segoe UI Emoji",
- "Segoe UI Historic",
- "Segoe UI Light",
- "Segoe UI Semibold",
- "Segoe UI Semilight",
- "Segoe UI Symbol",
- "Segoe UI Variable",
- "SimSun",
- "SimSun-ExtB",
- "Sitka",
- "Sitka Text",
- "Sylfaen",
- "Symbol",
- "Tahoma",
- "Times New Roman",
- "Trebuchet MS",
- "Twemoji Mozilla",
- "Verdana",
- "Webdings",
- "Wingdings",
- "Yu Gothic",
- "Yu Gothic Light",
- "Yu Gothic Medium",
- "Yu Gothic UI",
- "Yu Gothic UI Light",
- "Yu Gothic UI Semibold",
- "Yu Gothic UI Semilight",
- "宋体",
- "微軟正黑體",
- "微軟正黑體 Light",
- "微软雅黑",
- "微软雅黑 Light",
- "新宋体",
- "新細明體-ExtB",
- "游ゴシック",
- "游ゴシック Light",
- "游ゴシック Medium",
- "細明體-ExtB",
- "細明體_HKSCS-ExtB",
- "맑은 고딕",
- "맑은 고딕 Semilight",
- "MS ゴシック",
- "MS Pゴシック"
- ]
+ "fonts": [
+ "Arial",
+ "Arial Black",
+ "Bahnschrift",
+ "Calibri",
+ "Calibri Light",
+ "Cambria",
+ "Cambria Math",
+ "Candara",
+ "Candara Light",
+ "Comic Sans MS",
+ "Consolas",
+ "Constantia",
+ "Corbel",
+ "Corbel Light",
+ "Courier New",
+ "Ebrima",
+ "Franklin Gothic Medium",
+ "Gabriola",
+ "Gadugi",
+ "Georgia",
+ "HoloLens MDL2 Assets",
+ "Impact",
+ "Ink Free",
+ "Javanese Text",
+ "Leelawadee UI",
+ "Leelawadee UI Semilight",
+ "Lucida Console",
+ "Lucida Sans Unicode",
+ "MS Gothic",
+ "MS PGothic",
+ "MS UI Gothic",
+ "MV Boli",
+ "Malgun Gothic",
+ "Malgun Gothic Semilight",
+ "Marlett",
+ "Microsoft Himalaya",
+ "Microsoft JhengHei",
+ "Microsoft JhengHei Light",
+ "Microsoft JhengHei UI",
+ "Microsoft JhengHei UI Light",
+ "Microsoft New Tai Lue",
+ "Microsoft PhagsPa",
+ "Microsoft Sans Serif",
+ "Microsoft Tai Le",
+ "Microsoft YaHei",
+ "Microsoft YaHei Light",
+ "Microsoft YaHei UI",
+ "Microsoft YaHei UI Light",
+ "Microsoft Yi Baiti",
+ "MingLiU-ExtB",
+ "MingLiU_HKSCS-ExtB",
+ "Mongolian Baiti",
+ "Myanmar Text",
+ "NSimSun",
+ "Nirmala UI",
+ "Nirmala UI Semilight",
+ "PMingLiU-ExtB",
+ "Palatino Linotype",
+ "Segoe Fluent Icons",
+ "Segoe MDL2 Assets",
+ "Segoe Print",
+ "Segoe Script",
+ "Segoe UI",
+ "Segoe UI Black",
+ "Segoe UI Emoji",
+ "Segoe UI Historic",
+ "Segoe UI Light",
+ "Segoe UI Semibold",
+ "Segoe UI Semilight",
+ "Segoe UI Symbol",
+ "Segoe UI Variable",
+ "SimSun",
+ "SimSun-ExtB",
+ "Sitka",
+ "Sitka Text",
+ "Sylfaen",
+ "Symbol",
+ "Tahoma",
+ "Times New Roman",
+ "Trebuchet MS",
+ "Twemoji Mozilla",
+ "Verdana",
+ "Webdings",
+ "Wingdings",
+ "Yu Gothic",
+ "Yu Gothic Light",
+ "Yu Gothic Medium",
+ "Yu Gothic UI",
+ "Yu Gothic UI Light",
+ "Yu Gothic UI Semibold",
+ "Yu Gothic UI Semilight"
+ ],
+ "legacy_localized_fonts": [
+ "宋体",
+ "新宋体",
+ "微软雅黑",
+ "微软雅黑 Light",
+ "微軟正黑體",
+ "微軟正黑體 Light",
+ "細明體-ExtB",
+ "新細明體-ExtB",
+ "細明體_HKSCS-ExtB",
+ "游ゴシック",
+ "游ゴシック Light",
+ "游ゴシック Medium",
+ "MS ゴシック",
+ "MS Pゴシック",
+ "맑은 고딕",
+ "맑은 고딕 Semilight"
+ ]
}
diff --git a/internal/camoufoxnative/windows_voices.json b/internal/camoufoxnative/windows_voices.json
index 1d9bc712..995d1f1d 100644
--- a/internal/camoufoxnative/windows_voices.json
+++ b/internal/camoufoxnative/windows_voices.json
@@ -725,5 +725,67 @@
"Microsoft Hanhan Desktop - Chinese (Taiwan):zh-TW:local",
"Microsoft Zira Desktop - English (United States):en-US:local"
]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Ayumi - Japanese (Japan):ja-JP:local",
+ "Microsoft Haruka - Japanese (Japan):ja-JP:local",
+ "Microsoft Ichiro - Japanese (Japan):ja-JP:local",
+ "Microsoft Sayaka - Japanese (Japan):ja-JP:local",
+ "Microsoft Haruka Desktop - Japanese:ja-JP:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Danny - Chinese (Hong Kong SAR):zh-HK:local",
+ "Microsoft Tracy - Chinese (Hong Kong SAR):zh-HK:local",
+ "Microsoft Tracy Desktop - Chinese(Traditional, HongKong SAR):zh-HK:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Frank - Dutch (Netherlands):nl-NL:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Bengt - Swedish (Sweden):sv-SE:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Pattara - Thai (Thailand):th-TH:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft An - Vietnamese (Vietnam):vi-VN:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Ostap - Ukrainian (Ukraine):uk-UA:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
+ },
+ {
+ "weight": 1,
+ "voices": [
+ "Microsoft Asaf - Hebrew (Israel):he-IL:local",
+ "Microsoft Zira Desktop - English (United States):en-US:local"
+ ]
}
]
diff --git a/internal/camoufoxnative/windows_webgl.json b/internal/camoufoxnative/windows_webgl.json
index 1918fe93..039e8db3 100644
--- a/internal/camoufoxnative/windows_webgl.json
+++ b/internal/camoufoxnative/windows_webgl.json
@@ -1 +1,4543 @@
-[{"weight":0.2246278755074426,"config":{"webGl:renderer":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (NVIDIA)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212988,"35379":200704,"35380":256,"35657":4096,"35658":16380,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.2246278755074426,"config":{"webGl:renderer":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (NVIDIA)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212988,"35379":200704,"35380":256,"35657":4096,"35658":16380,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.18673883626522333,"config":{"webGl:renderer":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (Intel)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.1529093369418133,"config":{"webGl:renderer":"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (Intel)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":16,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.08254397834912046,"config":{"webGl:renderer":"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (AMD)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.05142083897158325,"config":{"webGl:renderer":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (AMD)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.01353179972936401,"config":{"webGl:renderer":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (NVIDIA)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212988,"35379":200704,"35380":256,"35657":4096,"35658":16380,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.012178619756427606,"config":{"webGl:renderer":"ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar","webGl:vendor":"Google Inc. (Microsoft)","webGl:contextAttributes":{"alpha":true,"antialias":false,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":0,"32937":0,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Microsoft)","37446":"ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":false,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":0,"32937":0,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":16,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Microsoft)","37446":"ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.006765899864682005,"config":{"webGl:renderer":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0)","webGl:vendor":"Google Inc. (Intel)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0)","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.004059539918809203,"config":{"webGl:renderer":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar","webGl:vendor":"Google Inc. (Intel)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":8192,"3386":[16383,16383],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":8192,"34045":null,"34047":null,"34068":null,"34076":8192,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":8192,"3386":[16383,16383],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":8192,"34045":2,"34047":null,"34068":null,"34076":8192,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":512,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":4,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.002706359945872802,"config":{"webGl:renderer":"ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)","webGl:vendor":"Google Inc. (Google)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_multi_draw"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":8192,"3386":[8192,8192],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"WebKit","7937":"WebKit WebGL","7938":"WebGL 1.0 (OpenGL ES 2.0 Chromium)","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1023],"33902":[1,1],"34016":33984,"34024":8192,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":32,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":32,"35661":64,"35723":null,"35724":"WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":1,"36347":4096,"36348":31,"36349":4096,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Google)","37446":"ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":15,"rangeMax":15,"precision":10},"35633,36337":{"rangeMin":15,"rangeMax":15,"precision":10},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":15,"rangeMax":14,"precision":0},"35633,36340":{"rangeMin":15,"rangeMax":14,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":15,"rangeMax":15,"precision":10},"35632,36337":{"rangeMin":15,"rangeMax":15,"precision":10},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":15,"rangeMax":14,"precision":0},"35632,36340":{"rangeMin":15,"rangeMax":14,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_color_buffer_half_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","EXT_texture_norm16","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_clip_cull_distance","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_lose_context","WEBGL_multi_draw"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":8192,"3386":[8192,8192],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"WebKit","7937":"WebKit WebGL","7938":"WebGL 2.0 (OpenGL ES 3.0 Chromium)","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1023],"33902":[1,1],"34016":33984,"34024":8192,"34045":15,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":1029,"34855":1029,"34856":1029,"34857":1029,"34858":1029,"34859":1029,"34860":1029,"34877":32774,"34921":16,"34930":32,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":14,"35373":14,"35374":60,"35375":72,"35376":65536,"35377":245760,"35379":245760,"35380":256,"35657":16384,"35658":16384,"35659":124,"35660":32,"35661":64,"35723":4352,"35724":"WebGL GLSL ES 3.00 (OpenGL ES GLSL ES 3.0 Chromium)","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":128,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":4,"36203":4294967294,"36345":1,"36347":4096,"36348":31,"36349":4096,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":128,"37157":128,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Google)","37446":"ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)","37447":0,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":15,"rangeMax":15,"precision":10},"35633,36337":{"rangeMin":15,"rangeMax":15,"precision":10},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":15,"rangeMax":14,"precision":0},"35633,36340":{"rangeMin":15,"rangeMax":14,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":15,"rangeMax":15,"precision":10},"35632,36337":{"rangeMin":15,"rangeMax":15,"precision":10},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":15,"rangeMax":14,"precision":0},"35632,36340":{"rangeMin":15,"rangeMax":14,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.0013531799729364013,"config":{"webGl:renderer":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0)","webGl:vendor":"Google Inc. (AMD)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,256,256],"3024":true,"3042":false,"3074":null,"3088":[0,0,256,256],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,256,256],"3024":true,"3042":false,"3074":1029,"3088":[0,0,256,256],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (AMD)","37446":"ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0)","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.001353179972936401,"config":{"webGl:renderer":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1)","webGl:vendor":"Google Inc. (Intel)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":8192,"3386":[16383,16383],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1)","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":8192,"34045":null,"34047":null,"34068":null,"34076":8192,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":8192,"3386":[16383,16383],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1)","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":8192,"34045":2,"34047":null,"34068":null,"34076":8192,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":512,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212992,"35379":200704,"35380":256,"35657":4096,"35658":16384,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":4,"36203":4294967294,"36345":null,"36347":4096,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (Intel)","37446":"ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1)","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.001353179972936401,"config":{"webGl:renderer":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0)","webGl:vendor":"Google Inc. (NVIDIA)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212988,"35379":200704,"35380":256,"35657":4096,"35658":16380,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0)","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}},{"weight":0.001353179972936401,"config":{"webGl:renderer":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0)","webGl:vendor":"Google Inc. (NVIDIA)","webGl:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl:supportedExtensions":["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_color_buffer_half_float","EXT_float_blend","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_float_linear","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_depth_texture","WEBGL_draw_buffers","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":null,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":null,"3315":null,"3316":null,"3317":4,"3330":null,"3331":null,"3332":null,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 1.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":null,"32878":null,"32883":null,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":null,"33001":null,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":null,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":null,"34853":null,"34854":null,"34855":null,"34856":null,"34857":null,"34858":null,"34859":null,"34860":null,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":null,"35076":null,"35077":null,"35371":null,"35373":null,"35374":null,"35375":null,"35376":null,"35377":null,"35379":null,"35380":null,"35657":null,"35658":null,"35659":null,"35660":16,"35661":32,"35723":null,"35724":"WebGL GLSL ES 1.0","35725":null,"35738":5121,"35739":6408,"35968":null,"35977":null,"35978":null,"35979":null,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":null,"36183":null,"36203":null,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":null,"36388":null,"36392":null,"36795":null,"37137":null,"37154":null,"37157":null,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0)","37447":null,"38449":null},"webGl:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}},"webGl2:contextAttributes":{"alpha":true,"antialias":true,"depth":true,"failIfMajorPerformanceCaveat":false,"powerPreference":"default","premultipliedAlpha":true,"preserveDrawingBuffer":false,"stencil":false},"webGl2:supportedExtensions":["EXT_color_buffer_float","EXT_float_blend","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","OES_draw_buffers_indexed","OES_texture_float_linear","OVR_multiview2","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_provoking_vertex"],"webGl2:parameters":{"2849":1,"2884":false,"2885":1029,"2886":2305,"2928":[0,1],"2929":false,"2930":true,"2931":1,"2932":513,"2960":false,"2961":0,"2962":519,"2963":2147483647,"2964":7680,"2965":7680,"2966":7680,"2967":0,"2968":2147483647,"2978":[0,0,300,150],"3024":true,"3042":false,"3074":1029,"3088":[0,0,300,150],"3089":false,"3106":[0,0,0,0],"3107":[true,true,true,true],"3314":0,"3315":0,"3316":0,"3317":4,"3330":0,"3331":0,"3332":0,"3333":4,"3379":16384,"3386":[32767,32767],"3408":4,"3410":8,"3411":8,"3412":8,"3413":8,"3414":24,"3415":0,"7936":"Mozilla","7937":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0)","7938":"WebGL 2.0","10752":0,"32773":[0,0,0,0],"32777":32774,"32823":false,"32824":0,"32873":null,"32877":0,"32878":0,"32883":2048,"32926":false,"32928":false,"32936":1,"32937":4,"32938":1,"32939":false,"32968":0,"32969":1,"32970":0,"32971":1,"33000":2147483647,"33001":2147483647,"33170":4352,"33901":[1,1024],"33902":[1,1],"34016":33984,"34024":16384,"34045":2,"34047":null,"34068":null,"34076":16384,"34467":null,"34816":519,"34817":7680,"34818":7680,"34819":7680,"34852":8,"34853":1029,"34854":0,"34855":0,"34856":0,"34857":0,"34858":0,"34859":0,"34860":0,"34877":32774,"34921":16,"34930":16,"34964":null,"34965":null,"35071":2048,"35076":-8,"35077":7,"35371":12,"35373":12,"35374":24,"35375":24,"35376":65536,"35377":212988,"35379":200704,"35380":256,"35657":4096,"35658":16380,"35659":120,"35660":16,"35661":32,"35723":4352,"35724":"WebGL GLSL ES 3.00","35725":null,"35738":5121,"35739":6408,"35968":4,"35977":false,"35978":120,"35979":4,"36003":0,"36004":2147483647,"36005":2147483647,"36006":null,"36007":null,"36063":8,"36183":8,"36203":4294967294,"36345":null,"36347":4095,"36348":30,"36349":1024,"36387":false,"36388":false,"36392":null,"36795":null,"37137":0,"37154":120,"37157":120,"37440":false,"37441":false,"37443":37444,"37444":null,"37445":"Google Inc. (NVIDIA)","37446":"ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0)","37447":1000000000,"38449":null},"webGl2:shaderPrecisionFormats":{"35633,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35633,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35633,36341":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36336":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36337":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36338":{"rangeMin":127,"rangeMax":127,"precision":23},"35632,36339":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36340":{"rangeMin":31,"rangeMax":30,"precision":0},"35632,36341":{"rangeMin":31,"rangeMax":30,"precision":0}}}}]
+[
+ {
+ "weight": 0.2246278755074426,
+ "config": {
+ "webGl:renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (NVIDIA)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4095,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (NVIDIA)",
+ "37446": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212988,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16380,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 8,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4095,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (NVIDIA)",
+ "37446": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.18673883626522333,
+ "config": {
+ "webGl:renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (Intel)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 8,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.1529093369418133,
+ "config": {
+ "webGl:renderer": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (Intel)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 16,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics 400 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.08254397834912046,
+ "config": {
+ "webGl:renderer": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (AMD)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (AMD)",
+ "37446": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 8,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (AMD)",
+ "37446": "ANGLE (AMD, Radeon HD 3200 Graphics Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.05142083897158325,
+ "config": {
+ "webGl:renderer": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (AMD)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (AMD)",
+ "37446": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 8,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (AMD)",
+ "37446": "ANGLE (AMD, Radeon R9 200 Series Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.01353179972936401,
+ "config": {
+ "webGl:renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (NVIDIA)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4095,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (NVIDIA)",
+ "37446": "ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212988,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16380,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 8,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4095,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (NVIDIA)",
+ "37446": "ANGLE (NVIDIA, NVIDIA GeForce GTX 480 Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.012178619756427606,
+ "config": {
+ "webGl:renderer": "ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar",
+ "webGl:vendor": "Google Inc. (Microsoft)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": false,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 0,
+ "32937": 0,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Microsoft)",
+ "37446": "ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": false,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_bptc",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "OVR_multiview2",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 16384,
+ "3386": [
+ 32767,
+ 32767
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 0,
+ "32937": 0,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 16384,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 16384,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 2048,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 16,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Microsoft)",
+ "37446": "ANGLE (Microsoft, Microsoft Basic Render Driver Direct3D11 vs_5_0 ps_5_0), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ },
+ {
+ "weight": 0.004059539918809203,
+ "config": {
+ "webGl:renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar",
+ "webGl:vendor": "Google Inc. (Intel)",
+ "webGl:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl:supportedExtensions": [
+ "ANGLE_instanced_arrays",
+ "EXT_blend_minmax",
+ "EXT_color_buffer_half_float",
+ "EXT_float_blend",
+ "EXT_frag_depth",
+ "EXT_shader_texture_lod",
+ "EXT_sRGB",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_element_index_uint",
+ "OES_fbo_render_mipmap",
+ "OES_standard_derivatives",
+ "OES_texture_float",
+ "OES_texture_float_linear",
+ "OES_texture_half_float",
+ "OES_texture_half_float_linear",
+ "OES_vertex_array_object",
+ "WEBGL_color_buffer_float",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_depth_texture",
+ "WEBGL_draw_buffers",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": null,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": null,
+ "3315": null,
+ "3316": null,
+ "3317": 4,
+ "3330": null,
+ "3331": null,
+ "3332": null,
+ "3333": 4,
+ "3379": 8192,
+ "3386": [
+ 16383,
+ 16383
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar",
+ "7938": "WebGL 1.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": null,
+ "32878": null,
+ "32883": null,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": null,
+ "33001": null,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 8192,
+ "34045": null,
+ "34047": null,
+ "34068": null,
+ "34076": 8192,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": null,
+ "34853": null,
+ "34854": null,
+ "34855": null,
+ "34856": null,
+ "34857": null,
+ "34858": null,
+ "34859": null,
+ "34860": null,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": null,
+ "35076": null,
+ "35077": null,
+ "35371": null,
+ "35373": null,
+ "35374": null,
+ "35375": null,
+ "35376": null,
+ "35377": null,
+ "35379": null,
+ "35380": null,
+ "35657": null,
+ "35658": null,
+ "35659": null,
+ "35660": 16,
+ "35661": 32,
+ "35723": null,
+ "35724": "WebGL GLSL ES 1.0",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": null,
+ "35977": null,
+ "35978": null,
+ "35979": null,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": null,
+ "36183": null,
+ "36203": null,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": null,
+ "36388": null,
+ "36392": null,
+ "36795": null,
+ "37137": null,
+ "37154": null,
+ "37157": null,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar",
+ "37447": null,
+ "38449": null
+ },
+ "webGl:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ },
+ "webGl2:contextAttributes": {
+ "alpha": true,
+ "antialias": true,
+ "depth": true,
+ "failIfMajorPerformanceCaveat": false,
+ "powerPreference": "default",
+ "premultipliedAlpha": true,
+ "preserveDrawingBuffer": false,
+ "stencil": false
+ },
+ "webGl2:supportedExtensions": [
+ "EXT_color_buffer_float",
+ "EXT_float_blend",
+ "EXT_texture_compression_rgtc",
+ "EXT_texture_filter_anisotropic",
+ "OES_draw_buffers_indexed",
+ "OES_texture_float_linear",
+ "WEBGL_compressed_texture_s3tc",
+ "WEBGL_compressed_texture_s3tc_srgb",
+ "WEBGL_debug_renderer_info",
+ "WEBGL_debug_shaders",
+ "WEBGL_lose_context",
+ "WEBGL_provoking_vertex"
+ ],
+ "webGl2:parameters": {
+ "2849": 1,
+ "2884": false,
+ "2885": 1029,
+ "2886": 2305,
+ "2928": [
+ 0,
+ 1
+ ],
+ "2929": false,
+ "2930": true,
+ "2931": 1,
+ "2932": 513,
+ "2960": false,
+ "2961": 0,
+ "2962": 519,
+ "2963": 2147483647,
+ "2964": 7680,
+ "2965": 7680,
+ "2966": 7680,
+ "2967": 0,
+ "2968": 2147483647,
+ "2978": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3024": true,
+ "3042": false,
+ "3074": 1029,
+ "3088": [
+ 0,
+ 0,
+ 300,
+ 150
+ ],
+ "3089": false,
+ "3106": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "3107": [
+ true,
+ true,
+ true,
+ true
+ ],
+ "3314": 0,
+ "3315": 0,
+ "3316": 0,
+ "3317": 4,
+ "3330": 0,
+ "3331": 0,
+ "3332": 0,
+ "3333": 4,
+ "3379": 8192,
+ "3386": [
+ 16383,
+ 16383
+ ],
+ "3408": 4,
+ "3410": 8,
+ "3411": 8,
+ "3412": 8,
+ "3413": 8,
+ "3414": 24,
+ "3415": 0,
+ "7936": "Mozilla",
+ "7937": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar",
+ "7938": "WebGL 2.0",
+ "10752": 0,
+ "32773": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "32777": 32774,
+ "32823": false,
+ "32824": 0,
+ "32873": null,
+ "32877": 0,
+ "32878": 0,
+ "32883": 2048,
+ "32926": false,
+ "32928": false,
+ "32936": 1,
+ "32937": 4,
+ "32938": 1,
+ "32939": false,
+ "32968": 0,
+ "32969": 1,
+ "32970": 0,
+ "32971": 1,
+ "33000": 2147483647,
+ "33001": 2147483647,
+ "33170": 4352,
+ "33901": [
+ 1,
+ 1024
+ ],
+ "33902": [
+ 1,
+ 1
+ ],
+ "34016": 33984,
+ "34024": 8192,
+ "34045": 2,
+ "34047": null,
+ "34068": null,
+ "34076": 8192,
+ "34467": null,
+ "34816": 519,
+ "34817": 7680,
+ "34818": 7680,
+ "34819": 7680,
+ "34852": 8,
+ "34853": 1029,
+ "34854": 0,
+ "34855": 0,
+ "34856": 0,
+ "34857": 0,
+ "34858": 0,
+ "34859": 0,
+ "34860": 0,
+ "34877": 32774,
+ "34921": 16,
+ "34930": 16,
+ "34964": null,
+ "34965": null,
+ "35071": 512,
+ "35076": -8,
+ "35077": 7,
+ "35371": 12,
+ "35373": 12,
+ "35374": 24,
+ "35375": 24,
+ "35376": 65536,
+ "35377": 212992,
+ "35379": 200704,
+ "35380": 256,
+ "35657": 4096,
+ "35658": 16384,
+ "35659": 120,
+ "35660": 16,
+ "35661": 32,
+ "35723": 4352,
+ "35724": "WebGL GLSL ES 3.00",
+ "35725": null,
+ "35738": 5121,
+ "35739": 6408,
+ "35968": 4,
+ "35977": false,
+ "35978": 120,
+ "35979": 4,
+ "36003": 0,
+ "36004": 2147483647,
+ "36005": 2147483647,
+ "36006": null,
+ "36007": null,
+ "36063": 8,
+ "36183": 4,
+ "36203": 4294967294,
+ "36345": null,
+ "36347": 4096,
+ "36348": 30,
+ "36349": 1024,
+ "36387": false,
+ "36388": false,
+ "36392": null,
+ "36795": null,
+ "37137": 0,
+ "37154": 120,
+ "37157": 120,
+ "37440": false,
+ "37441": false,
+ "37443": 37444,
+ "37444": null,
+ "37445": "Google Inc. (Intel)",
+ "37446": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_4_1 ps_4_1), or similar",
+ "37447": 1000000000,
+ "38449": null
+ },
+ "webGl2:shaderPrecisionFormats": {
+ "35633,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35633,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35633,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36336": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36337": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36338": {
+ "rangeMin": 127,
+ "rangeMax": 127,
+ "precision": 23
+ },
+ "35632,36339": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36340": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ },
+ "35632,36341": {
+ "rangeMin": 31,
+ "rangeMax": 30,
+ "precision": 0
+ }
+ }
+ }
+ }
+]
diff --git a/internal/camoufoxnative/worker.go b/internal/camoufoxnative/worker.go
index abe4c20e..f6b43106 100644
--- a/internal/camoufoxnative/worker.go
+++ b/internal/camoufoxnative/worker.go
@@ -59,6 +59,10 @@ type Worker struct {
cookieOrder map[cookieKey]int
// pageCatalog 是页面载入时目录 RPC 的响应正文
pageCatalog PageCatalog
+ // driveToken、driveTokenAt 与 driveDenied 是页面冷启动 GenerateAccessToken 观察到的 Drive 令牌与 401 状态
+ driveToken string
+ driveTokenAt time.Time
+ driveDenied bool
// options 是启动选项,重新载入页面时沿用
options Options
// tabs 是有进行中受保护请求或已被替换的标签页,键为标签页的 context
@@ -298,7 +302,9 @@ func (worker *Worker) boostFrames(ctx context.Context) (func(), error) {
if _, err := worker.chromeEvaluate(ctx, "Services.prefs.setIntPref('gfx.display.frame-rate-divisor', 1); gBrowser.selectedBrowser.renderLayers = true"); err != nil {
return nil, fmt.Errorf("提高 Camoufox 刷新帧率: %w", err)
}
- worker.idle.Stop()
+ if worker.idle != nil {
+ worker.idle.Stop()
+ }
}
worker.frameBoosts++
var once sync.Once
@@ -315,7 +321,9 @@ func (worker *Worker) boostFrames(ctx context.Context) (func(), error) {
if _, err := worker.chromeEvaluate(restoreCtx, idleRenderingExpression); err != nil {
slog.Warn("恢复 Camoufox 刷新帧率失败", "error", err)
}
- worker.idle.Reset(idleMinimizeDelay)
+ if worker.idle != nil {
+ worker.idle.Reset(idleMinimizeDelay)
+ }
})
}, nil
}
@@ -466,6 +474,13 @@ func (worker *Worker) PageCatalog() PageCatalog {
return worker.pageCatalog
}
+// DriveAccessToken 返回当前页面冷启动时观察到的 Drive access token、取得时刻与是否被 401 拒绝
+func (worker *Worker) DriveAccessToken() (string, time.Time, bool) {
+ worker.mu.Lock()
+ defer worker.mu.Unlock()
+ return worker.driveToken, worker.driveTokenAt, worker.driveDenied
+}
+
// Reload 在新标签页中按官网冷启动重新载入页面,载入成功后切换过去并关闭空闲旧标签页,有进行中请求的旧标签页在其请求结束后关闭;载入失败时关闭新标签页并保留原页面
func (worker *Worker) Reload(ctx context.Context) error {
worker.mu.Lock()
@@ -478,32 +493,23 @@ func (worker *Worker) Reload(ctx context.Context) error {
options.StartupProgress = nil
worker.lockInput()
defer worker.inputMu.Unlock()
+ unboost, err := worker.boostFrames(ctx)
+ if err != nil {
+ return err
+ }
+ defer unboost()
contextID, err := worker.openTab(ctx)
if err != nil {
return err
}
loaded, err := worker.openPage(ctx, options, contextID)
- if err == nil && options.Headless && !options.liveView {
- err = worker.stopRendering(ctx)
- }
if err != nil {
worker.mu.Lock()
if worker.selected == contextID {
worker.selected = ""
}
worker.mu.Unlock()
- closeErr := worker.closeTab(contextID)
- if closeErr == nil && options.Headless && !options.liveView {
- worker.frameMu.Lock()
- idle := worker.frameBoosts == 0
- worker.frameMu.Unlock()
- if idle {
- stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- _ = worker.stopRendering(stopCtx)
- cancel()
- }
- }
- return errors.Join(err, closeErr)
+ return errors.Join(err, worker.closeTab(contextID))
}
return worker.switchTab(contextID, loaded)
}
@@ -518,6 +524,7 @@ func (worker *Worker) switchTab(contextID string, loaded loadedPage) error {
}
worker.reloads++
worker.contextID, worker.page, worker.state, worker.pageCatalog = contextID, loaded.page, loaded.state, loaded.catalog
+ worker.driveToken, worker.driveTokenAt, worker.driveDenied = loaded.driveToken, loaded.driveTokenAt, loaded.driveDenied
worker.chats = []*chatTab{{contextID: contextID, page: loaded.page}}
worker.syncReadyPages()
if previous != contextID || worker.selected == "" {
@@ -805,6 +812,7 @@ func (worker *Worker) bootstrap(ctx context.Context, options Options, storage st
return err
}
worker.page, worker.state, worker.pageCatalog = loaded.page, loaded.state, loaded.catalog
+ worker.driveToken, worker.driveTokenAt, worker.driveDenied = loaded.driveToken, loaded.driveTokenAt, loaded.driveDenied
worker.chats, worker.selected = []*chatTab{{contextID: contextID, page: loaded.page}}, contextID
worker.syncReadyPages()
return nil
@@ -832,9 +840,12 @@ func (worker *Worker) ReadyPages() int {
// loadedPage 是一次官网页面载入取得的 WAA 页面对象、页面状态与目录 RPC 响应
type loadedPage struct {
- page pageHandle
- state State
- catalog PageCatalog
+ page pageHandle
+ state State
+ catalog PageCatalog
+ driveToken string
+ driveTokenAt time.Time
+ driveDenied bool
}
// openPage 在 contextID 标签页中按官网冷启动载入新对话页:preload 在官网 WAA service 首次取请求头时交出该实例,页面载入期间记下目录 RPC 响应与第一个带 x-aistudio-visit-id 的 MakerSuite 请求的公共头,等官方 WAA 程序的图片请求结束或到达上限后返回页面对象
@@ -982,6 +993,9 @@ func (worker *Worker) openPage(ctx context.Context, options Options, contextID s
if err != nil {
return loadedPage{}, err
}
+ if tsdtv, evalErr := client.evaluateString(ctx, contextID, pageTSDtVExpression); evalErr == nil {
+ catalog.BuildAgency = BuildAgencyFromTSDtV(tsdtv)
+ }
options.reportStartup(StartupLocatingWAA)
serviceCtx, cancelService := context.WithTimeout(ctx, 30*time.Second)
service, err := services.next(serviceCtx)
@@ -1002,6 +1016,7 @@ func (worker *Worker) openPage(ctx context.Context, options Options, contextID s
client.mu.Lock()
observed := client.loads[contextID].headers
client.mu.Unlock()
+ driveToken, driveTokenAt, driveDenied := client.pageAccessToken(ctx, contextID, catalogCollector)
if err := release(); err != nil {
return loadedPage{}, err
}
@@ -1030,7 +1045,7 @@ func (worker *Worker) openPage(ctx context.Context, options Options, contextID s
return loadedPage{}, fmt.Errorf("官网 MakerSuite 请求缺少必要公共头 %s", name)
}
}
- return loadedPage{page: page, catalog: catalog, state: State{
+ return loadedPage{page: page, catalog: catalog, driveToken: driveToken, driveTokenAt: driveTokenAt, driveDenied: driveDenied, state: State{
PID: worker.process.command.Process.Pid,
PageURL: pageURL,
UserAgent: headers.Get("user-agent"),
diff --git a/internal/chromeauth/protocol.go b/internal/chromeauth/protocol.go
index 65cb2777..eaa2bed3 100644
--- a/internal/chromeauth/protocol.go
+++ b/internal/chromeauth/protocol.go
@@ -435,11 +435,7 @@ func appendVarintField(output []byte, number int, value uint64) []byte {
}
func appendVarint(output []byte, value uint64) []byte {
- for value >= 0x80 {
- output = append(output, byte(value)|0x80)
- value >>= 7
- }
- return append(output, byte(value))
+ return binary.AppendUvarint(output, value)
}
func parsePublicKeyBlob(blob []byte) ([]byte, error) {
diff --git a/internal/config/config.go b/internal/config/config.go
index 42068cf1..f168c386 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -28,61 +28,87 @@ const (
defaultAccountConcurrency = 2
)
-var configKeys = [...]string{
- "AISTUDIO_AUTH_STATES",
- "LISTEN_ADDR",
- "PREVIEW_LISTEN_ADDR",
- "PROXY_API_KEY",
- "API_KEY_ACCOUNTS",
- "PROXY",
- "INIT_TIMEOUT",
- "REQUEST_TIMEOUT",
- "WARM_WORKER_LIMIT",
- "MAX_ACTIVE_WORKERS",
- "WARM_STARTUP_CONCURRENCY",
- "PER_ACCOUNT_CONCURRENCY",
- "ROUTING_STRATEGY",
- "ACCOUNT_ORDER",
- "MAX_ACCOUNT_SWITCHES",
- "ACCOUNT_SWITCH_INTERVAL",
- "MAX_QUOTA_SWITCHES",
- "UPSTREAM_CHANNELS",
- "MODEL_MAPPING",
- "MODEL_CHANNELS",
- "MODEL_ACCOUNTS",
- "HIDE_MODELS",
- "GENERATE_CONTENT_ACCOUNTS",
- "WAA_BACKEND",
- "MEDIA_OUTPUT",
- "MEDIA_BASE_URL",
- "AUTO_START",
- "HIDE_DOCK_ICON",
- "REQUEST_BODY_LOG",
- "LOG_FILE",
- "LOG_MAX_TOTAL_MB",
- "ADMIN_AUTH_ENABLED",
- "ADMIN_USERNAME",
- "ADMIN_PASSWORD",
- "BUILD_NATIVE_NONSTREAM",
- "BUILD_CHAT_MODELS",
- "NONSTREAM_KEEPALIVE",
- "FAKE_STREAM",
- "YOUTUBE_LINKS",
- "STRIP_THOUGHT_SIGNATURES",
- "SEARCH_MODEL_ALIASES",
- "DISCOVER_HIDDEN_MODELS",
- "GOOGLE_SEARCH",
- "FIRST_EVENT_HEDGE",
- "FIRST_EVENT_HEDGE_MODELS",
- "FIRST_EVENT_TIMEOUT",
- "CONTINUATION_REWRITE",
- "CONTINUATION_PROMPT",
- "REPLY_TOOL",
- "USER_MESSAGE_REWRITE",
- "THINKING_GUARD",
- "SILLYTAVERN_API_KEYS",
+// configField 描述一个配置键在 Config 中的读写方式
+type configField struct {
+ key string
+ set func(*Config, string) error
+ get func(Config) string
}
+// configFields 按写入 .env 的固定顺序列出全部配置键
+var configFields = []configField{
+ textField("AISTUDIO_AUTH_STATES", func(c *Config) *string { return &c.AuthStates }, strings.TrimSpace),
+ textField("LISTEN_ADDR", func(c *Config) *string { return &c.ListenAddr }, strings.TrimSpace),
+ textField("PREVIEW_LISTEN_ADDR", func(c *Config) *string { return &c.PreviewListenAddr }, strings.TrimSpace),
+ textField("PROXY_API_KEY", func(c *Config) *string { return &c.ProxyAPIKey }, strings.TrimSpace),
+ textField("API_KEY_ACCOUNTS", func(c *Config) *string { return &c.APIKeyAccounts }, strings.TrimSpace),
+ textField("PROXY", func(c *Config) *string { return &c.Proxy }, strings.TrimSpace),
+ durationField("INIT_TIMEOUT", func(c *Config) *time.Duration { return &c.InitTimeout }),
+ durationField("REQUEST_TIMEOUT", func(c *Config) *time.Duration { return &c.RequestTimeout }),
+ intField("WARM_WORKER_LIMIT", func(c *Config) *int { return &c.WarmWorkerLimit }),
+ intField("MAX_ACTIVE_WORKERS", func(c *Config) *int { return &c.MaxActiveWorkers }),
+ intField("WARM_STARTUP_CONCURRENCY", func(c *Config) *int { return &c.WarmStartupConcurrency }),
+ intField("PER_ACCOUNT_CONCURRENCY", func(c *Config) *int { return &c.PerAccountConcurrency }),
+ textField("ROUTING_STRATEGY", func(c *Config) *string { return &c.RoutingStrategy }, strings.TrimSpace),
+ textField("ACCOUNT_ORDER", func(c *Config) *string { return &c.AccountOrder }, strings.TrimSpace),
+ {
+ key: "MAX_ACCOUNT_SWITCHES",
+ set: setMaxAccountSwitches,
+ get: func(c Config) string { return strconv.Itoa(c.MaxAccountSwitches) },
+ },
+ textField("ACCOUNT_SWITCH_INTERVAL", func(c *Config) *string { return &c.AccountSwitchInterval }, lowerTrim),
+ textField("MAX_QUOTA_SWITCHES", func(c *Config) *string { return &c.MaxQuotaSwitches }, lowerTrim),
+ {
+ key: "UPSTREAM_CHANNELS",
+ set: func(c *Config, value string) error { c.UpstreamChannels = parseUpstreamChannels(value); return nil },
+ get: func(c Config) string { return strings.Join(c.UpstreamChannels, ",") },
+ },
+ textField("MODEL_MAPPING", func(c *Config) *string { return &c.ModelMapping }, strings.TrimSpace),
+ textField("MODEL_CHANNELS", func(c *Config) *string { return &c.ModelChannels }, strings.TrimSpace),
+ textField("MODEL_ACCOUNTS", func(c *Config) *string { return &c.ModelAccounts }, strings.TrimSpace),
+ textField("HIDE_MODELS", func(c *Config) *string { return &c.HideModels }, strings.TrimSpace),
+ textField("GENERATE_CONTENT_ACCOUNTS", func(c *Config) *string { return &c.GenerateContentAccounts }, strings.TrimSpace),
+ textField("WAA_BACKEND", func(c *Config) *string { return &c.WAABackend }, lowerTrim),
+ textField("MEDIA_OUTPUT", func(c *Config) *string { return &c.MediaOutput }, lowerTrim),
+ textField("MEDIA_BASE_URL", func(c *Config) *string { return &c.MediaBaseURL }, strings.TrimSpace),
+ boolField("AUTO_START", func(c *Config) *bool { return &c.AutoStart }),
+ boolField("HIDE_DOCK_ICON", func(c *Config) *bool { return &c.HideDockIcon }),
+ boolField("REQUEST_BODY_LOG", func(c *Config) *bool { return &c.RequestBodyLog }),
+ boolField("LOG_FILE", func(c *Config) *bool { return &c.LogFile }),
+ intField("LOG_MAX_TOTAL_MB", func(c *Config) *int { return &c.LogMaxTotalMB }),
+ boolField("ADMIN_AUTH_ENABLED", func(c *Config) *bool { return &c.AdminAuthEnabled }),
+ textField("ADMIN_USERNAME", func(c *Config) *string { return &c.AdminUsername }, strings.TrimSpace),
+ textField("ADMIN_PASSWORD", func(c *Config) *string { return &c.AdminPassword }, nil),
+ boolField("BUILD_NATIVE_NONSTREAM", func(c *Config) *bool { return &c.BuildNativeNonstream }),
+ boolField("BUILD_CHAT_MODELS", func(c *Config) *bool { return &c.BuildChatModels }),
+ textField("BUILD_CHAT_PROTOCOL", func(c *Config) *string { return &c.BuildChatProtocol }, lowerTrim),
+ boolField("NONSTREAM_KEEPALIVE", func(c *Config) *bool { return &c.NonstreamKeepalive }),
+ boolField("FAKE_STREAM", func(c *Config) *bool { return &c.FakeStream }),
+ boolField("YOUTUBE_LINKS", func(c *Config) *bool { return &c.YouTubeLinks }),
+ boolField("STRIP_THOUGHT_SIGNATURES", func(c *Config) *bool { return &c.StripThoughtSignatures }),
+ boolField("SEARCH_MODEL_ALIASES", func(c *Config) *bool { return &c.SearchModelAliases }),
+ boolField("DISCOVER_HIDDEN_MODELS", func(c *Config) *bool { return &c.DiscoverHiddenModels }),
+ boolField("GOOGLE_SEARCH", func(c *Config) *bool { return &c.GoogleSearch }),
+ textField("FIRST_EVENT_HEDGE", func(c *Config) *string { return &c.FirstEventHedge }, lowerTrim),
+ textField("FIRST_EVENT_HEDGE_MODELS", func(c *Config) *string { return &c.FirstEventHedgeModels }, strings.TrimSpace),
+ textField("FIRST_EVENT_TIMEOUT", func(c *Config) *string { return &c.FirstEventTimeout }, lowerTrim),
+ boolField("CONTINUATION_REWRITE", func(c *Config) *bool { return &c.ContinuationRewrite }),
+ textField("CONTINUATION_PROMPT", func(c *Config) *string { return &c.ContinuationPrompt }, strings.TrimSpace),
+ boolField("REPLY_TOOL", func(c *Config) *bool { return &c.ReplyTool }),
+ textField("USER_MESSAGE_REWRITE", func(c *Config) *string { return &c.UserMessageRewrite }, lowerTrim),
+ boolField("THINKING_GUARD", func(c *Config) *bool { return &c.ThinkingGuard }),
+ textField("SILLYTAVERN_API_KEYS", func(c *Config) *string { return &c.SillyTavernAPIKeys }, strings.TrimSpace),
+}
+
+// configFieldByKey 按键名索引配置字段
+var configFieldByKey = func() map[string]configField {
+ byKey := make(map[string]configField, len(configFields))
+ for _, field := range configFields {
+ byKey[field.key] = field
+ }
+ return byKey
+}()
+
// LogFileMB 是单个日志文件的轮转大小
const LogFileMB = 10
@@ -134,6 +160,15 @@ const UserMessageRewriteTraditional = "traditional"
// UserMessageRewriteMartian 表示发送前将用户消息中的中文转为火星文
const UserMessageRewriteMartian = "martian"
+// BuildChatProtocolAuto 表示按账户页面启动数据标志 45831005 自适应选择 Build 对话协议
+const BuildChatProtocolAuto = "auto"
+
+// BuildChatProtocolAgency 表示固定使用新版 agency 协议(StreamRunAgentTask)
+const BuildChatProtocolAgency = "agency"
+
+// BuildChatProtocolLegacy 表示固定使用旧版接口(CodeAssistantOffline)
+const BuildChatProtocolLegacy = "legacy"
+
// DefaultContinuationPrompt 是 CONTINUATION_PROMPT 未设置时改写末尾 assistant 轮所用的续写提示词
const DefaultContinuationPrompt = "Continue the assistant response after the following prefix. Return only the continuation, without repeating the prefix."
@@ -193,6 +228,8 @@ type Config struct {
Environment []string
// BuildChatModels 让公开 API 提供并接受 Build 对话模型(-build)
BuildChatModels bool
+ // BuildChatProtocol 控制 -build 对话模型使用的上游协议:auto(默认,按账户页面标志 45831005 选择)、agency 或 legacy
+ BuildChatProtocol string
// HideModels 是不在公开 API 中提供的目录模型 ID,逗号分隔
HideModels string
// GenerateContentAccounts 是被迁移到任务接口的模型改走 GenerateContent 的账户 ID,逗号分隔
@@ -221,6 +258,7 @@ func Default() Config {
LogMaxTotalMB: 500,
BuildNativeNonstream: true,
BuildChatModels: true,
+ BuildChatProtocol: BuildChatProtocolAuto,
NonstreamKeepalive: true,
SearchModelAliases: true,
FirstEventHedge: FirstEventHedgeOff,
@@ -266,102 +304,66 @@ func invalidValue(key, value string, err error) InvalidValue {
return InvalidValue{Key: key, Value: value, Reason: err.Error()}
}
-// configSetters 把每个配置键的文本值解析到 Config
-var configSetters = map[string]func(*Config, string) error{
- "AUTO_START": boolSetter("AUTO_START", func(c *Config) *bool { return &c.AutoStart }),
- "HIDE_DOCK_ICON": boolSetter("HIDE_DOCK_ICON", func(c *Config) *bool { return &c.HideDockIcon }),
- "REQUEST_BODY_LOG": boolSetter("REQUEST_BODY_LOG", func(c *Config) *bool { return &c.RequestBodyLog }),
- "LOG_FILE": boolSetter("LOG_FILE", func(c *Config) *bool { return &c.LogFile }),
- "ADMIN_AUTH_ENABLED": boolSetter("ADMIN_AUTH_ENABLED", func(c *Config) *bool { return &c.AdminAuthEnabled }),
- "BUILD_NATIVE_NONSTREAM": boolSetter("BUILD_NATIVE_NONSTREAM", func(c *Config) *bool { return &c.BuildNativeNonstream }),
- "NONSTREAM_KEEPALIVE": boolSetter("NONSTREAM_KEEPALIVE", func(c *Config) *bool { return &c.NonstreamKeepalive }),
- "FAKE_STREAM": boolSetter("FAKE_STREAM", func(c *Config) *bool { return &c.FakeStream }),
- "SEARCH_MODEL_ALIASES": boolSetter("SEARCH_MODEL_ALIASES", func(c *Config) *bool { return &c.SearchModelAliases }),
- "DISCOVER_HIDDEN_MODELS": boolSetter("DISCOVER_HIDDEN_MODELS", func(c *Config) *bool { return &c.DiscoverHiddenModels }),
- "GOOGLE_SEARCH": boolSetter("GOOGLE_SEARCH", func(c *Config) *bool { return &c.GoogleSearch }),
- "YOUTUBE_LINKS": boolSetter("YOUTUBE_LINKS", func(c *Config) *bool { return &c.YouTubeLinks }),
- "STRIP_THOUGHT_SIGNATURES": boolSetter("STRIP_THOUGHT_SIGNATURES", func(c *Config) *bool { return &c.StripThoughtSignatures }),
- "CONTINUATION_REWRITE": boolSetter("CONTINUATION_REWRITE", func(c *Config) *bool { return &c.ContinuationRewrite }),
- "REPLY_TOOL": boolSetter("REPLY_TOOL", func(c *Config) *bool { return &c.ReplyTool }),
- "USER_MESSAGE_REWRITE": textSetter(func(c *Config) *string { return &c.UserMessageRewrite }, lowerTrim),
- "THINKING_GUARD": boolSetter("THINKING_GUARD", func(c *Config) *bool { return &c.ThinkingGuard }),
- "LOG_MAX_TOTAL_MB": intSetter("LOG_MAX_TOTAL_MB", func(c *Config) *int { return &c.LogMaxTotalMB }),
- "WARM_WORKER_LIMIT": intSetter("WARM_WORKER_LIMIT", func(c *Config) *int { return &c.WarmWorkerLimit }),
- "MAX_ACTIVE_WORKERS": intSetter("MAX_ACTIVE_WORKERS", func(c *Config) *int { return &c.MaxActiveWorkers }),
- "WARM_STARTUP_CONCURRENCY": intSetter("WARM_STARTUP_CONCURRENCY", func(c *Config) *int { return &c.WarmStartupConcurrency }),
- "PER_ACCOUNT_CONCURRENCY": intSetter("PER_ACCOUNT_CONCURRENCY", func(c *Config) *int { return &c.PerAccountConcurrency }),
- "MAX_ACCOUNT_SWITCHES": setMaxAccountSwitches,
- "ACCOUNT_SWITCH_INTERVAL": textSetter(func(c *Config) *string { return &c.AccountSwitchInterval }, lowerTrim),
- "MAX_QUOTA_SWITCHES": textSetter(func(c *Config) *string { return &c.MaxQuotaSwitches }, lowerTrim),
- "INIT_TIMEOUT": durationSetter("INIT_TIMEOUT", func(c *Config) *time.Duration { return &c.InitTimeout }),
- "REQUEST_TIMEOUT": durationSetter("REQUEST_TIMEOUT", func(c *Config) *time.Duration { return &c.RequestTimeout }),
- "ADMIN_USERNAME": textSetter(func(c *Config) *string { return &c.AdminUsername }, strings.TrimSpace),
- "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),
- "PREVIEW_LISTEN_ADDR": textSetter(func(c *Config) *string { return &c.PreviewListenAddr }, strings.TrimSpace),
- "PROXY_API_KEY": textSetter(func(c *Config) *string { return &c.ProxyAPIKey }, strings.TrimSpace),
- "PROXY": textSetter(func(c *Config) *string { return &c.Proxy }, strings.TrimSpace),
- "ROUTING_STRATEGY": textSetter(func(c *Config) *string { return &c.RoutingStrategy }, strings.TrimSpace),
- "ACCOUNT_ORDER": textSetter(func(c *Config) *string { return &c.AccountOrder }, strings.TrimSpace),
- "MODEL_MAPPING": textSetter(func(c *Config) *string { return &c.ModelMapping }, strings.TrimSpace),
- "MODEL_CHANNELS": textSetter(func(c *Config) *string { return &c.ModelChannels }, strings.TrimSpace),
- "MODEL_ACCOUNTS": textSetter(func(c *Config) *string { return &c.ModelAccounts }, strings.TrimSpace),
- "API_KEY_ACCOUNTS": textSetter(func(c *Config) *string { return &c.APIKeyAccounts }, strings.TrimSpace),
- "WAA_BACKEND": textSetter(func(c *Config) *string { return &c.WAABackend }, lowerTrim),
- "MEDIA_OUTPUT": textSetter(func(c *Config) *string { return &c.MediaOutput }, lowerTrim),
- "MEDIA_BASE_URL": textSetter(func(c *Config) *string { return &c.MediaBaseURL }, strings.TrimSpace),
- "UPSTREAM_CHANNELS": func(c *Config, value string) error {
- c.UpstreamChannels = parseUpstreamChannels(value)
- return nil
- },
- "BUILD_CHAT_MODELS": boolSetter("BUILD_CHAT_MODELS", func(c *Config) *bool { return &c.BuildChatModels }),
- "HIDE_MODELS": textSetter(func(c *Config) *string { return &c.HideModels }, strings.TrimSpace),
- "GENERATE_CONTENT_ACCOUNTS": textSetter(func(c *Config) *string { return &c.GenerateContentAccounts }, strings.TrimSpace),
- "SILLYTAVERN_API_KEYS": textSetter(func(c *Config) *string { return &c.SillyTavernAPIKeys }, strings.TrimSpace),
-}
-
-func boolSetter(key string, field func(*Config) *bool) func(*Config, string) error {
- return func(c *Config, value string) error {
- parsed, err := strconv.ParseBool(strings.TrimSpace(value))
- if err != nil {
- return fmt.Errorf("%s 必须是 true 或 false", key)
- }
- *field(c) = parsed
- return nil
+// boolField 返回布尔配置键的读写方式
+func boolField(key string, field func(*Config) *bool) configField {
+ return configField{
+ key: key,
+ set: func(c *Config, value string) error {
+ parsed, err := strconv.ParseBool(strings.TrimSpace(value))
+ if err != nil {
+ return fmt.Errorf("%s 必须是 true 或 false", key)
+ }
+ *field(c) = parsed
+ return nil
+ },
+ get: func(c Config) string { return strconv.FormatBool(*field(&c)) },
}
}
-func intSetter(key string, field func(*Config) *int) func(*Config, string) error {
- return func(c *Config, value string) error {
- parsed, err := parsePositiveInt(key, value)
- if err != nil {
- return err
- }
- *field(c) = parsed
- return nil
+// intField 返回正整数配置键的读写方式
+func intField(key string, field func(*Config) *int) configField {
+ return configField{
+ key: key,
+ set: func(c *Config, value string) error {
+ parsed, err := parsePositiveInt(key, value)
+ if err != nil {
+ return err
+ }
+ *field(c) = parsed
+ return nil
+ },
+ get: func(c Config) string { return strconv.Itoa(*field(&c)) },
}
}
-func durationSetter(key string, field func(*Config) *time.Duration) func(*Config, string) error {
- return func(c *Config, value string) error {
- parsed, err := parsePositiveDuration(key, value)
- if err != nil {
- return err
- }
- *field(c) = parsed
- return nil
+// durationField 返回正时长配置键的读写方式
+func durationField(key string, field func(*Config) *time.Duration) configField {
+ return configField{
+ key: key,
+ set: func(c *Config, value string) error {
+ parsed, err := parsePositiveDuration(key, value)
+ if err != nil {
+ return err
+ }
+ *field(c) = parsed
+ return nil
+ },
+ get: func(c Config) string { return (*field(&c)).String() },
}
}
-func textSetter(field func(*Config) *string, normalize func(string) string) func(*Config, string) error {
- return func(c *Config, value string) error {
- *field(c) = normalize(value)
- return nil
+// textField 返回文本配置键的读写方式,normalize 为空时保留原文
+func textField(key string, field func(*Config) *string, normalize func(string) string) configField {
+ return configField{
+ key: key,
+ set: func(c *Config, value string) error {
+ if normalize != nil {
+ value = normalize(value)
+ }
+ *field(c) = value
+ return nil
+ },
+ get: func(c Config) string { return *field(&c) },
}
}
@@ -510,6 +512,14 @@ var configChecks = []configCheck{
return fmt.Errorf("USER_MESSAGE_REWRITE 必须是 off、traditional 或 martian")
}
}},
+ {[]string{"BUILD_CHAT_PROTOCOL"}, func(c Config) error {
+ switch c.BuildChatProtocol {
+ case BuildChatProtocolAuto, BuildChatProtocolAgency, BuildChatProtocolLegacy:
+ return nil
+ default:
+ return fmt.Errorf("BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy")
+ }
+ }},
{[]string{"MEDIA_BASE_URL"}, func(c Config) error {
if c.MediaBaseURL == "" {
return nil
@@ -535,23 +545,23 @@ func Load(path string) (Config, error) {
return Config{}, err
}
cfg := Default()
- for _, key := range configKeys {
- if value, ok := os.LookupEnv(key); ok {
- values[key] = value
- cfg.Environment = append(cfg.Environment, key)
+ for _, field := range configFields {
+ if value, ok := os.LookupEnv(field.key); ok {
+ values[field.key] = value
+ cfg.Environment = append(cfg.Environment, field.key)
}
}
- for _, key := range configKeys {
- if value, ok := values[key]; ok {
- if err := configSetters[key](&cfg, value); err != nil {
- cfg.Invalid = append(cfg.Invalid, invalidValue(key, value, err))
+ for _, field := range configFields {
+ if value, ok := values[field.key]; ok {
+ if err := field.set(&cfg, value); err != nil {
+ cfg.Invalid = append(cfg.Invalid, invalidValue(field.key, value, err))
}
}
}
defaults := defaultsFor(cfg.WAABackend).envValues()
for _, key := range workerDefaultKeys {
if _, ok := values[key]; !ok {
- configSetters[key](&cfg, defaults[key])
+ configFieldByKey[key].set(&cfg, defaults[key])
}
}
if _, ok := values["WARM_WORKER_LIMIT"]; !ok {
@@ -569,7 +579,7 @@ func Load(path string) (Config, error) {
}
failed = true
for _, key := range check.keys {
- configSetters[key](&cfg, defaults[key])
+ configFieldByKey[key].set(&cfg, defaults[key])
value, ok := values[key]
if ok && !slices.ContainsFunc(cfg.Invalid, func(item InvalidValue) bool { return item.Key == key }) {
cfg.Invalid = append(cfg.Invalid, invalidValue(key, value, err))
@@ -587,7 +597,7 @@ func Load(path string) (Config, error) {
func (c Config) KeepEnvironment(saved Config) Config {
values := saved.envValues()
for _, key := range saved.Environment {
- configSetters[key](&c, values[key])
+ configFieldByKey[key].set(&c, values[key])
}
c.Environment = saved.Environment
c.Invalid = slices.DeleteFunc(slices.Clone(saved.Invalid), func(item InvalidValue) bool { return !slices.Contains(saved.Environment, item.Key) })
@@ -596,61 +606,11 @@ func (c Config) KeepEnvironment(saved Config) Config {
// envValues 返回每个配置键在 .env 中的文本值
func (c Config) envValues() map[string]string {
- return map[string]string{
- "AUTO_START": strconv.FormatBool(c.AutoStart),
- "HIDE_DOCK_ICON": strconv.FormatBool(c.HideDockIcon),
- "REQUEST_BODY_LOG": strconv.FormatBool(c.RequestBodyLog),
- "LOG_FILE": strconv.FormatBool(c.LogFile),
- "LOG_MAX_TOTAL_MB": strconv.Itoa(c.LogMaxTotalMB),
- "ADMIN_AUTH_ENABLED": strconv.FormatBool(c.AdminAuthEnabled),
- "ADMIN_USERNAME": c.AdminUsername,
- "ADMIN_PASSWORD": c.AdminPassword,
- "BUILD_NATIVE_NONSTREAM": strconv.FormatBool(c.BuildNativeNonstream),
- "NONSTREAM_KEEPALIVE": strconv.FormatBool(c.NonstreamKeepalive),
- "FAKE_STREAM": strconv.FormatBool(c.FakeStream),
- "YOUTUBE_LINKS": strconv.FormatBool(c.YouTubeLinks),
- "STRIP_THOUGHT_SIGNATURES": strconv.FormatBool(c.StripThoughtSignatures),
- "SEARCH_MODEL_ALIASES": strconv.FormatBool(c.SearchModelAliases),
- "DISCOVER_HIDDEN_MODELS": strconv.FormatBool(c.DiscoverHiddenModels),
- "GOOGLE_SEARCH": strconv.FormatBool(c.GoogleSearch),
- "FIRST_EVENT_HEDGE": c.FirstEventHedge,
- "FIRST_EVENT_HEDGE_MODELS": c.FirstEventHedgeModels,
- "FIRST_EVENT_TIMEOUT": c.FirstEventTimeout,
- "CONTINUATION_REWRITE": strconv.FormatBool(c.ContinuationRewrite),
- "CONTINUATION_PROMPT": c.ContinuationPrompt,
- "REPLY_TOOL": strconv.FormatBool(c.ReplyTool),
- "USER_MESSAGE_REWRITE": c.UserMessageRewrite,
- "THINKING_GUARD": strconv.FormatBool(c.ThinkingGuard),
- "AISTUDIO_AUTH_STATES": c.AuthStates,
- "LISTEN_ADDR": c.ListenAddr,
- "PREVIEW_LISTEN_ADDR": c.PreviewListenAddr,
- "PROXY_API_KEY": c.ProxyAPIKey,
- "PROXY": c.Proxy,
- "INIT_TIMEOUT": c.InitTimeout.String(),
- "REQUEST_TIMEOUT": c.RequestTimeout.String(),
- "WARM_WORKER_LIMIT": strconv.Itoa(c.WarmWorkerLimit),
- "MAX_ACTIVE_WORKERS": strconv.Itoa(c.MaxActiveWorkers),
- "WARM_STARTUP_CONCURRENCY": strconv.Itoa(c.WarmStartupConcurrency),
- "PER_ACCOUNT_CONCURRENCY": strconv.Itoa(c.PerAccountConcurrency),
- "ROUTING_STRATEGY": c.RoutingStrategy,
- "ACCOUNT_ORDER": c.AccountOrder,
- "MAX_ACCOUNT_SWITCHES": strconv.Itoa(c.MaxAccountSwitches),
- "ACCOUNT_SWITCH_INTERVAL": c.AccountSwitchInterval,
- "MAX_QUOTA_SWITCHES": c.MaxQuotaSwitches,
- "UPSTREAM_CHANNELS": strings.Join(c.UpstreamChannels, ","),
- "MODEL_MAPPING": c.ModelMapping,
- "MODEL_CHANNELS": c.ModelChannels,
- "MODEL_ACCOUNTS": c.ModelAccounts,
- "API_KEY_ACCOUNTS": c.APIKeyAccounts,
- "WAA_BACKEND": c.WAABackend,
- "MEDIA_OUTPUT": c.MediaOutput,
- "MEDIA_BASE_URL": c.MediaBaseURL,
-
- "BUILD_CHAT_MODELS": strconv.FormatBool(c.BuildChatModels),
- "HIDE_MODELS": c.HideModels,
- "GENERATE_CONTENT_ACCOUNTS": c.GenerateContentAccounts,
- "SILLYTAVERN_API_KEYS": c.SillyTavernAPIKeys,
+ values := make(map[string]string, len(configFields))
+ for _, field := range configFields {
+ values[field.key] = field.get(c)
}
+ return values
}
// Save 将与默认值不同的配置原子写入指定 env 文件,进程环境变量决定的项保留文件中原有的值;文件中没有的常驻预热账户数与活动 Worker 上限仍等于原后端的默认值时不写入,随后端取默认值
@@ -665,11 +625,12 @@ func (c Config) Save(path string) error {
values, defaults := c.envValues(), defaultsFor(c.WAABackend).envValues()
previous := Default()
if value, ok := saved["WAA_BACKEND"]; ok {
- _ = configSetters["WAA_BACKEND"](&previous, value)
+ _ = configFieldByKey["WAA_BACKEND"].set(&previous, value)
}
previousDefaults := defaultsFor(previous.WAABackend).envValues()
file := make(map[string]string)
- for _, key := range configKeys {
+ for _, field := range configFields {
+ key := field.key
_, inFile := saved[key]
switch {
case slices.Contains(c.Environment, key):
@@ -684,12 +645,12 @@ func (c Config) Save(path string) error {
return writeEnv(path, file)
}
-// writeEnv 按 configKeys 的顺序原子写入 values 中的键
+// writeEnv 按 configFields 的顺序原子写入 values 中的键
func writeEnv(path string, values map[string]string) error {
var output strings.Builder
- for _, key := range configKeys {
- if value, ok := values[key]; ok {
- output.WriteString(key)
+ for _, field := range configFields {
+ if value, ok := values[field.key]; ok {
+ output.WriteString(field.key)
output.WriteByte('=')
output.WriteString(formatEnvValue(value))
output.WriteByte('\n')
@@ -855,15 +816,20 @@ func ScopedAPIKeys(value string, apiKeys string) []string {
return slices.DeleteFunc(APIKeys(value), func(key string) bool { return !slices.Contains(keys, key) })
}
-// AccountList 返回逗号分隔、去掉空白与重复的账户 ID
-func AccountList(value string) []string {
- var ids []string
- for id := range strings.SplitSeq(value, ",") {
- if id = strings.TrimSpace(id); id != "" && !slices.Contains(ids, id) {
- ids = append(ids, id)
+// commaUniqueList 返回逗号分隔、去掉空白与重复的各项
+func commaUniqueList(value string) []string {
+ var items []string
+ for item := range strings.SplitSeq(value, ",") {
+ if item = strings.TrimSpace(item); item != "" && !slices.Contains(items, item) {
+ items = append(items, item)
}
}
- return ids
+ return items
+}
+
+// AccountList 返回逗号分隔、去掉空白与重复的账户 ID
+func AccountList(value string) []string {
+ return commaUniqueList(value)
}
// ParseModelMapping 解析逗号分隔的 别名:模型 ID,别名可含冒号,以最后一个冒号分隔
@@ -935,13 +901,7 @@ func validateUpstreamChannels(channels []string) error {
// ProxyList 返回 PROXY 中以逗号分隔的代理 URL
func ProxyList(value string) []string {
- var proxies []string
- for proxy := range strings.SplitSeq(value, ",") {
- if proxy = strings.TrimSpace(proxy); proxy != "" && !slices.Contains(proxies, proxy) {
- proxies = append(proxies, proxy)
- }
- }
- return proxies
+ return commaUniqueList(value)
}
// ValidateProxy 校验账户或全局代理 URL
@@ -991,7 +951,7 @@ func readEnvFile(path string) (map[string]string, error) {
return nil, fmt.Errorf("%s:%d 缺少等号", path, lineNumber)
}
key = strings.TrimSpace(key)
- if !slices.Contains(configKeys[:], key) {
+ if _, ok := configFieldByKey[key]; !ok {
continue
}
value, err := parseEnvValue(strings.TrimSpace(raw))
diff --git a/internal/i18n/messages/de.json b/internal/i18n/messages/de.json
index 2884ad81..10d7e919 100644
--- a/internal/i18n/messages/de.json
+++ b/internal/i18n/messages/de.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0} stimmt mit mehreren sichtbaren Zielen überein",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1}, bitte in einem Browser exportieren, der bei AI Studio angemeldet ist",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0}: {1} wird bereits von einer anderen AIStudio2API-Runtime verwendet",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0}: Live-Sitzungen auf dem Build-Kanal unterstützen client_content und context_update nicht",
"%w: CountTokens model 不能为空": "{0}: CountTokens model darf nicht leer sein",
"%w: GenerateContent model 不能为空": "{0}: GenerateContent model darf nicht leer sein",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0}: Live unterstützt nur die Tools functionDeclarations und googleSearch, nicht {1}",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0}: Live-Anweisungen und -Runden unterstützen nur Text-Parts",
"%w: Waa/Create 未确认账户会话": "{0}: Waa/Create hat Kontositzung nicht bestätigt",
"%w: audio 未在 setup input_modalities 中声明": "{0}: audio ist in setup input_modalities nicht deklariert",
+ "%w: bidi client_content 不能为空": "{0}: bidi client_content darf nicht leer sein",
+ "%w: bidi context_update 不能为空": "{0}: bidi context_update darf nicht leer sein",
"%w: bidi function response 列表为空": "{0}: bidi function response-Liste ist leer",
"%w: bidi function response 缺少函数名": "{0}: bidi function response fehlt Funktionsname",
"%w: bidi function response 缺少调用 ID": "{0}: bidi function response fehlt Aufruf-ID",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0}: bidi model darf nicht leer sein",
"%w: bidi text 不能为空": "{0}: bidi text darf nicht leer sein",
"%w: embedding model 不能为空": "{0}: embedding model darf nicht leer sein",
+ "%w: functionDeclarations 无效: %v": "{0}: ungültige functionDeclarations: {1}",
"%w: image 未在 setup input_modalities 中声明": "{0}: image ist in setup input_modalities nicht deklariert",
"%w: inline data 缺少 MIME 或数据": "{0}: inline data fehlt MIME-Typ oder Daten",
"%w: live input modality %q 不可用": "{0}: Live input modality {1} ist nicht verfügbar",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0}: Modality-Liste darf nicht leer sein",
"%w: music_config 必须是 JSON 对象": "{0}: music_config muss ein JSON-Objekt sein",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0}: playback_control muss play, pause, stop oder reset_context sein",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0}: Die Medien von realtimeInput müssen audio/pcm oder ein JPEG-, PNG- oder WebP-Bild sein",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0}: Die Medien von realtimeInput erfordern mimeType und base64-data",
"%w: robotics input_modalities 必须是 [text]": "{0}: robotics input_modalities muss [text] sein",
"%w: robotics output_modalities 必须是 [text]": "{0}: robotics output_modalities muss [text] sein",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: robotics unterstützt system_instruction, voice, media_resolution, thinking_level, context_window_compression und google_search nicht",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: robotics unterstützt system_instruction, voice, media_resolution, thinking_level, context_window_compression, google_search, proactive_audio, proactive_video, enable_affective_dialog und turn_coverage nicht",
"%w: robotics 不支持 translation 或 transcription": "{0}: robotics unterstützt translation oder transcription nicht",
+ "%w: setup 只能是首帧": "{0}: setup muss die erste Nachricht sein",
"%w: storage state 缺少有效 Cookie: %s": "{0}: storage state fehlen gültige Cookies: {1}",
"%w: text 未在 setup input_modalities 中声明": "{0}: text ist in setup input_modalities nicht deklariert",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0}: thinking_level muss minimal, low, medium oder high sein",
"%w: tool_response 的 setup 未声明 tools": "{0}: setup von tool_response hat tools nicht deklariert",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0}: turn_coverage muss only_activity, all_input oder audio_activity_and_all_video sein",
"%w: weighted_prompts 不能为空": "{0}: weighted_prompts darf nicht leer sein",
"%w: weighted_prompts[%d].text 不能为空": "{0}: weighted_prompts[{1}].text darf nicht leer sein",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0}: Live-Musiksitzung akzeptiert nur music_prompts, music_config und playback",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: Live-Musikmodell {1} unterstützt system_instruction, voice, media_resolution, thinking_level, context_window_compression und google_search nicht",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0}: Live-Musikmodell {1} unterstützt tools, translation oder transcription nicht",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0}: output_modalities des Live-Musikmodells {1} muss [audio] sein",
+ "%w: 客户端消息无效: %v": "{0}: ungültige Client-Nachricht: {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0}: Eine Client-Nachricht muss setup, clientContent, realtimeInput, toolResponse oder contextUpdate enthalten",
"%w: 导航 AI Studio: %v": "{0}: Navigation zu AI Studio: {1}",
"%w: 文件 ID 为空": "{0}: Datei-ID ist leer",
"%w: 文件引用缺少 ID": "{0}: Dateireferenz fehlt ID",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0}: Neueste Chatrunde überschreitet Modell-Kontextfenster {1}",
+ "%w: AI Studio 的 Live 不提供 %s": "{0}: AI Studio Live bietet {1} nicht an",
"%w: 未识别的 bidi media type %q": "{0}: Unerkannter bidi media type {1}",
"%w: 未识别的 bidi mode %q": "{0}: Unerkannter bidi mode {1}",
"%w: 模型 %s 不支持 %s": "{0}: Modell {1} unterstützt {2} nicht",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: Modell {1} unterstützt media_resolution, thinking_level, context_window_compression, proactive_audio, proactive_video, enable_affective_dialog und turn_coverage nicht",
"%w: 模型 %s 不支持 system_instruction": "{0}: Modell {1} unterstützt system_instruction nicht",
"%w: 模型 %s 不支持 tools": "{0}: Modell {1} unterstützt tools nicht",
"%w: 模型 %s 不支持 transcription": "{0}: Modell {1} unterstützt transcription nicht",
"%w: 模型 %s 不支持 translation": "{0}: Modell {1} unterstützt translation nicht",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: Modell {1} unterstützt voice, media_resolution, thinking_level und context_window_compression nicht",
+ "%w: 模型 %s 不支持 voice": "{0}: Modell {1} unterstützt voice nicht",
"%w: 模型 %s 不是实时音乐模型": "{0}: Modell {1} ist kein Live-Musikmodell",
"%w: 模型 %s 不输出视频": "{0}: Modell {1} gibt kein Video aus",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: output_modalities für Modell {1} muss [audio] sein",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: Ressource {1} kann nicht als Dateireferenz verwendet werden",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0}: Die Seite läuft bereits, Proof-Funktion der Website aufgerufen={1}",
"%w: 首帧 type 必须是 setup": "{0}: type des ersten Frames muss setup sein",
+ "%w: 首帧必须是 setup 消息": "{0}: Die erste Nachricht muss setup sein",
"%v,官网跳转 %s": "{0}, Weiterleitung der offiziellen Website: {1}",
"%w:在管理页面账户页添加账户": "{0}: Fügen Sie auf der Kontenseite der Konsole ein Konto hinzu",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0}; legen Sie in .env einen PROXY fest, der GitHub erreicht, und versuchen Sie es erneut, oder laden Sie {1} manuell herunter und entpacken Sie es nach {2}",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Das in Chrome aktualisierte Konto stimmt nicht mit dem Ursprungskonto überein",
"Chrome 账号重复: %s": "Doppeltes Chrome-Konto: {0}",
"Chrome 账户已导入": "Chrome-Konto importiert",
- "CodeAssistantOffline contents 不能为空": "contents für CodeAssistantOffline darf nicht leer sein",
"Cookie JSON 无效: %w": "Ungültiges Cookie-JSON: {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "Das in den Cookies unter u/{0} angemeldete Konto ist {1} und weicht von --email {2} ab",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Cookie-Import: aistudio2api setup --cookie , --cookie-file oder --cdp ",
@@ -847,6 +861,7 @@
"检测代理池": "Proxy-Pool wird geprüft",
"模型 %s 不接受 agent_config": "Modell {0} akzeptiert agent_config nicht",
"模型 %s 不支持 %s": "Modell {0} unterstützt {1} nicht",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0} wurde für die API-Version v1beta nicht gefunden oder wird für {1} nicht unterstützt. Rufen Sie ListModels auf, um die verfügbaren Modelle und ihre unterstützten Methoden anzuzeigen.",
"模型 %s 没有 %s 任务": "Modell {0} hat keine {1}-Aufgabe",
"模型 %s 没有尾帧输入": "Modell {0} hat keine Endframe-Eingabe",
"模型 %s 没有返回视频:%s": "Modell {0} hat kein Video zurückgegeben: {1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "Öffentlichen NCrypt-ECDSA-Schlüssel codieren: {0}",
"编码 NCrypt Provider 名称: %w": "NCrypt-Provider-Name codieren: {0}",
"编码 NCrypt 公钥类型: %w": "Öffentlichen NCrypt-Schlüsseltyp codieren: {0}",
+ "编码 bidi client_content: %w": "bidi client_content codieren: {0}",
+ "编码 bidi context_update: %w": "bidi context_update codieren: {0}",
"编码 bidi function declaration: %w": "bidi function declaration codieren: {0}",
"编码 bidi function response: %w": "bidi function response codieren: {0}",
"编码 bidi provider event: %w": "bidi provider event codieren: {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "Experiment-Token TSDtV der AI Studio-Seite: {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "In TSDtV der AI Studio-Seite fehlt das Experiment-Token",
"AI Studio 页面 UUFaWc %w": "AI Studio-Seite UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "Report-only-CSP der AI Studio-Seite: {0}",
"AI Studio 页面缺少 WIZ 数据": "Auf der AI Studio-Seite fehlen WIZ-Daten",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "Auf der AI Studio-Seite fehlt goX6ee oder S6lZl",
"JSPB 数组无效: %.20q": "Ungültiges JSPB-Array: {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Modell {0} erfordert eine dieser Berechtigungen, die für diese Anfrage verfügbaren Konten ({1}) verfügen nicht darüber: {2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction-Modell contents[{0}] akzeptiert keinen serverseitigen Tool-Schritt {1}",
"模型 %s 已在设置中隐藏": "Modell {0} ist in den Einstellungen ausgeblendet",
- "Build 对话模型 %s 已在设置中关闭": "Build-Chatmodell {0} ist in den Einstellungen ausgeschaltet"
+ "Build 对话模型 %s 已在设置中关闭": "Build-Chatmodell {0} ist in den Einstellungen ausgeschaltet",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL muss auto, agency oder legacy sein",
+ "Build 写代码助手协议已选定": "Build-Chatprotokoll ausgewählt",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "In den Startdaten der Seite fehlt das Build-Chatprotokoll-Flag 45831005; das alte Protokoll wird verwendet. Falls die offizielle Website vollständig auf das neue Protokoll umgestellt hat, setzen Sie BUILD_CHAT_PROTOCOL in den Einstellungen auf agency",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "In den Startdaten der Seite fehlt das Build-Chatprotokoll-Flag 45831005, daher wird das alte Protokoll verwendet",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "Falls die offizielle Website vollständig auf das neue Protokoll umgestellt hat, setzen Sie BUILD_CHAT_PROTOCOL in den Einstellungen auf agency",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "Position des Skriptlade-Aufrufs fehlt im AI Studio-Frontend-Bundle; CSP-Bericht wird übersprungen",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "Aufruf zum Laden von Skripten fehlt im AI Studio-Frontend-Bundle; Zeilen- und Spaltenbestimmung für CSP wird übersprungen",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "Der geschützte AI Studio-Transport unterstützt keine Anfragen des Build-Code-Assistenten",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "Report-only-CSP der AI Studio-Seite konnte nicht geparst werden; CSP-Bericht wird übersprungen",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "Einstiegskarten-Modul fehlt auf der AI Studio-Seite; Vorabladen wird übersprungen",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "Telemetriedaten der AI Studio-Seite konnten nicht geparst werden; Start wird ohne sie fortgesetzt",
+ "StreamRunAgentTask contents 不能为空": "Der Inhalt der Anfrage an den Build-Code-Assistenten darf nicht leer sein",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Für die erneute Verbindung des Build-Code-Assistenten fehlt die Sitzungsverlaufs-ID",
+ "后台刷新绑定会话失败": "Hintergrundaktualisierung der gebundenen Sitzung fehlgeschlagen",
+ "点击 AI Studio 启动覆盖层: %w": "Klick auf das AI Studio-Start-Overlay: {0}",
+ "缺少步骤序号": "Schrittnummer fehlt",
+ "解析 AI Studio 启动覆盖层: %w": "AI Studio-Start-Overlay parsen: {0}"
}
diff --git a/internal/i18n/messages/en.json b/internal/i18n/messages/en.json
index 336c2056..27a96bd0 100644
--- a/internal/i18n/messages/en.json
+++ b/internal/i18n/messages/en.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0} matches multiple visible targets",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1}, please export from a browser signed in to AI Studio",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0}: {1} is already in use by another AIStudio2API runtime",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0}: Live sessions on the Build channel do not support client_content or context_update",
"%w: CountTokens model 不能为空": "{0}: CountTokens model cannot be empty",
"%w: GenerateContent model 不能为空": "{0}: GenerateContent model cannot be empty",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0}: Live supports only the functionDeclarations and googleSearch tools, not {1}",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0}: Live instructions and turns support only text parts",
"%w: Waa/Create 未确认账户会话": "{0}: Waa/Create did not confirm account session",
"%w: audio 未在 setup input_modalities 中声明": "{0}: audio is not declared in setup input_modalities",
+ "%w: bidi client_content 不能为空": "{0}: bidi client_content cannot be empty",
+ "%w: bidi context_update 不能为空": "{0}: bidi context_update cannot be empty",
"%w: bidi function response 列表为空": "{0}: bidi function response list is empty",
"%w: bidi function response 缺少函数名": "{0}: bidi function response is missing function name",
"%w: bidi function response 缺少调用 ID": "{0}: bidi function response is missing call ID",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0}: bidi model cannot be empty",
"%w: bidi text 不能为空": "{0}: bidi text cannot be empty",
"%w: embedding model 不能为空": "{0}: embedding model cannot be empty",
+ "%w: functionDeclarations 无效: %v": "{0}: invalid functionDeclarations: {1}",
"%w: image 未在 setup input_modalities 中声明": "{0}: image is not declared in setup input_modalities",
"%w: inline data 缺少 MIME 或数据": "{0}: inline data is missing MIME or data",
"%w: live input modality %q 不可用": "{0}: live input modality {1} is unavailable",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0}: modality list cannot be empty",
"%w: music_config 必须是 JSON 对象": "{0}: music_config must be a JSON object",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0}: playback_control must be play, pause, stop, or reset_context",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0}: realtimeInput media must be audio/pcm or a JPEG, PNG or WebP image",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0}: realtimeInput media requires mimeType and base64 data",
"%w: robotics input_modalities 必须是 [text]": "{0}: robotics input_modalities must be [text]",
"%w: robotics output_modalities 必须是 [text]": "{0}: robotics output_modalities must be [text]",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: robotics does not support system_instruction, voice, media_resolution, thinking_level, context_window_compression, or google_search",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: robotics does not support system_instruction, voice, media_resolution, thinking_level, context_window_compression, google_search, proactive_audio, proactive_video, enable_affective_dialog, or turn_coverage",
"%w: robotics 不支持 translation 或 transcription": "{0}: robotics does not support translation or transcription",
+ "%w: setup 只能是首帧": "{0}: setup must be the first message",
"%w: storage state 缺少有效 Cookie: %s": "{0}: storage state is missing valid Cookies: {1}",
"%w: text 未在 setup input_modalities 中声明": "{0}: text is not declared in setup input_modalities",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0}: thinking_level must be minimal, low, medium, or high",
"%w: tool_response 的 setup 未声明 tools": "{0}: setup for tool_response did not declare tools",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0}: turn_coverage must be only_activity, all_input, or audio_activity_and_all_video",
"%w: weighted_prompts 不能为空": "{0}: weighted_prompts cannot be empty",
"%w: weighted_prompts[%d].text 不能为空": "{0}: weighted_prompts[{1}].text cannot be empty",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0}: live music session only accepts music_prompts, music_config, and playback",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: live music model {1} does not support system_instruction, voice, media_resolution, thinking_level, context_window_compression, or google_search",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0}: live music model {1} does not support tools, translation, or transcription",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0}: output_modalities for live music model {1} must be [audio]",
+ "%w: 客户端消息无效: %v": "{0}: invalid client message: {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0}: a client message must contain setup, clientContent, realtimeInput, toolResponse, or contextUpdate",
"%w: 导航 AI Studio: %v": "{0}: navigating AI Studio: {1}",
"%w: 文件 ID 为空": "{0}: file ID is empty",
"%w: 文件引用缺少 ID": "{0}: file reference is missing ID",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0}: latest chat turn exceeds model context window {1}",
+ "%w: AI Studio 的 Live 不提供 %s": "{0}: AI Studio Live does not provide {1}",
"%w: 未识别的 bidi media type %q": "{0}: unrecognized bidi media type {1}",
"%w: 未识别的 bidi mode %q": "{0}: unrecognized bidi mode {1}",
"%w: 模型 %s 不支持 %s": "{0}: Model {1} does not support {2}",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: Model {1} does not support media_resolution, thinking_level, context_window_compression, proactive_audio, proactive_video, enable_affective_dialog, or turn_coverage",
"%w: 模型 %s 不支持 system_instruction": "{0}: Model {1} does not support system_instruction",
"%w: 模型 %s 不支持 tools": "{0}: Model {1} does not support tools",
"%w: 模型 %s 不支持 transcription": "{0}: Model {1} does not support transcription",
"%w: 模型 %s 不支持 translation": "{0}: Model {1} does not support translation",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: Model {1} does not support voice, media_resolution, thinking_level, and context_window_compression",
+ "%w: 模型 %s 不支持 voice": "{0}: Model {1} does not support voice",
"%w: 模型 %s 不是实时音乐模型": "{0}: Model {1} is not a real-time music model",
"%w: 模型 %s 不输出视频": "{0}: Model {1} does not output video",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: output_modalities for model {1} must be [audio]",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: Resource {1} cannot be used as a file reference",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0}: the page started running, official proof function called={1}",
"%w: 首帧 type 必须是 setup": "{0}: Initial frame type must be setup",
+ "%w: 首帧必须是 setup 消息": "{0}: the first message must be setup",
"%v,官网跳转 %s": "{0}, official site redirects to {1}",
"%w:在管理页面账户页添加账户": "{0}: add an account on the Accounts page of the console",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0}; set a PROXY that can reach GitHub in .env and retry, or download {1} manually and extract it to {2}",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Updated Chrome account does not match original account",
"Chrome 账号重复: %s": "Duplicate Chrome account: {0}",
"Chrome 账户已导入": "Chrome account imported",
- "CodeAssistantOffline contents 不能为空": "CodeAssistantOffline contents cannot be empty",
"Cookie JSON 无效: %w": "Invalid Cookies JSON: {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "The account signed in at u/{0} in the cookies is {1}, which differs from --email {2}",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Cookies import: aistudio2api setup --cookie , --cookie-file , or --cdp ",
@@ -847,6 +861,7 @@
"检测代理池": "Checking the proxy pool",
"模型 %s 不接受 agent_config": "Model {0} does not accept agent_config",
"模型 %s 不支持 %s": "Model {0} does not support {1}",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0} is not found for API version v1beta, or is not supported for {1}. Call ListModels to see the list of available models and their supported methods.",
"模型 %s 没有 %s 任务": "Model {0} has no {1} task",
"模型 %s 没有尾帧输入": "Model {0} has no end frame input",
"模型 %s 没有返回视频:%s": "Model {0} returned no video: {1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "Encode NCrypt ECDSA public key: {0}",
"编码 NCrypt Provider 名称: %w": "Encode NCrypt provider name: {0}",
"编码 NCrypt 公钥类型: %w": "Encode NCrypt public key type: {0}",
+ "编码 bidi client_content: %w": "Encode bidi client_content: {0}",
+ "编码 bidi context_update: %w": "Encode bidi context_update: {0}",
"编码 bidi function declaration: %w": "Encode bidi function declaration: {0}",
"编码 bidi function response: %w": "Encode bidi function response: {0}",
"编码 bidi provider event: %w": "Encode bidi provider event: {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "AI Studio page TSDtV experiment token: {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "AI Studio page TSDtV is missing the experiment token",
"AI Studio 页面 UUFaWc %w": "AI Studio page UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "AI Studio page report-only CSP: {0}",
"AI Studio 页面缺少 WIZ 数据": "AI Studio page is missing WIZ data",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "AI Studio page is missing goX6ee or S6lZl",
"JSPB 数组无效: %.20q": "Invalid JSPB array: {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Model {0} requires one of these entitlements, which the accounts available to this request ({1}) do not have: {2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction model contents[{0}] does not accept server-side tool step {1}",
"模型 %s 已在设置中隐藏": "Model {0} is hidden in settings",
- "Build 对话模型 %s 已在设置中关闭": "Build chat model {0} is turned off in settings"
+ "Build 对话模型 %s 已在设置中关闭": "Build chat model {0} is turned off in settings",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL must be auto, agency, or legacy",
+ "Build 写代码助手协议已选定": "Build chat protocol selected",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "Page bootstrap data is missing Build chat protocol flag 45831005; using the legacy protocol. If the official site has fully switched to the new protocol, set BUILD_CHAT_PROTOCOL to agency in settings",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "Page bootstrap data is missing Build chat protocol flag 45831005, so the legacy protocol is used",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "If the official site has fully switched to the new protocol, set BUILD_CHAT_PROTOCOL to agency in settings",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "AI Studio frontend bundle is missing the script loader position; skipping CSP report",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "AI Studio frontend bundle is missing the script loader call; skipping CSP line and column lookup",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "AI Studio protected transport does not support Build coding assistant requests",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "Failed to parse AI Studio page report-only CSP; skipping CSP report",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "AI Studio page is missing the getting-started card module; skipping preload",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "Failed to parse AI Studio page telemetry; continuing startup without it",
+ "StreamRunAgentTask contents 不能为空": "Build coding assistant request contents cannot be empty",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Build coding assistant reconnection is missing session history ID",
+ "后台刷新绑定会话失败": "Background refresh of bound session failed",
+ "点击 AI Studio 启动覆盖层: %w": "Click AI Studio startup overlay: {0}",
+ "缺少步骤序号": "Missing step sequence number",
+ "解析 AI Studio 启动覆盖层: %w": "Parse AI Studio startup overlay: {0}"
}
diff --git a/internal/i18n/messages/fr.json b/internal/i18n/messages/fr.json
index df25d06e..f8f707ac 100644
--- a/internal/i18n/messages/fr.json
+++ b/internal/i18n/messages/fr.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0} correspond à plusieurs cibles visibles",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1}, veuillez exporter depuis un navigateur connecté à AI Studio",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0} : {1} est déjà utilisé par un autre runtime AIStudio2API",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0} : les sessions Live sur le canal Build ne prennent pas en charge client_content ni context_update",
"%w: CountTokens model 不能为空": "{0} : le modèle CountTokens ne peut pas être vide",
"%w: GenerateContent model 不能为空": "{0} : le modèle GenerateContent ne peut pas être vide",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0} : Live ne prend en charge que les outils functionDeclarations et googleSearch, pas {1}",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0} : les instructions et les tours Live ne prennent en charge que les parts de texte",
"%w: Waa/Create 未确认账户会话": "{0} : session de compte non confirmée par Waa/Create",
"%w: audio 未在 setup input_modalities 中声明": "{0} : audio n’est pas déclaré dans les input_modalities du setup",
+ "%w: bidi client_content 不能为空": "{0} : bidi client_content ne peut pas être vide",
+ "%w: bidi context_update 不能为空": "{0} : bidi context_update ne peut pas être vide",
"%w: bidi function response 列表为空": "{0} : la liste des bidi function response est vide",
"%w: bidi function response 缺少函数名": "{0} : le nom de fonction est manquant dans la bidi function response",
"%w: bidi function response 缺少调用 ID": "{0} : l’ID d’appel est manquant dans la bidi function response",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0} : le modèle bidi ne peut pas être vide",
"%w: bidi text 不能为空": "{0} : le texte bidi ne peut pas être vide",
"%w: embedding model 不能为空": "{0} : le modèle embedding ne peut pas être vide",
+ "%w: functionDeclarations 无效: %v": "{0} : functionDeclarations non valides : {1}",
"%w: image 未在 setup input_modalities 中声明": "{0} : image n’est pas déclaré dans les input_modalities du setup",
"%w: inline data 缺少 MIME 或数据": "{0} : type MIME ou données manquants pour inline data",
"%w: live input modality %q 不可用": "{0} : la modalité d’entrée live {1} n’est pas disponible",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0} : la liste des modalités ne peut pas être vide",
"%w: music_config 必须是 JSON 对象": "{0} : music_config doit être un objet JSON",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0} : playback_control doit être play, pause, stop ou reset_context",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0} : les médias de realtimeInput doivent être de l’audio/pcm ou une image JPEG, PNG ou WebP",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0} : les médias de realtimeInput nécessitent mimeType et des data en base64",
"%w: robotics input_modalities 必须是 [text]": "{0} : robotics input_modalities doit être [text]",
"%w: robotics output_modalities 必须是 [text]": "{0} : robotics output_modalities doit être [text]",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0} : robotics ne prend pas en charge system_instruction, voice, media_resolution, thinking_level, context_window_compression et google_search",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0} : robotics ne prend pas en charge system_instruction, voice, media_resolution, thinking_level, context_window_compression, google_search, proactive_audio, proactive_video, enable_affective_dialog ni turn_coverage",
"%w: robotics 不支持 translation 或 transcription": "{0} : robotics ne prend pas en charge translation ou transcription",
+ "%w: setup 只能是首帧": "{0} : setup doit être le premier message",
"%w: storage state 缺少有效 Cookie: %s": "{0} : l’état de stockage ne contient aucun Cookie valide : {1}",
"%w: text 未在 setup input_modalities 中声明": "{0} : text n’est pas déclaré dans les input_modalities du setup",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0} : thinking_level doit être minimal, low, medium ou high",
"%w: tool_response 的 setup 未声明 tools": "{0} : le setup de tool_response n’a déclaré aucun tools",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0} : turn_coverage doit être only_activity, all_input ou audio_activity_and_all_video",
"%w: weighted_prompts 不能为空": "{0} : weighted_prompts ne peut pas être vide",
"%w: weighted_prompts[%d].text 不能为空": "{0} : weighted_prompts[{1}].text ne peut pas être vide",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0} : la session musique en temps réel n’accepte que music_prompts, music_config et playback",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0} : le modèle de musique en temps réel {1} ne prend pas en charge system_instruction, voice, media_resolution, thinking_level, context_window_compression et google_search",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0} : le modèle de musique en temps réel {1} ne prend pas en charge tools, translation ou transcription",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0} : output_modalities du modèle de musique en temps réel {1} doit être [audio]",
+ "%w: 客户端消息无效: %v": "{0} : message client non valide : {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0} : un message client doit contenir setup, clientContent, realtimeInput, toolResponse ou contextUpdate",
"%w: 导航 AI Studio: %v": "{0} : navigation AI Studio : {1}",
"%w: 文件 ID 为空": "{0} : l’ID de fichier est vide",
"%w: 文件引用缺少 ID": "{0} : ID manquant dans la référence de fichier",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0} : le dernier tour de discussion dépasse la fenêtre de contexte du modèle {1}",
+ "%w: AI Studio 的 Live 不提供 %s": "{0} : AI Studio Live ne propose pas {1}",
"%w: 未识别的 bidi media type %q": "{0} : type bidi media inconnu {1}",
"%w: 未识别的 bidi mode %q": "{0} : mode bidi inconnu {1}",
"%w: 模型 %s 不支持 %s": "{0}: le modèle {1} ne prend pas en charge {2}",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0} : le modèle {1} ne prend pas en charge media_resolution, thinking_level, context_window_compression, proactive_audio, proactive_video, enable_affective_dialog ni turn_coverage",
"%w: 模型 %s 不支持 system_instruction": "{0}: le modèle {1} ne prend pas en charge system_instruction",
"%w: 模型 %s 不支持 tools": "{0}: le modèle {1} ne prend pas en charge tools",
"%w: 模型 %s 不支持 transcription": "{0}: le modèle {1} ne prend pas en charge transcription",
"%w: 模型 %s 不支持 translation": "{0}: le modèle {1} ne prend pas en charge translation",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: le modèle {1} ne prend pas en charge voice, media_resolution, thinking_level et context_window_compression",
+ "%w: 模型 %s 不支持 voice": "{0} : le modèle {1} ne prend pas en charge voice",
"%w: 模型 %s 不是实时音乐模型": "{0}: le modèle {1} n'est pas un modèle de musique en temps réel",
"%w: 模型 %s 不输出视频": "{0}: le modèle {1} ne génère pas de vidéo",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: output_modalities du modèle {1} doit être [audio]",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: la ressource {1} ne peut pas être utilisée comme référence de fichier",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0} : la page a démarré l’exécution, fonction de proof du site officiel appelée={1}",
"%w: 首帧 type 必须是 setup": "{0}: le champ type de la première trame doit être setup",
+ "%w: 首帧必须是 setup 消息": "{0} : le premier message doit être setup",
"%v,官网跳转 %s": "{0}, redirection du site officiel vers {1}",
"%w:在管理页面账户页添加账户": "{0} : ajoutez un compte dans la page Comptes de l’administration",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0} ; définissez dans .env un PROXY qui accède à GitHub puis réessayez, ou téléchargez {1} manuellement et extrayez-le dans {2}",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Le compte mis à jour dans Chrome ne correspond pas au compte d’origine",
"Chrome 账号重复: %s": "Compte Chrome en double : {0}",
"Chrome 账户已导入": "Compte Chrome importé",
- "CodeAssistantOffline contents 不能为空": "contents de CodeAssistantOffline ne peut pas être vide",
"Cookie JSON 无效: %w": "JSON des cookies non valide : {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "Le compte connecté en u/{0} dans les cookies est {1}, différent de --email {2}",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Importation de cookies : aistudio2api setup --cookie , --cookie-file ou --cdp ",
@@ -847,6 +861,7 @@
"检测代理池": "Vérification du pool de proxys",
"模型 %s 不接受 agent_config": "Le modèle {0} n'accepte pas agent_config",
"模型 %s 不支持 %s": "Le modèle {0} ne prend pas en charge {1}",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0} est introuvable pour la version d’API v1beta ou n’est pas pris en charge pour {1}. Appelez ListModels pour afficher la liste des modèles disponibles et des méthodes qu’ils prennent en charge.",
"模型 %s 没有 %s 任务": "Le modèle {0} n’a pas de tâche {1}",
"模型 %s 没有尾帧输入": "Le modèle {0} n’a pas d’entrée d’image finale",
"模型 %s 没有返回视频:%s": "Le modèle {0} n’a retourné aucune vidéo: {1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "Encodage de la clé publique ECDSA NCrypt : {0}",
"编码 NCrypt Provider 名称: %w": "Encodage du nom du provider NCrypt : {0}",
"编码 NCrypt 公钥类型: %w": "Encodage du type de clé publique NCrypt : {0}",
+ "编码 bidi client_content: %w": "Encodage de bidi client_content : {0}",
+ "编码 bidi context_update: %w": "Encodage de bidi context_update : {0}",
"编码 bidi function declaration: %w": "Encodage de la déclaration de fonction bidi : {0}",
"编码 bidi function response: %w": "Encodage de la réponse de fonction bidi : {0}",
"编码 bidi provider event: %w": "Encodage de l’événement de provider bidi : {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "Jeton d’expérience TSDtV de la page AI Studio : {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "Le jeton d’expérience manque dans TSDtV de la page AI Studio",
"AI Studio 页面 UUFaWc %w": "Page AI Studio UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "CSP report-only de la page AI Studio : {0}",
"AI Studio 页面缺少 WIZ 数据": "Données WIZ manquantes sur la page AI Studio",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "goX6ee ou S6lZl manquant sur la page AI Studio",
"JSPB 数组无效: %.20q": "Tableau JSPB non valide : {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "Le modèle {0} nécessite l'un de ces droits, que ne possèdent pas les comptes disponibles pour cette requête ({1}) : {2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Le modèle Interaction contents[{0}] n'accepte pas l'étape d'outil côté serveur {1}",
"模型 %s 已在设置中隐藏": "Le modèle {0} est masqué dans les paramètres",
- "Build 对话模型 %s 已在设置中关闭": "Le modèle de chat Build {0} est désactivé dans les paramètres"
+ "Build 对话模型 %s 已在设置中关闭": "Le modèle de chat Build {0} est désactivé dans les paramètres",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL doit être auto, agency ou legacy",
+ "Build 写代码助手协议已选定": "Protocole de chat Build sélectionné",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "Les données de démarrage de la page ne contiennent pas l’indicateur de protocole de chat Build 45831005 ; l’ancien protocole est utilisé. Si le site officiel est entièrement passé au nouveau protocole, définissez BUILD_CHAT_PROTOCOL sur agency dans les paramètres",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "Les données de démarrage de la page ne contiennent pas l’indicateur de protocole de chat Build 45831005, l’ancien protocole est donc utilisé",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "Si le site officiel est entièrement passé au nouveau protocole, définissez BUILD_CHAT_PROTOCOL sur agency dans les paramètres",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "Position de l’appel de chargement de script manquante dans le bundle frontal d’AI Studio ; rapport CSP ignoré",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "Appel de chargement de script manquant dans le bundle frontal d’AI Studio ; localisation de ligne et colonne CSP ignorée",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "Le transport protégé d’AI Studio ne prend pas en charge les requêtes de l’assistant de code Build",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "Échec de l’analyse de la CSP report-only de la page AI Studio ; rapport CSP ignoré",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "Module de cartes de démarrage manquant sur la page AI Studio ; préchargement ignoré",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "Échec de l’analyse des données de télémétrie de la page AI Studio ; poursuite du démarrage en mode dégradé",
+ "StreamRunAgentTask contents 不能为空": "Le contenu de la requête de l’assistant de code Build ne peut pas être vide",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Identifiant d’historique de session manquant pour la reconnexion de l’assistant de code Build",
+ "后台刷新绑定会话失败": "Échec de l’actualisation en arrière-plan de la session liée",
+ "点击 AI Studio 启动覆盖层: %w": "Clic sur la superposition de démarrage d’AI Studio : {0}",
+ "缺少步骤序号": "Numéro d’étape manquant",
+ "解析 AI Studio 启动覆盖层: %w": "Analyse de la superposition de démarrage d’AI Studio : {0}"
}
diff --git a/internal/i18n/messages/ja.json b/internal/i18n/messages/ja.json
index 87fb69a7..2b743875 100644
--- a/internal/i18n/messages/ja.json
+++ b/internal/i18n/messages/ja.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0} が複数の可視ターゲットに一致しました",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1}。AI Studio にログイン済みのブラウザでエクスポートしてください",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0}: {1} は別の AIStudio2API runtime で既に使用されています",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0}: Build チャネルの Live セッションは client_content と context_update に対応していません",
"%w: CountTokens model 不能为空": "{0}: CountTokens の model は空にできません",
"%w: GenerateContent model 不能为空": "{0}: GenerateContent の model は空にできません",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0}: Live が対応するツールは functionDeclarations と googleSearch のみで、{1} には対応していません",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0}: Live の指示とターンはテキストの part のみに対応しています",
"%w: Waa/Create 未确认账户会话": "{0}: Waa/Create アカウントセッションが未確認です",
"%w: audio 未在 setup input_modalities 中声明": "{0}: audio が setup の input_modalities で宣言されていません",
+ "%w: bidi client_content 不能为空": "{0}: bidi client_content は空にできません",
+ "%w: bidi context_update 不能为空": "{0}: bidi context_update は空にできません",
"%w: bidi function response 列表为空": "{0}: bidi function response リストが空です",
"%w: bidi function response 缺少函数名": "{0}: bidi function response に関数名がありません",
"%w: bidi function response 缺少调用 ID": "{0}: bidi function response に呼び出し ID がありません",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0}: bidi model は空にできません",
"%w: bidi text 不能为空": "{0}: bidi text は空にできません",
"%w: embedding model 不能为空": "{0}: embedding model は空にできません",
+ "%w: functionDeclarations 无效: %v": "{0}: functionDeclarations が無効です: {1}",
"%w: image 未在 setup input_modalities 中声明": "{0}: image が setup の input_modalities で宣言されていません",
"%w: inline data 缺少 MIME 或数据": "{0}: inline data に MIME またはデータがありません",
"%w: live input modality %q 不可用": "{0}: live input modality {1} は利用不可です",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0}: modality リストは空にできません",
"%w: music_config 必须是 JSON 对象": "{0}: music_config は JSON オブジェクトである必要があります",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0}: playback_control は play、pause、stop、または reset_context である必要があります",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0}: realtimeInput のメディアは audio/pcm または JPEG、PNG、WebP の画像である必要があります",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0}: realtimeInput のメディアには mimeType と base64 の data が必要です",
"%w: robotics input_modalities 必须是 [text]": "{0}: robotics input_modalities は [text] である必要があります",
"%w: robotics output_modalities 必须是 [text]": "{0}: robotics output_modalities は [text] である必要があります",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: robotics は system_instruction、voice、media_resolution、thinking_level、context_window_compression、および google_search をサポートしていません",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: robotics は system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog、turn_coverage に対応していません",
"%w: robotics 不支持 translation 或 transcription": "{0}: robotics は translation または transcription をサポートしていません",
+ "%w: setup 只能是首帧": "{0}: setup は最初のメッセージである必要があります",
"%w: storage state 缺少有效 Cookie: %s": "{0}: storage state に有効な Cookie がありません: {1}",
"%w: text 未在 setup input_modalities 中声明": "{0}: text が setup の input_modalities で宣言されていません",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0}: thinking_level は minimal、low、medium、または high である必要があります",
"%w: tool_response 的 setup 未声明 tools": "{0}: tool_response の setup で tools が宣言されていません",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0}: turn_coverage は only_activity、all_input、audio_activity_and_all_video のいずれかである必要があります",
"%w: weighted_prompts 不能为空": "{0}: weighted_prompts は空にできません",
"%w: weighted_prompts[%d].text 不能为空": "{0}: weighted_prompts[{1}].text は空にできません",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0}: リアルタイム音楽セッションは music_prompts、music_config、および playback のみを受け付けます",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: リアルタイム音楽モデル {1} は system_instruction、voice、media_resolution、thinking_level、context_window_compression、および google_search をサポートしていません",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0}: リアルタイム音楽モデル {1} は tools、translation、または transcription をサポートしていません",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0}: リアルタイム音楽モデル {1} の output_modalities は [audio] である必要があります",
+ "%w: 客户端消息无效: %v": "{0}: クライアントメッセージが無効です: {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0}: クライアントメッセージには setup、clientContent、realtimeInput、toolResponse、contextUpdate のいずれかを含める必要があります",
"%w: 导航 AI Studio: %v": "{0}: AI Studio への移動: {1}",
"%w: 文件 ID 为空": "{0}: ファイル ID が空です",
"%w: 文件引用缺少 ID": "{0}: ファイル参照に ID がありません",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0}: 最新の会話ターンがモデルのコンテキスト ウィンドウ {1} を超えています",
+ "%w: AI Studio 的 Live 不提供 %s": "{0}: AI Studio の Live には {1} がありません",
"%w: 未识别的 bidi media type %q": "{0}: 未認識の bidi media type {1}",
"%w: 未识别的 bidi mode %q": "{0}: 未認識の bidi mode {1}",
"%w: 模型 %s 不支持 %s": "{0}: モデル {1} は {2} をサポートしていません",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: モデル {1} は media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog、turn_coverage に対応していません",
"%w: 模型 %s 不支持 system_instruction": "{0}: モデル {1} は system_instruction をサポートしていません",
"%w: 模型 %s 不支持 tools": "{0}: モデル {1} は tools をサポートしていません",
"%w: 模型 %s 不支持 transcription": "{0}: モデル {1} は transcription をサポートしていません",
"%w: 模型 %s 不支持 translation": "{0}: モデル {1} は translation をサポートしていません",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: モデル {1} は voice、media_resolution、thinking_level、context_window_compression をサポートしていません",
+ "%w: 模型 %s 不支持 voice": "{0}: モデル {1} は voice に対応していません",
"%w: 模型 %s 不是实时音乐模型": "{0}: モデル {1} はリアルタイム音楽モデルではありません",
"%w: 模型 %s 不输出视频": "{0}: モデル {1} は動画を出力しません",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: モデル {1} の output_modalities は [audio] である必要があります",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: リソース {1} はファイル参照として使用できません",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0}: ページは実行を開始済み、公式サイトの proof 関数の呼び出し={1}",
"%w: 首帧 type 必须是 setup": "{0}: 最初のフレームの type は setup である必要があります",
+ "%w: 首帧必须是 setup 消息": "{0}: 最初のメッセージは setup である必要があります",
"%v,官网跳转 %s": "{0}、公式サイトへのリダイレクト {1}",
"%w:在管理页面账户页添加账户": "{0}:管理コンソールのアカウントページでアカウントを追加してください",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0};.env の PROXY に GitHub へ接続できるプロキシを設定して再試行するか、{1} を手動でダウンロードして {2} に展開してください",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Chrome 更新アカウントが元のアカウントと一致しません",
"Chrome 账号重复: %s": "Chrome アカウントが重複しています: {0}",
"Chrome 账户已导入": "Chrome アカウントはインポート済みです",
- "CodeAssistantOffline contents 不能为空": "CodeAssistantOffline の contents は空にできません",
"Cookie JSON 无效: %w": "Cookie JSON が無効です: {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "Cookie の u/{0} でログインしているアカウントは {1} で、--email {2} と異なります",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Cookie インポート: aistudio2api setup --cookie 、--cookie-file または --cdp <デバッグアドレス>",
@@ -847,6 +861,7 @@
"检测代理池": "プロキシプールを確認中",
"模型 %s 不接受 agent_config": "モデル {0} は agent_config を受け付けません",
"模型 %s 不支持 %s": "モデル {0} は {1} に対応していません",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0} は API バージョン v1beta で見つからないか、{1} に対応していません。ListModels を呼び出すと、利用可能なモデルとそれぞれが対応するメソッドの一覧を確認できます。",
"模型 %s 没有 %s 任务": "モデル {0} には {1} タスクがありません",
"模型 %s 没有尾帧输入": "モデル {0} には末尾フレーム入力がありません",
"模型 %s 没有返回视频:%s": "モデル {0} から動画が返されませんでした:{1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "NCrypt ECDSA 公開鍵のエンコード: {0}",
"编码 NCrypt Provider 名称: %w": "NCrypt Provider 名前のエンコード: {0}",
"编码 NCrypt 公钥类型: %w": "NCrypt 公開鍵種類のエンコード: {0}",
+ "编码 bidi client_content: %w": "bidi client_content のエンコード: {0}",
+ "编码 bidi context_update: %w": "bidi context_update のエンコード: {0}",
"编码 bidi function declaration: %w": "bidi function declaration のエンコード: {0}",
"编码 bidi function response: %w": "bidi function response のエンコード: {0}",
"编码 bidi provider event: %w": "bidi provider event のエンコード: {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "AI Studio ページの TSDtV 実験トークン: {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "AI Studio ページの TSDtV に実験トークンがありません",
"AI Studio 页面 UUFaWc %w": "AI Studio ページ UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "AI Studio ページの report-only CSP: {0}",
"AI Studio 页面缺少 WIZ 数据": "AI Studio ページに WIZ データがありません",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "AI Studio ページに goX6ee または S6lZl がありません",
"JSPB 数组无效: %.20q": "JSPB 配列が無効です: {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "モデル {0} には次のいずれかの権限が必要ですが、このリクエストで使用できるアカウント({1})はいずれも備えていません: {2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction モデルの contents[{0}] はサーバー側ツールのステップ {1} を受け付けません",
"模型 %s 已在设置中隐藏": "モデル {0} は設定で非表示になっています",
- "Build 对话模型 %s 已在设置中关闭": "Build チャットモデル {0} は設定でオフになっています"
+ "Build 对话模型 %s 已在设置中关闭": "Build チャットモデル {0} は設定でオフになっています",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL は auto、agency、legacy のいずれかである必要があります",
+ "Build 写代码助手协议已选定": "Build チャットのプロトコルを選択しました",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "ページの起動データに Build チャットのプロトコルフラグ 45831005 がないため、旧プロトコルで動作しています。公式サイトがすべて新プロトコルに切り替わった場合は、設定で BUILD_CHAT_PROTOCOL を agency に固定してください",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "ページの起動データに Build チャットのプロトコルフラグ 45831005 がないため、旧プロトコルで動作しています",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "公式サイトがすべて新プロトコルに切り替わった場合は、設定で BUILD_CHAT_PROTOCOL を agency に固定してください",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "AI Studio フロントエンド バンドルにスクリプト読み込み呼び出し位置がないため、CSP レポートをスキップします",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "AI Studio フロントエンド バンドルにスクリプト読み込み呼び出しがないため、CSP の行・列位置の特定をスキップします",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "AI Studio の保護付きトランスポートは Build コード作成アシスタントのリクエストに対応していません",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "AI Studio ページの report-only CSP の解析に失敗したため、CSP レポートをスキップします",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "AI Studio ページに入門カード モジュールがないため、事前読み込みをスキップします",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "AI Studio ページのテレメトリ データの解析に失敗したため、そのまま起動を続行します",
+ "StreamRunAgentTask contents 不能为空": "Build コード作成アシスタントのリクエスト内容は空にできません",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Build コード作成アシスタントの再接続に必要なセッション履歴 ID がありません",
+ "后台刷新绑定会话失败": "バインド済みセッションのバックグラウンド更新に失敗しました",
+ "点击 AI Studio 启动覆盖层: %w": "AI Studio 起動オーバーレイのクリック: {0}",
+ "缺少步骤序号": "ステップ番号がありません",
+ "解析 AI Studio 启动覆盖层: %w": "AI Studio 起動オーバーレイの解析: {0}"
}
diff --git a/internal/i18n/messages/ko.json b/internal/i18n/messages/ko.json
index c7a35f07..cad65e02 100644
--- a/internal/i18n/messages/ko.json
+++ b/internal/i18n/messages/ko.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0}이(가) 여러 표시 대상과 일치합니다",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1}, AI Studio에 로그인한 브라우저에서 내보내세요",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0}: {1}은(는) 다른 AIStudio2API runtime에서 이미 사용 중입니다",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0}: Build 채널의 Live 세션은 client_content와 context_update를 지원하지 않습니다",
"%w: CountTokens model 不能为空": "{0}: CountTokens model은 비어 있을 수 없습니다",
"%w: GenerateContent model 不能为空": "{0}: GenerateContent model은 비어 있을 수 없습니다",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0}: Live는 functionDeclarations와 googleSearch 도구만 지원하며 {1}은(는) 지원하지 않습니다",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0}: Live의 안내와 턴은 텍스트 part만 지원합니다",
"%w: Waa/Create 未确认账户会话": "{0}: Waa/Create에서 계정 세션을 확인하지 못했습니다",
"%w: audio 未在 setup input_modalities 中声明": "{0}: setup input_modalities에 audio가 선언되지 않았습니다",
+ "%w: bidi client_content 不能为空": "{0}: bidi client_content는 비어 있을 수 없습니다",
+ "%w: bidi context_update 不能为空": "{0}: bidi context_update는 비어 있을 수 없습니다",
"%w: bidi function response 列表为空": "{0}: bidi function response 목록이 비어 있습니다",
"%w: bidi function response 缺少函数名": "{0}: bidi function response에 함수 이름이 없습니다",
"%w: bidi function response 缺少调用 ID": "{0}: bidi function response에 호출 ID가 없습니다",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0}: bidi model은 비어 있을 수 없습니다",
"%w: bidi text 不能为空": "{0}: bidi text는 비어 있을 수 없습니다",
"%w: embedding model 不能为空": "{0}: embedding model은 비어 있을 수 없습니다",
+ "%w: functionDeclarations 无效: %v": "{0}: functionDeclarations가 올바르지 않습니다: {1}",
"%w: image 未在 setup input_modalities 中声明": "{0}: setup input_modalities에 image가 선언되지 않았습니다",
"%w: inline data 缺少 MIME 或数据": "{0}: inline data에 MIME 또는 데이터가 없습니다",
"%w: live input modality %q 不可用": "{0}: live input modality {1}을(를) 사용할 수 없습니다",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0}: modality 목록은 비어 있을 수 없습니다",
"%w: music_config 必须是 JSON 对象": "{0}: music_config는 JSON 객체여야 합니다",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0}: playback_control은 play, pause, stop 또는 reset_context여야 합니다",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0}: realtimeInput의 미디어는 audio/pcm 또는 JPEG, PNG, WebP 이미지여야 합니다",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0}: realtimeInput의 미디어에는 mimeType과 base64 data가 필요합니다",
"%w: robotics input_modalities 必须是 [text]": "{0}: robotics input_modalities는 [text]여야 합니다",
"%w: robotics output_modalities 必须是 [text]": "{0}: robotics output_modalities는 [text]여야 합니다",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: robotics는 system_instruction, voice, media_resolution, thinking_level, context_window_compression 및 google_search를 지원하지 않습니다",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: robotics는 system_instruction, voice, media_resolution, thinking_level, context_window_compression, google_search, proactive_audio, proactive_video, enable_affective_dialog, turn_coverage를 지원하지 않습니다",
"%w: robotics 不支持 translation 或 transcription": "{0}: robotics는 translation 또는 transcription을 지원하지 않습니다",
+ "%w: setup 只能是首帧": "{0}: setup은 첫 번째 메시지여야 합니다",
"%w: storage state 缺少有效 Cookie: %s": "{0}: storage state에 유효한 쿠키가 없습니다: {1}",
"%w: text 未在 setup input_modalities 中声明": "{0}: setup input_modalities에 text가 선언되지 않았습니다",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0}: thinking_level은 minimal, low, medium 또는 high여야 합니다",
"%w: tool_response 的 setup 未声明 tools": "{0}: tool_response의 setup에 tools가 선언되지 않았습니다",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0}: turn_coverage는 only_activity, all_input 또는 audio_activity_and_all_video여야 합니다",
"%w: weighted_prompts 不能为空": "{0}: weighted_prompts는 비어 있을 수 없습니다",
"%w: weighted_prompts[%d].text 不能为空": "{0}: weighted_prompts[{1}].text는 비어 있을 수 없습니다",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0}: 실시간 음악 세션은 music_prompts, music_config 및 playback만 허용합니다",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: 실시간 음악 모델 {1}은(는) system_instruction, voice, media_resolution, thinking_level, context_window_compression 및 google_search를 지원하지 않습니다",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0}: 실시간 음악 모델 {1}은(는) tools, translation 또는 transcription을 지원하지 않습니다",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0}: 실시간 음악 모델 {1}의 output_modalities는 [audio]여야 합니다",
+ "%w: 客户端消息无效: %v": "{0}: 클라이언트 메시지가 올바르지 않습니다: {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0}: 클라이언트 메시지에는 setup, clientContent, realtimeInput, toolResponse 또는 contextUpdate가 포함되어야 합니다",
"%w: 导航 AI Studio: %v": "{0}: AI Studio 탐색 중: {1}",
"%w: 文件 ID 为空": "{0}: 파일 ID가 비어 있습니다",
"%w: 文件引用缺少 ID": "{0}: 파일 참조에 ID가 없습니다",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0}: 최신 대화 턴이 모델 컨텍스트 윈도우 {1}을(를) 초과했습니다",
+ "%w: AI Studio 的 Live 不提供 %s": "{0}: AI Studio의 Live는 {1}을(를) 제공하지 않습니다",
"%w: 未识别的 bidi media type %q": "{0}: 알 수 없는 bidi media type {1}",
"%w: 未识别的 bidi mode %q": "{0}: 알 수 없는 bidi mode {1}",
"%w: 模型 %s 不支持 %s": "{0}: {1} 모델은 {2} 기능을 지원하지 않습니다",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: 모델 {1}은(는) media_resolution, thinking_level, context_window_compression, proactive_audio, proactive_video, enable_affective_dialog, turn_coverage를 지원하지 않습니다",
"%w: 模型 %s 不支持 system_instruction": "{0}: {1} 모델은 system_instruction을 지원하지 않습니다",
"%w: 模型 %s 不支持 tools": "{0}: {1} 모델은 tools를 지원하지 않습니다",
"%w: 模型 %s 不支持 transcription": "{0}: {1} 모델은 transcription을 지원하지 않습니다",
"%w: 模型 %s 不支持 translation": "{0}: {1} 모델은 translation을 지원하지 않습니다",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: {1} 모델은 voice, media_resolution, thinking_level, context_window_compression을 지원하지 않습니다",
+ "%w: 模型 %s 不支持 voice": "{0}: 모델 {1}은(는) voice를 지원하지 않습니다",
"%w: 模型 %s 不是实时音乐模型": "{0}: {1} 모델은 실시간 음악 모델이 아닙니다",
"%w: 模型 %s 不输出视频": "{0}: {1} 모델은 동영상을 출력하지 않습니다",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: {1} 모델의 output_modalities는 [audio]여야 합니다",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: 리소스 {1}은(는) 파일 참조로 사용할 수 없습니다",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0}: 페이지가 실행을 시작함, 공식 사이트 proof 함수 호출={1}",
"%w: 首帧 type 必须是 setup": "{0}: 첫 프레임의 type은 setup이어야 합니다",
+ "%w: 首帧必须是 setup 消息": "{0}: 첫 번째 메시지는 setup이어야 합니다",
"%v,官网跳转 %s": "{0}, 공식 웹사이트 리디렉션 {1}",
"%w:在管理页面账户页添加账户": "{0}: 관리 페이지의 계정 페이지에서 계정을 추가하세요",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0}; .env의 PROXY에 GitHub에 접속할 수 있는 프록시를 설정한 뒤 다시 시도하거나, {1}을(를) 직접 다운로드해 {2}에 압축을 푸세요",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Chrome 업데이트 계정이 기존 계정과 일치하지 않습니다",
"Chrome 账号重复: %s": "Chrome 계정 중복: {0}",
"Chrome 账户已导入": "Chrome 계정을 가져왔습니다",
- "CodeAssistantOffline contents 不能为空": "CodeAssistantOffline contents는 비워 둘 수 없습니다",
"Cookie JSON 无效: %w": "Cookie JSON이 유효하지 않습니다: {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "쿠키의 u/{0}에 로그인된 계정은 {1}(으)로 --email {2}와 다릅니다",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Cookie 가져오기: aistudio2api setup --cookie , --cookie-file 또는 --cdp <디버그 주소>",
@@ -847,6 +861,7 @@
"检测代理池": "프록시 풀 확인 중",
"模型 %s 不接受 agent_config": "모델 {0}에서 agent_config를 지원하지 않습니다",
"模型 %s 不支持 %s": "모델 {0}에서 {1}을(를) 지원하지 않습니다",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0}을(를) API 버전 v1beta에서 찾을 수 없거나 {1}에 지원되지 않습니다. ListModels를 호출하면 사용 가능한 모델과 각 모델이 지원하는 메서드 목록을 볼 수 있습니다.",
"模型 %s 没有 %s 任务": "모델 {0}에 {1} 작업이 없습니다",
"模型 %s 没有尾帧输入": "모델 {0}에 마지막 프레임 입력이 없습니다",
"模型 %s 没有返回视频:%s": "모델 {0}에서 동영상을 반환하지 않았습니다: {1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "NCrypt ECDSA 공개 키 인코딩: {0}",
"编码 NCrypt Provider 名称: %w": "NCrypt Provider 이름 인코딩: {0}",
"编码 NCrypt 公钥类型: %w": "NCrypt 공개 키 유형 인코딩: {0}",
+ "编码 bidi client_content: %w": "bidi client_content 인코딩: {0}",
+ "编码 bidi context_update: %w": "bidi context_update 인코딩: {0}",
"编码 bidi function declaration: %w": "bidi function declaration 인코딩: {0}",
"编码 bidi function response: %w": "bidi function response 인코딩: {0}",
"编码 bidi provider event: %w": "bidi provider event 인코딩: {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "AI Studio 페이지 TSDtV 실험 토큰: {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "AI Studio 페이지 TSDtV에 실험 토큰이 없습니다",
"AI Studio 页面 UUFaWc %w": "AI Studio 페이지 UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "AI Studio 페이지 report-only CSP: {0}",
"AI Studio 页面缺少 WIZ 数据": "AI Studio 페이지에 WIZ 데이터가 없습니다",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "AI Studio 페이지에 goX6ee 또는 S6lZl이 없습니다",
"JSPB 数组无效: %.20q": "JSPB 배열이 잘못되었습니다: {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "모델 {0}에는 다음 권한 중 하나가 필요하지만 이 요청에서 사용할 수 있는 계정({1})에 없습니다: {2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction 모델의 contents[{0}]은(는) 서버 측 도구 단계 {1}을(를) 허용하지 않습니다",
"模型 %s 已在设置中隐藏": "모델 {0}은(는) 설정에서 숨겨져 있습니다",
- "Build 对话模型 %s 已在设置中关闭": "Build 대화 모델 {0}이(가) 설정에서 꺼져 있습니다"
+ "Build 对话模型 %s 已在设置中关闭": "Build 대화 모델 {0}이(가) 설정에서 꺼져 있습니다",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL은 auto, agency 또는 legacy여야 합니다",
+ "Build 写代码助手协议已选定": "Build 채팅 프로토콜을 선택했습니다",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "페이지 시작 데이터에 Build 채팅 프로토콜 플래그 45831005가 없어 이전 프로토콜로 실행합니다. 공식 사이트가 모두 새 프로토콜로 전환되었다면 설정에서 BUILD_CHAT_PROTOCOL을 agency로 고정하세요",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "페이지 시작 데이터에 Build 채팅 프로토콜 플래그 45831005가 없어 이전 프로토콜로 실행합니다",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "공식 사이트가 모두 새 프로토콜로 전환되었다면 설정에서 BUILD_CHAT_PROTOCOL을 agency로 고정하세요",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "AI Studio 프런트엔드 번들에 스크립트 로드 호출 위치가 없어 CSP 보고를 건너뜁니다",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "AI Studio 프런트엔드 번들에 스크립트 로드 호출이 없어 CSP 행과 열 위치 확인을 건너뜁니다",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "AI Studio 보호 전송은 Build 코드 작성 도우미 요청을 지원하지 않습니다",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "AI Studio 페이지의 report-only CSP를 구문 분석하지 못해 CSP 보고를 건너뜁니다",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "AI Studio 페이지에 시작하기 카드 모듈이 없어 미리 불러오기를 건너뜁니다",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "AI Studio 페이지의 원격 측정 데이터를 구문 분석하지 못해 해당 데이터 없이 시작을 계속합니다",
+ "StreamRunAgentTask contents 不能为空": "Build 코드 작성 도우미 요청 내용은 비워 둘 수 없습니다",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Build 코드 작성 도우미 재연결에 필요한 세션 기록 ID가 없습니다",
+ "后台刷新绑定会话失败": "바인딩된 세션의 백그라운드 새로고침에 실패했습니다",
+ "点击 AI Studio 启动覆盖层: %w": "AI Studio 시작 오버레이 클릭: {0}",
+ "缺少步骤序号": "단계 번호가 없습니다",
+ "解析 AI Studio 启动覆盖层: %w": "AI Studio 시작 오버레이 구문 분석: {0}"
}
diff --git a/internal/i18n/messages/zh-TW.json b/internal/i18n/messages/zh-TW.json
index b4628622..7c084915 100644
--- a/internal/i18n/messages/zh-TW.json
+++ b/internal/i18n/messages/zh-TW.json
@@ -30,10 +30,15 @@
"%v 匹配多个可见目标": "{0} 符合多個可見目標",
"%w %s,请在已登录 AI Studio 的浏览器中导出": "{0} {1},請在已登入 AI Studio 的瀏覽器中匯出",
"%w: %s 已由另一个 AIStudio2API runtime 使用": "{0}: {1} 已由另一個 AIStudio2API runtime 使用",
+ "%w: Build 通道的 Live 会话不支持 client_content 与 context_update": "{0}: Build 通道的 Live 工作階段不支援 client_content 與 context_update",
"%w: CountTokens model 不能为空": "{0}: CountTokens model 不能為空",
"%w: GenerateContent model 不能为空": "{0}: GenerateContent model 不能為空",
+ "%w: Live 只支持 functionDeclarations 与 googleSearch 工具,不支持 %s": "{0}: Live 只支援 functionDeclarations 與 googleSearch 工具,不支援 {1}",
+ "%w: Live 的指令与对话轮只支持文本 part": "{0}: Live 的指示與對話輪只支援文字 part",
"%w: Waa/Create 未确认账户会话": "{0}: Waa/Create 未確認帳號工作階段",
"%w: audio 未在 setup input_modalities 中声明": "{0}: audio 未在 setup input_modalities 中宣告",
+ "%w: bidi client_content 不能为空": "{0}: bidi client_content 不能為空",
+ "%w: bidi context_update 不能为空": "{0}: bidi context_update 不能為空",
"%w: bidi function response 列表为空": "{0}: bidi function response 清單為空",
"%w: bidi function response 缺少函数名": "{0}: bidi function response 缺少函式名稱",
"%w: bidi function response 缺少调用 ID": "{0}: bidi function response 缺少呼叫 ID",
@@ -41,6 +46,7 @@
"%w: bidi model 不能为空": "{0}: bidi model 不能為空",
"%w: bidi text 不能为空": "{0}: bidi text 不能為空",
"%w: embedding model 不能为空": "{0}: embedding model 不能為空",
+ "%w: functionDeclarations 无效: %v": "{0}: functionDeclarations 無效: {1}",
"%w: image 未在 setup input_modalities 中声明": "{0}: image 未在 setup input_modalities 中宣告",
"%w: inline data 缺少 MIME 或数据": "{0}: inline data 缺少 MIME 或資料",
"%w: live input modality %q 不可用": "{0}: live input modality {1} 無法使用",
@@ -52,32 +58,40 @@
"%w: modality 列表不能为空": "{0}: modality 清單不能為空",
"%w: music_config 必须是 JSON 对象": "{0}: music_config 必須是 JSON 物件",
"%w: playback_control 必须是 play、pause、stop 或 reset_context": "{0}: playback_control 必須是 play、pause、stop 或 reset_context",
+ "%w: realtimeInput 的媒体必须是 audio/pcm 或 JPEG、PNG、WebP 图片": "{0}: realtimeInput 的媒體必須是 audio/pcm 或 JPEG、PNG、WebP 圖片",
+ "%w: realtimeInput 的媒体需要 mimeType 与 base64 data": "{0}: realtimeInput 的媒體需要 mimeType 與 base64 data",
"%w: robotics input_modalities 必须是 [text]": "{0}: robotics input_modalities 必須是 [text]",
"%w: robotics output_modalities 必须是 [text]": "{0}: robotics output_modalities 必須是 [text]",
- "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: robotics 不支援 system_instruction、voice、media_resolution、thinking_level、context_window_compression 與 google_search",
+ "%w: robotics 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: robotics 不支援 system_instruction、voice、media_resolution、thinking_level、context_window_compression、google_search、proactive_audio、proactive_video、enable_affective_dialog 與 turn_coverage",
"%w: robotics 不支持 translation 或 transcription": "{0}: robotics 不支援 translation 或 transcription",
+ "%w: setup 只能是首帧": "{0}: setup 只能是第一則訊息",
"%w: storage state 缺少有效 Cookie: %s": "{0}: storage state 缺少有效 Cookie: {1}",
"%w: text 未在 setup input_modalities 中声明": "{0}: text 未在 setup input_modalities 中宣告",
"%w: thinking_level 必须是 minimal、low、medium 或 high": "{0}: thinking_level 必須是 minimal、low、medium 或 high",
"%w: tool_response 的 setup 未声明 tools": "{0}: tool_response 的 setup 未宣告 tools",
+ "%w: turn_coverage 必须是 only_activity、all_input 或 audio_activity_and_all_video": "{0}: turn_coverage 必須是 only_activity、all_input 或 audio_activity_and_all_video",
"%w: weighted_prompts 不能为空": "{0}: weighted_prompts 不能為空",
"%w: weighted_prompts[%d].text 不能为空": "{0}: weighted_prompts[{1}].text 不能為空",
"%w: 实时音乐会话只接受 music_prompts、music_config 与 playback": "{0}: 即時音樂工作階段只接受 music_prompts、music_config 與 playback",
"%w: 实时音乐模型 %s 不支持 system_instruction、voice、media_resolution、thinking_level、context_window_compression 与 google_search": "{0}: 即時音樂模型 {1} 不支援 system_instruction、voice、media_resolution、thinking_level、context_window_compression 與 google_search",
"%w: 实时音乐模型 %s 不支持 tools、translation 或 transcription": "{0}: 即時音樂模型 {1} 不支援 tools、translation 或 transcription",
"%w: 实时音乐模型 %s 的 output_modalities 必须是 [audio]": "{0}: 即時音樂模型 {1} 的 output_modalities 必須是 [audio]",
+ "%w: 客户端消息无效: %v": "{0}: 用戶端訊息無效: {1}",
+ "%w: 客户端消息需要含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate": "{0}: 用戶端訊息必須包含 setup、clientContent、realtimeInput、toolResponse 或 contextUpdate",
"%w: 导航 AI Studio: %v": "{0}: 導覽 AI Studio: {1}",
"%w: 文件 ID 为空": "{0}: 檔案 ID 為空",
"%w: 文件引用缺少 ID": "{0}: 檔案參照缺少 ID",
"%w: 最新对话轮次超过模型上下文窗口 %d": "{0}: 最新對話輪次超過模型上下文視窗 {1}",
+ "%w: AI Studio 的 Live 不提供 %s": "{0}: AI Studio 的 Live 不提供 {1}",
"%w: 未识别的 bidi media type %q": "{0}: 未辨識的 bidi media type {1}",
"%w: 未识别的 bidi mode %q": "{0}: 未辨識的 bidi mode {1}",
"%w: 模型 %s 不支持 %s": "{0}: 模型 {1} 不支援 {2}",
+ "%w: 模型 %s 不支持 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 与 turn_coverage": "{0}: 模型 {1} 不支援 media_resolution、thinking_level、context_window_compression、proactive_audio、proactive_video、enable_affective_dialog 與 turn_coverage",
"%w: 模型 %s 不支持 system_instruction": "{0}: 模型 {1} 不支援 system_instruction",
"%w: 模型 %s 不支持 tools": "{0}: 模型 {1} 不支援 tools",
"%w: 模型 %s 不支持 transcription": "{0}: 模型 {1} 不支援 transcription",
"%w: 模型 %s 不支持 translation": "{0}: 模型 {1} 不支援 translation",
- "%w: 模型 %s 不支持 voice、media_resolution、thinking_level 与 context_window_compression": "{0}: 模型 {1} 不支援 voice、media_resolution、thinking_level 與 context_window_compression",
+ "%w: 模型 %s 不支持 voice": "{0}: 模型 {1} 不支援 voice",
"%w: 模型 %s 不是实时音乐模型": "{0}: 模型 {1} 不是即時音樂模型",
"%w: 模型 %s 不输出视频": "{0}: 模型 {1} 不輸出影片",
"%w: 模型 %s 的 output_modalities 必须是 [audio]": "{0}: 模型 {1} 的 output_modalities 必須是 [audio]",
@@ -92,6 +106,7 @@
"%w: 资源 %s 不能作为文件引用": "{0}: 資源 {1} 不能作為檔案參照",
"%w: 页面已开始运行,官网取 proof 的函数已调用=%t": "{0}: 頁面已開始執行,官網取 proof 的函式已呼叫={1}",
"%w: 首帧 type 必须是 setup": "{0}: 首個訊框 type 必須是 setup",
+ "%w: 首帧必须是 setup 消息": "{0}: 第一則訊息必須是 setup",
"%v,官网跳转 %s": "{0},官網跳轉 {1}",
"%w:在管理页面账户页添加账户": "{0}:在管理頁面帳號頁新增帳號",
"%w;在 .env 的 PROXY 设置能访问 GitHub 的代理后重试,或手动下载 %s 解压到 %s": "{0};在 .env 的 PROXY 設定能存取 GitHub 的代理伺服器後重試,或手動下載 {1} 解壓縮到 {2}",
@@ -218,7 +233,6 @@
"Chrome 更新账户与原账户不匹配": "Chrome 更新帳號與原帳號不相符",
"Chrome 账号重复: %s": "Chrome 帳號重複: {0}",
"Chrome 账户已导入": "Chrome 帳號已匯入",
- "CodeAssistantOffline contents 不能为空": "CodeAssistantOffline contents 不能為空",
"Cookie JSON 无效: %w": "Cookie JSON 無效: {0}",
"Cookie 中 u/%d 登录的账户是 %s,与 --email %s 不同": "Cookie 中 u/{0} 登入的帳號是 {1},與 --email {2} 不同",
"Cookie 导入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <调试地址>": "Cookie 匯入: aistudio2api setup --cookie 、--cookie-file 或 --cdp <偵錯位址>",
@@ -847,6 +861,7 @@
"检测代理池": "檢測代理池",
"模型 %s 不接受 agent_config": "模型 {0} 不接受 agent_config",
"模型 %s 不支持 %s": "模型 {0} 不支援 {1}",
+ "模型 %s 不支持 %s 方法,可调用 ListModels 查看各模型支持的方法": "models/{0} 在 API 版本 v1beta 中找不到,或不支援 {1}。可呼叫 ListModels 查看可用模型及其支援的方法。",
"模型 %s 没有 %s 任务": "模型 {0} 沒有 {1} 任務",
"模型 %s 没有尾帧输入": "模型 {0} 沒有結尾影格輸入",
"模型 %s 没有返回视频:%s": "模型 {0} 沒有傳回影片:{1}",
@@ -959,6 +974,8 @@
"编码 NCrypt ECDSA 公钥: %w": "編碼 NCrypt ECDSA 公鑰: {0}",
"编码 NCrypt Provider 名称: %w": "編碼 NCrypt Provider 名稱: {0}",
"编码 NCrypt 公钥类型: %w": "編碼 NCrypt 公鑰類型: {0}",
+ "编码 bidi client_content: %w": "編碼 bidi client_content: {0}",
+ "编码 bidi context_update: %w": "編碼 bidi context_update: {0}",
"编码 bidi function declaration: %w": "編碼 bidi function declaration: {0}",
"编码 bidi function response: %w": "編碼 bidi function response: {0}",
"编码 bidi provider event: %w": "編碼 bidi provider event: {0}",
@@ -1447,7 +1464,6 @@
"AI Studio 页面 TSDtV 实验标记串: %w": "AI Studio 頁面 TSDtV 實驗標記串: {0}",
"AI Studio 页面 TSDtV 缺少实验标记串": "AI Studio 頁面 TSDtV 缺少實驗標記串",
"AI Studio 页面 UUFaWc %w": "AI Studio 頁面 UUFaWc {0}",
- "AI Studio 页面 report-only CSP: %w": "AI Studio 頁面 report-only CSP: {0}",
"AI Studio 页面缺少 WIZ 数据": "AI Studio 頁面缺少 WIZ 資料",
"AI Studio 页面缺少 goX6ee 或 S6lZl": "AI Studio 頁面缺少 goX6ee 或 S6lZl",
"JSPB 数组无效: %.20q": "JSPB 陣列無效: {0}",
@@ -1556,5 +1572,22 @@
"模型 %s 需要以下任一权益,本次请求可用的账户 %s 都不具备:%s": "模型 {0} 需要以下任一權益,本次請求可用的帳號 {1} 都不具備:{2}",
"Interaction 模型的 contents[%d] 不接受服务端工具步骤 %s": "Interaction 模型的 contents[{0}] 不接受伺服器端工具步驟 {1}",
"模型 %s 已在设置中隐藏": "模型 {0} 已在設定中隱藏",
- "Build 对话模型 %s 已在设置中关闭": "Build 對話模型 {0} 已在設定中關閉"
+ "Build 对话模型 %s 已在设置中关闭": "Build 對話模型 {0} 已在設定中關閉",
+ "BUILD_CHAT_PROTOCOL 必须是 auto、agency 或 legacy": "BUILD_CHAT_PROTOCOL 必須是 auto、agency 或 legacy",
+ "Build 写代码助手协议已选定": "Build 寫程式碼助手協定已選定",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行;若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "頁面啟動資料缺少 Build 對話協定旗標 45831005,目前依舊協定執行;若官網已全面改用新協定,可在設定中將 BUILD_CHAT_PROTOCOL 固定為 agency",
+ "页面启动数据缺少 Build 对话协议标志 45831005,当前按旧协议运行": "頁面啟動資料缺少 Build 對話協定旗標 45831005,目前依舊協定執行",
+ "若官网已全部改用新协议,可在设置中将 BUILD_CHAT_PROTOCOL 固定为 agency": "若官網已全面改用新協定,可在設定中將 BUILD_CHAT_PROTOCOL 固定為 agency",
+ "AI Studio 前端主程序缺少脚本加载调用位置,跳过 CSP 报告": "AI Studio 前端主程式缺少腳本載入呼叫位置,略過 CSP 報告",
+ "AI Studio 前端主程序缺少脚本加载调用,跳过 CSP 行列定位": "AI Studio 前端主程式缺少腳本載入呼叫,略過 CSP 行列定位",
+ "AI Studio 受保护传输不支持 Build 写代码助手请求": "AI Studio 受保護傳輸不支援 Build 寫程式碼助手請求",
+ "AI Studio 页面 report-only CSP 解析失败,跳过 CSP 报告": "AI Studio 頁面 report-only CSP 解析失敗,略過 CSP 報告",
+ "AI Studio 页面缺少入门卡片模块,跳过预载": "AI Studio 頁面缺少入門卡片模組,略過預載",
+ "AI Studio 页面遥测数据解析失败,降级继续启动": "AI Studio 頁面遙測資料解析失敗,降級繼續啟動",
+ "StreamRunAgentTask contents 不能为空": "Build 寫程式碼助手請求內容不能為空",
+ "StreamRunAgentTask 重连缺少 trajectory ID": "Build 寫程式碼助手重新連線缺少工作階段記錄 ID",
+ "后台刷新绑定会话失败": "背景重新整理綁定工作階段失敗",
+ "点击 AI Studio 启动覆盖层: %w": "點擊 AI Studio 啟動覆蓋層: {0}",
+ "缺少步骤序号": "缺少步驟序號",
+ "解析 AI Studio 启动覆盖层: %w": "解析 AI Studio 啟動覆蓋層: {0}"
}
diff --git a/internal/requestdb/requestdb.go b/internal/requestdb/requestdb.go
index 22451eb0..4642295c 100644
--- a/internal/requestdb/requestdb.go
+++ b/internal/requestdb/requestdb.go
@@ -44,7 +44,8 @@ const rollupColumns = `
start INTEGER NOT NULL, model TEXT NOT NULL, account TEXT NOT NULL, channel TEXT NOT NULL, protocol TEXT NOT NULL,
api_key TEXT NOT NULL, state TEXT NOT NULL, status INTEGER NOT NULL, requests INTEGER NOT NULL,
input_tokens INTEGER NOT NULL, cached_tokens INTEGER NOT NULL, reasoning_tokens INTEGER NOT NULL, reply_tokens INTEGER NOT NULL,
- total_tokens INTEGER NOT NULL, duration_ms INTEGER NOT NULL, first_event_ms INTEGER NOT NULL, first_events INTEGER NOT NULL,
+ total_tokens INTEGER NOT NULL, long_input_tokens INTEGER NOT NULL, long_cached_tokens INTEGER NOT NULL, long_output_tokens INTEGER NOT NULL,
+ duration_ms INTEGER NOT NULL, first_event_ms INTEGER NOT NULL, first_events INTEGER NOT NULL,
queue_ms INTEGER NOT NULL, duration_hist BLOB NOT NULL, first_event_hist BLOB NOT NULL, last_time INTEGER NOT NULL,
PRIMARY KEY (start, model, account, channel, protocol, api_key, state, status)`
@@ -63,7 +64,6 @@ CREATE TABLE IF NOT EXISTS requests (
reply_tool INTEGER NOT NULL DEFAULT 0, reply_tool_calls INTEGER NOT NULL DEFAULT 0, reply_tool_continuations INTEGER NOT NULL DEFAULT 0,
api_key TEXT NOT NULL DEFAULT '');
CREATE INDEX IF NOT EXISTS requests_time ON requests(time);
-CREATE INDEX IF NOT EXISTS requests_cost ON requests(time, model, input_tokens, cached_tokens, reasoning_tokens, reply_tokens, api_key);
CREATE INDEX IF NOT EXISTS requests_model_time ON requests(model, time);
CREATE INDEX IF NOT EXISTS requests_account_time ON requests(account, time);
CREATE INDEX IF NOT EXISTS requests_state_time ON requests(state, time);
@@ -371,12 +371,14 @@ func (store *Store) write(batch []write) (err error) {
func mergeRollup(tx *sql.Tx, table string, key rollupKey, value *entry) error {
existing := &entry{}
var durations, firstEvents []byte
- err := tx.QueryRow(`SELECT requests, input_tokens, cached_tokens, reasoning_tokens, reply_tokens, total_tokens, duration_ms,
+ err := tx.QueryRow(`SELECT requests, input_tokens, cached_tokens, reasoning_tokens, reply_tokens, total_tokens,
+ long_input_tokens, long_cached_tokens, long_output_tokens, duration_ms,
first_event_ms, first_events, queue_ms, duration_hist, first_event_hist, last_time FROM `+table+`
WHERE start=? AND model=? AND account=? AND channel=? AND protocol=? AND api_key=? AND state=? AND status=?`,
key.start, key.model, key.account, key.channel, key.protocol, key.apiKey, key.state, key.status).Scan(
&existing.requests, &existing.inputTokens, &existing.cachedTokens, &existing.reasoningTokens, &existing.replyTokens,
- &existing.totalTokens, &existing.durationMS, &existing.firstEventMS, &existing.firstEvents, &existing.queueMS, &durations,
+ &existing.totalTokens, &existing.longInputTokens, &existing.longCachedTokens, &existing.longOutputTokens,
+ &existing.durationMS, &existing.firstEventMS, &existing.firstEvents, &existing.queueMS, &durations,
&firstEvents, &existing.lastTime)
switch {
case errors.Is(err, sql.ErrNoRows):
@@ -391,10 +393,10 @@ func mergeRollup(tx *sql.Tx, table string, key rollupKey, value *entry) error {
}
value.combine(existing)
}
- _, err = tx.Exec(`INSERT OR REPLACE INTO `+table+` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ _, err = tx.Exec(`INSERT OR REPLACE INTO `+table+` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
key.start, key.model, key.account, key.channel, key.protocol, key.apiKey, key.state, key.status, value.requests,
value.inputTokens, value.cachedTokens, value.reasoningTokens, value.replyTokens, value.totalTokens,
- value.durationMS, value.firstEventMS, value.firstEvents, value.queueMS,
+ value.longInputTokens, value.longCachedTokens, value.longOutputTokens, value.durationMS, value.firstEventMS, value.firstEvents, value.queueMS,
value.duration.encode(), value.firstEvent.encode(), value.lastTime)
return err
}
diff --git a/internal/requestdb/usage.go b/internal/requestdb/usage.go
index 31a771ba..e6cc915c 100644
--- a/internal/requestdb/usage.go
+++ b/internal/requestdb/usage.go
@@ -38,13 +38,25 @@ type entry struct {
reasoningTokens int64
replyTokens int64
totalTokens int64
- durationMS int64
- firstEventMS int64
- firstEvents int64
- queueMS int64
- duration counts
- firstEvent counts
- lastTime int64
+ // long*Tokens 是输入超过长上下文阈值的请求的输入、缓存与输出 token,按长上下文分档计费
+ longInputTokens int64
+ longCachedTokens int64
+ longOutputTokens int64
+ durationMS int64
+ firstEventMS int64
+ firstEvents int64
+ queueMS int64
+ duration counts
+ firstEvent counts
+ lastTime int64
+}
+
+// markLong 在单条请求的输入超过长上下文阈值时把它的全部 token 记入长上下文分档,否则清零
+func (value *entry) markLong() {
+ value.longInputTokens, value.longCachedTokens, value.longOutputTokens = 0, 0, 0
+ if value.inputTokens > pricing.LongContext {
+ value.longInputTokens, value.longCachedTokens, value.longOutputTokens = value.inputTokens, value.cachedTokens, value.reasoningTokens+value.replyTokens
+ }
}
// rowEntry 把一条用量记录转换为汇总条目
@@ -55,6 +67,7 @@ func rowEntry(row *Row) *entry {
replyTokens: row.ReplyTokens, totalTokens: row.TotalTokens, durationMS: row.Duration.Milliseconds(),
queueMS: row.Queue.Milliseconds(), duration: single(row.Duration.Milliseconds()), lastTime: row.Time.UnixMilli(),
}
+ value.markLong()
if first := row.FirstEvent.Milliseconds(); first > 0 {
value.firstEventMS, value.firstEvents, value.firstEvent = first, 1, single(first)
}
@@ -76,6 +89,9 @@ func (value *entry) combine(other *entry) {
value.reasoningTokens += other.reasoningTokens
value.replyTokens += other.replyTokens
value.totalTokens += other.totalTokens
+ value.longInputTokens += other.longInputTokens
+ value.longCachedTokens += other.longCachedTokens
+ value.longOutputTokens += other.longOutputTokens
value.durationMS += other.durationMS
value.firstEventMS += other.firstEventMS
value.firstEvents += other.firstEvents
@@ -261,27 +277,41 @@ func appendSegment(segments []segment, part segment) []segment {
return append(segments, part)
}
-// plan 把 [from, to) 切成连续段:完整落在范围与单个分桶内的服务器本地日读取日汇总,其余部分按 planHours 切分
-func plan(from, to int64, starts []int64) []segment {
+// samePriceWindow 判断 (from, to) 开区间内没有单价切换时刻
+func samePriceWindow(cuts []int64, from, to int64) bool {
+ return !slices.ContainsFunc(cuts, func(cut int64) bool { return cut > from && cut < to })
+}
+
+// priceCuts 返回落在 [from, to] 内的单价切换毫秒时刻
+func priceCuts(from, to int64) []int64 {
+ var cuts []int64
+ for _, at := range pricing.Boundaries(time.UnixMilli(from), time.UnixMilli(to)) {
+ cuts = append(cuts, at.UnixMilli())
+ }
+ return cuts
+}
+
+// plan 把 [from, to) 切成连续段:完整落在范围、单个分桶与单个单价区间内的服务器本地日读取日汇总,其余部分按 planHours 切分;cuts 是单价切换时刻
+func plan(from, to int64, starts, cuts []int64) []segment {
var segments []segment
for start, end := localDay(from); start < to; start, end = localDay(end) {
- if start >= from && end <= to && sameBucket(starts, start, end) {
+ if start >= from && end <= to && sameBucket(starts, start, end) && samePriceWindow(cuts, start, end) {
segments = appendSegment(segments, segment{from: start, to: end, source: fromDays})
continue
}
- for _, part := range planHours(max(start, from), min(end, to), starts) {
+ for _, part := range planHours(max(start, from), min(end, to), starts, cuts) {
segments = appendSegment(segments, part)
}
}
return segments
}
-// planHours 把 [from, to) 切成连续段:完整落在范围与单个分桶内的整小时读取小时汇总,其余读取原始记录
-func planHours(from, to int64, starts []int64) []segment {
+// planHours 把 [from, to) 切成连续段:完整落在范围、单个分桶与单个单价区间内的整小时读取小时汇总,其余读取原始记录
+func planHours(from, to int64, starts, cuts []int64) []segment {
var segments []segment
for hour := floorDiv(from, hourMS) * hourMS; hour < to; hour += hourMS {
end, part := hour+hourMS, segment{from: max(hour, from), to: min(hour+hourMS, to)}
- if hour >= from && end <= to && sameBucket(starts, hour, end) {
+ if hour >= from && end <= to && sameBucket(starts, hour, end) && samePriceWindow(cuts, hour, end) {
part.source = fromHours
}
segments = appendSegment(segments, part)
@@ -314,7 +344,8 @@ func (store *Store) scan(ctx context.Context, part segment, filters api.UsageFil
value := &entry{}
if part.source != fromRequests {
rows, err := store.db.QueryContext(ctx, `SELECT start, model, account, channel, protocol, api_key, state, status, requests,
- input_tokens, cached_tokens, reasoning_tokens, reply_tokens, total_tokens, duration_ms, first_event_ms, first_events, queue_ms,
+ input_tokens, cached_tokens, reasoning_tokens, reply_tokens, total_tokens,
+ long_input_tokens, long_cached_tokens, long_output_tokens, duration_ms, first_event_ms, first_events, queue_ms,
duration_hist, first_event_hist, last_time FROM `+table+` WHERE `+column+` >= ? AND `+column+` < ?`+clause, args...)
if err != nil {
return err
@@ -323,7 +354,8 @@ func (store *Store) scan(ctx context.Context, part segment, filters api.UsageFil
for rows.Next() {
if err := rows.Scan(&value.time, &value.model, &value.account, &value.channel, &value.protocol, &value.apiKey, &value.state,
&value.status, &value.requests, &value.inputTokens, &value.cachedTokens, &value.reasoningTokens, &value.replyTokens,
- &value.totalTokens, &value.durationMS, &value.firstEventMS, &value.firstEvents, &value.queueMS, &durations, &firstEvents,
+ &value.totalTokens, &value.longInputTokens, &value.longCachedTokens, &value.longOutputTokens,
+ &value.durationMS, &value.firstEventMS, &value.firstEvents, &value.queueMS, &durations, &firstEvents,
&value.lastTime); err != nil {
return errors.Join(err, rows.Close())
}
@@ -351,6 +383,7 @@ func (store *Store) scan(ctx context.Context, part segment, filters api.UsageFil
&value.totalTokens, &value.cachedTokens); err != nil {
return errors.Join(err, rows.Close())
}
+ value.markLong()
value.lastTime = value.time
duration[0] = bucketCount{bucket: histogramBucket(value.durationMS), count: 1}
value.duration, value.firstEvent, value.firstEvents = duration[:], nil, 0
@@ -371,78 +404,22 @@ type cost struct {
unpriced map[string]bool
}
-// scanCost 在 SQL 中按分桶、单价分段、模型、长上下文分档与 API key 汇总 [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()
+// add 按条目的长上下文分档累加估算费用,bucket 不小于 0 时同时累加到该分桶;汇总条目由 plan 保证不跨分桶与单价切换,与逐条请求计价相同
+func (target *cost) add(value *entry, bucket int) {
+ output := value.reasoningTokens + value.replyTokens
+ if value.inputTokens+output > 0 && !pricing.Priced(value.model) {
+ target.unpriced[value.model] = true
}
- 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 = min(starts[index+1], to)
- }
- }
- if start >= stop {
- continue
- }
- 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)), keys: map[string]float64{}, 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, start, model, `+tier+`, api_key, 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, start, model, `+tier+`, api_key`, append(args, filterArgs...)...)
- if err != nil {
- return cost{}, err
+ at := time.UnixMilli(value.time)
+ amount := pricing.TierCost(value.model, at, false, value.inputTokens-value.longInputTokens, value.cachedTokens-value.longCachedTokens, output-value.longOutputTokens) +
+ pricing.TierCost(value.model, at, true, value.longInputTokens, value.longCachedTokens, value.longOutputTokens)
+ target.total += amount
+ if target.keys != nil {
+ target.keys[value.apiKey] += amount
}
- var slot int
- var start int64
- var long bool
- var input, cached, output int64
- var model, key string
- for rows.Next() {
- if err := rows.Scan(&slot, &start, &model, &long, &key, &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, time.UnixMilli(start), long, input, cached, output)
- result.total += value
- result.keys[key] += value
- if starts != nil {
- result.buckets[slot] += value
- }
+ if bucket >= 0 {
+ target.buckets[bucket] += amount
}
- return result, errors.Join(rows.Err(), rows.Close())
}
// usageDimensions 是报告分项包含的维度,比筛选维度多出 HTTP 状态码
@@ -469,10 +446,12 @@ func (store *Store) Usage(ctx context.Context, query api.UsageQuery) (api.UsageR
}
target[key].add(value)
}
+ current := cost{buckets: make([]float64, len(starts)), keys: map[string]float64{}, unpriced: map[string]bool{}}
visit := func(value *entry) {
index := bucketIndex(starts, value.time)
totals.add(value)
buckets[index].add(value)
+ current.add(value, index)
for _, dimension := range usageDimensions {
add(groups[dimension], value.dimension(dimension), value)
}
@@ -483,15 +462,19 @@ func (store *Store) Usage(ctx context.Context, query api.UsageQuery) (api.UsageR
stack[key][index][0] += value.requests
stack[key][index][1] += value.totalTokens
}
- segments := plan(from, to, starts)
+ segments := plan(from, to, starts, priceCuts(from, to))
for _, part := range segments {
if err := store.scan(ctx, part, query.Filters, visit); err != nil {
return api.UsageReport{}, err
}
}
previous := &aggregate{}
- for _, part := range plan(from-(to-from), from, nil) {
- if err := store.scan(ctx, part, query.Filters, previous.add); err != nil {
+ before := cost{unpriced: map[string]bool{}}
+ for _, part := range plan(from-(to-from), from, nil, priceCuts(from-(to-from), from)) {
+ if err := store.scan(ctx, part, query.Filters, func(value *entry) {
+ previous.add(value)
+ before.add(value, -1)
+ }); err != nil {
return api.UsageReport{}, err
}
}
@@ -499,14 +482,6 @@ func (store *Store) Usage(ctx context.Context, query api.UsageQuery) (api.UsageR
if err := store.scan(ctx, segment{from: now.Add(-recentWindow).UnixMilli(), to: now.UnixMilli() + 1}, query.Filters, recent.add); err != nil {
return api.UsageReport{}, err
}
- current, err := store.scanCost(ctx, from, to, starts, query.Filters)
- if err != nil {
- return api.UsageReport{}, err
- }
- before, err := store.scanCost(ctx, from-(to-from), from, nil, query.Filters)
- if err != nil {
- return api.UsageReport{}, err
- }
unpriced := slices.AppendSeq([]string{}, maps.Keys(current.unpriced))
slices.Sort(unpriced)
report := api.UsageReport{
@@ -541,11 +516,19 @@ func (store *Store) Usage(ctx context.Context, query api.UsageQuery) (api.UsageR
}
report.Options = map[string][]string{}
for _, dimension := range api.UsageDimensions {
- report.Options[dimension] = slices.Sorted(maps.Keys(groups[dimension]))
+ report.Options[dimension] = optionValues(groups[dimension])
}
return report, nil
}
+// optionValues 返回维度取值的升序列表,没有取值时为空切片,输出 []
+func optionValues[V any](values map[string]V) []string {
+ if len(values) == 0 {
+ return []string{}
+ }
+ return slices.Sorted(maps.Keys(values))
+}
+
// UsagePairs 返回时间范围内符合筛选的账户与模型组合汇总,按请求数降序、账户与模型升序排列
func (store *Store) UsagePairs(ctx context.Context, query api.UsageQuery) ([]api.UsagePair, error) {
totals := map[[2]string]*aggregate{}
@@ -556,7 +539,7 @@ func (store *Store) UsagePairs(ctx context.Context, query api.UsageQuery) ([]api
}
totals[key].add(value)
}
- for _, part := range plan(query.From.UnixMilli(), query.To.UnixMilli(), nil) {
+ for _, part := range plan(query.From.UnixMilli(), query.To.UnixMilli(), nil, nil) {
if err := store.scan(ctx, part, query.Filters, visit); err != nil {
return nil, err
}
@@ -633,7 +616,7 @@ func (store *Store) options(ctx context.Context, segments []segment) (map[string
}
options := map[string][]string{}
for dimension, values := range seen {
- options[dimension] = slices.Sorted(maps.Keys(values))
+ options[dimension] = optionValues(values)
}
return options, nil
}
diff --git a/internal/requestdb/usage_seed.go b/internal/requestdb/usage_seed.go
index 610dc5d8..95cf3bb0 100644
--- a/internal/requestdb/usage_seed.go
+++ b/internal/requestdb/usage_seed.go
@@ -58,7 +58,7 @@ func (store *Store) AccountUsageSeed(ctx context.Context, quotaDayStart time.Tim
if from >= to {
return seed, nil
}
- for _, part := range plan(from, to, nil) {
+ for _, part := range plan(from, to, nil, nil) {
if err := store.scan(ctx, part, nil, func(value *entry) {
if account := strings.TrimSpace(value.account); account != "" {
seed.QuotaDayRequests[account] += value.requests
diff --git a/internal/waa/dom.js b/internal/waa/dom.js
index 97eba7ba..a9a2c3b1 100644
--- a/internal/waa/dom.js
+++ b/internal/waa/dom.js
@@ -18,6 +18,8 @@
const brands = host.brands;
const realmName = host.realm;
const topRealm = host.topRealm || null;
+ // framePhase 是本页面 60 Hz 帧时钟的随机初始相位,取值 [0, 16.67) ms,同一页面各帧共用
+ const framePhase = topRealm && topRealm.framePhase !== undefined ? topRealm.framePhase : Math.floor(Math.random() * (1000 / 60) * 100) / 100;
// userActivation 记录顶层页面最近一次用户点击或按键的 Unix 毫秒时刻,各 Realm 共用
const userActivation = topRealm ? topRealm.userActivation : { at: null };
// transientActivationMs 是 Firefox dom.user_activation.transient.timeout 的瞬时激活时长
@@ -450,6 +452,7 @@
proto: name => protos[name],
pageOrigin: () => pageOrigin(),
userActivation,
+ framePhase,
// activate 记录一次用户点击或按键
activate: () => { userActivation.at = host.timeOrigin + host.performanceNow(); },
// mouseInput 按 Firefox 可信鼠标输入依次派发 types 中的事件:nodes 的布局矩形取 rects,指针与鼠标事件派发到指针下的 target,out 事件派发到指针离开的 left,坐标为 point,pointermove 与 mousemove 的移动量为 movement,焦点从 blurred 移到 focused,pointerdown 记录一次用户点击,同一次原生输入派生的各事件共用这次输入发生时的时间戳
@@ -1183,7 +1186,7 @@
const refreshTime = () => {
const frame = 1000 / 60;
const now = host.performanceNow();
- return Math.round((Math.floor((now - 0.66) / frame) * frame + 0.66) * 100) / 100;
+ return Math.max(0, Math.round((Math.floor((now - framePhase) / frame) * frame + framePhase) * 100) / 100);
};
const intersectionEntries = targets => targets.map(target => {
const bounds = layoutRect(target);
@@ -1599,7 +1602,6 @@
'IntersectionObserver.unobserve': (brand, [target]) => { brand.targets = brand.targets.filter(item => item !== target); },
'IntersectionObserver.disconnect': brand => { brand.targets = []; },
'IntersectionObserver.takeRecords': () => [],
- 'GPU.requestAdapter': () => Promise.resolve(null),
'Element.getClientRects': () => collection('DOMRectList', []),
'Document.createElement': function (brand, [name]) { return elementFor(this, name); },
'Document.createElementNS': function (brand, [, name]) { return elementFor(this, name); },
@@ -1687,7 +1689,7 @@
'Performance.getEntriesByType': (brand, [type]) => String(type) === 'navigation' ? navigationEntries() : [],
'Performance.getEntriesByName': (brand, [name]) => navigationEntries().filter(entry => readValue(entry, brandFor(entry), 'name') === String(name)),
'HTMLCanvasElement.getContext': function (brand, [type]) { if (String(type) !== '2d') return null; if (!brand.context2d) { brand.context2d = create('CanvasRenderingContext2D'); brandFor(brand.context2d).over.canvas = this; } return brand.context2d; },
- 'Window.getComputedStyle': () => create('CSSStyleProperties', (shape.singletonsComputed || {}).values || shape.defaults.CSSStyleProperties),
+ 'Window.getComputedStyle': () => create('CSSStyleProperties', shape.defaults.CSSStyleProperties),
'Window.matchMedia': (brand, [query]) => {
const list = create('MediaQueryList');
const text = String(query);
@@ -1699,7 +1701,7 @@
'Window.requestAnimationFrame': (brand, [callback]) => {
const frame = 1000 / 60;
const now = host.performanceNow();
- const next = Math.max(Math.floor((now - 0.66) / frame) * frame + 0.66 + frame, animationFrameTime + frame);
+ const next = Math.max(Math.floor((now - framePhase) / frame) * frame + framePhase + frame, animationFrameTime + frame);
const handle = ++animationHandle;
animationCallbacks.add(handle);
host.queueTask(Math.max(0, Math.ceil(next - now)), () => { if (animationCallbacks.delete(handle)) { animationFrameTime = next; callback(Math.round(next * 100) / 100); } });
@@ -2003,7 +2005,18 @@
DOMException: ([message, name]) => {
const error = create('DOMException');
const kind = name === undefined ? 'Error' : String(name);
- Object.assign(brandFor(error).over, { message: message === undefined ? '' : String(message), name: kind, code: domExceptionCodes[kind] || 0 });
+ const lines = (new Error().stack || '').split('\n').filter(line => line && !line.includes('dom.js') && !line.includes('host.js'));
+ const stack = lines.length ? lines.join('\n') + '\n' : '';
+ const loc = (lines[0] || '').match(/@(.*):(\d+):(\d+)$/);
+ Object.assign(brandFor(error).over, {
+ message: message === undefined ? '' : String(message),
+ name: kind,
+ code: domExceptionCodes[kind] || 0,
+ stack,
+ filename: loc ? loc[1] : '',
+ lineNumber: loc ? Number(loc[2]) : 0,
+ columnNumber: loc ? Number(loc[3]) : 0,
+ });
return error;
},
Blob: ([parts, options]) => blobFromParts('Blob', blobParts('Blob', parts), options && options.type),
diff --git a/internal/waa/firefox158.json.gz b/internal/waa/firefox158.json.gz
index 8a43d3bd..fe4f3d19 100644
Binary files a/internal/waa/firefox158.json.gz and b/internal/waa/firefox158.json.gz differ
diff --git a/internal/waa/host.go b/internal/waa/host.go
index e56157ce..63bcaff3 100644
--- a/internal/waa/host.go
+++ b/internal/waa/host.go
@@ -288,25 +288,26 @@ type realmHost struct {
// agent 保存一个 SpiderMonkey 上下文内各 Realm 共享的宿主数据
type agent struct {
- cx *mozjs.Context
- loop *eventLoop
- profile Profile
- loadImage func(string) bool
- loadFrame func(string) bool
- pending int
- settled []chan struct{}
- timezone string
- navigationStart time.Time
- depth int
- shared mozjs.Handle
- track mozjs.Handle
- notify mozjs.Handle
- activate mozjs.Handle
- mouseInput mozjs.Handle
- keyInput mozjs.Handle
- array mozjs.Handle
- top *realmHost
- realms []*realmHost
+ cx *mozjs.Context
+ loop *eventLoop
+ profile Profile
+ loadImage func(string) bool
+ loadFrame func(string) bool
+ pending int
+ settled []chan struct{}
+ timezone string
+ navigationStart time.Time
+ defaultLastModified string
+ depth int
+ shared mozjs.Handle
+ track mozjs.Handle
+ notify mozjs.Handle
+ activate mozjs.Handle
+ mouseInput mozjs.Handle
+ keyInput mozjs.Handle
+ array mozjs.Handle
+ top *realmHost
+ realms []*realmHost
}
// invoke 调用 JS 函数,最外层调用返回后执行微任务检查点
@@ -687,13 +688,28 @@ func (state *agent) realmProfile(realm string) map[string]any {
values["screen"] = profile.Screen
}
window := map[string]any{}
+ if state.defaultLastModified == "" {
+ loc, _ := time.LoadLocation(state.timezone)
+ at := state.navigationStart
+ if at.IsZero() {
+ at = time.Now()
+ }
+ state.defaultLastModified = at.In(loc).Format("01/02/2006 15:04:05")
+ }
+ lastMod, _ := profile.Document["lastModified"].(string)
+ if lastMod == "" {
+ lastMod = state.defaultLastModified
+ }
if realm == "top" {
for name, value := range profile.Window {
window[name] = value
}
- if len(profile.Document) > 0 {
- values["document"] = profile.Document
+ document := map[string]any{}
+ for name, value := range profile.Document {
+ document[name] = value
}
+ document["lastModified"] = lastMod
+ values["document"] = document
if width, ok := profile.Window["innerWidth"]; ok {
values["visualViewport"] = map[string]any{"width": width, "height": profile.Window["innerHeight"]}
}
@@ -706,14 +722,33 @@ func (state *agent) realmProfile(realm string) map[string]any {
window[name] = value
}
}
- document := map[string]any{}
- for _, name := range []string{"cookie", "lastModified"} {
- if value, ok := profile.Document[name]; ok {
- document[name] = value
- }
+ document := map[string]any{"lastModified": lastMod}
+ if value, ok := profile.Document["cookie"]; ok {
+ document["cookie"] = value
}
- if len(document) > 0 {
- values["document"] = document
+ values["document"] = document
+ reqStart := 2 + rand.IntN(4)
+ respStart := 40 + rand.IntN(140)
+ domInt := respStart + 2 + rand.IntN(6)
+ domDone := domInt + 1 + rand.IntN(4)
+ values["performance.navigationEntry"] = map[string]any{
+ "requestStart": reqStart,
+ "finalResponseHeadersStart": respStart,
+ "responseStart": respStart,
+ "responseEnd": respStart,
+ "domInteractive": domInt,
+ "domContentLoadedEventStart": domInt,
+ "domContentLoadedEventEnd": domInt,
+ "domComplete": domDone,
+ "loadEventStart": domDone,
+ "loadEventEnd": domDone,
+ "duration": domDone,
+ }
+ }
+ // screenLeft 与 screenTop 在 Firefox 中是 screenX 与 screenY 的别名
+ for alias, name := range map[string]string{"screenLeft": "screenX", "screenTop": "screenY"} {
+ if value, ok := profile.Window[name]; ok {
+ window[alias] = value
}
}
result := map[string]any{"hasFocus": profile.HasFocus, "window": window, "values": values, "mediaInputs": append([]string{}, profile.MediaInputs...)}
diff --git a/internal/waa/mozjs/clock.cpp b/internal/waa/mozjs/clock.cpp
index 56096558..4f28f42e 100644
--- a/internal/waa/mozjs/clock.cpp
+++ b/internal/waa/mozjs/clock.cpp
@@ -33,15 +33,32 @@ extern "C" double mz_clock(void) { return clockBase + std::min(clockLimit, clock
extern "C" double mz_clock_task(void) { return clockBase; }
#ifdef _WIN32
-// CyclesPerMillisecond 返回线程周期计数(时间戳计数器)每毫秒的增量,进程内第一次调用时以 2 ms 单调时钟测定
+// CyclesPerMillisecond 返回线程周期计数(时间戳计数器)每毫秒的增量,进程内第一次调用时以高分辨率等待定时器(非忙等)配合单调时钟测定
static double CyclesPerMillisecond() {
static const double value = [] {
auto started = std::chrono::steady_clock::now();
unsigned long long counter = __rdtsc();
- while (std::chrono::steady_clock::now() - started < std::chrono::milliseconds(2)) {
+# ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
+# define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x00000002
+# endif
+ HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
+ bool waited = false;
+ if (timer != nullptr) {
+ LARGE_INTEGER due;
+ due.QuadPart = -20000LL; // 2 ms (100ns units)
+ if (SetWaitableTimer(timer, &due, 0, nullptr, nullptr, FALSE)) {
+ WaitForSingleObject(timer, 20);
+ waited = true;
+ }
+ CloseHandle(timer);
+ }
+ if (!waited) {
+ Sleep(2);
}
unsigned long long elapsed = __rdtsc() - counter;
- return double(elapsed) / std::chrono::duration(std::chrono::steady_clock::now() - started).count();
+ double ms = std::chrono::duration(std::chrono::steady_clock::now() - started).count();
+ if (ms <= 0) ms = 2.0;
+ return double(elapsed) / ms;
}();
return value;
}
diff --git a/internal/waa/mozjs/mozjs.go b/internal/waa/mozjs/mozjs.go
index b87e470b..f7792a25 100644
--- a/internal/waa/mozjs/mozjs.go
+++ b/internal/waa/mozjs/mozjs.go
@@ -121,11 +121,13 @@ var (
stackSlack = 256 << 10
)
-// Init 初始化进程内的 SpiderMonkey,只执行一次
+// Init 初始化进程内的 SpiderMonkey,只执行一次,并在后台预热 Windows TSC 频率标定
func Init() error {
initOnce.Do(func() {
if reason := C.mz_init(); reason != nil {
initErr = fmt.Errorf("初始化 SpiderMonkey: %s", C.GoString(reason))
+ } else {
+ go func() { _ = CPU() }()
}
})
return initErr
diff --git a/internal/waa/rhythm/rhythm.go b/internal/waa/rhythm/rhythm.go
index bd6f9765..79307819 100644
--- a/internal/waa/rhythm/rhythm.go
+++ b/internal/waa/rhythm/rhythm.go
@@ -47,10 +47,11 @@ func New() Rhythm {
}
}
-// sample 取 values 中的一个值加上 ±1.5 ms 的均匀抖动,限制在 values 的最小与最大值之间
+// sample 取 values 中的一个值,在 values 的最小与最大值之间、该值 ±1.5 ms 的范围内均匀采样
func sample(values []float64) float64 {
- value := values[rand.IntN(len(values))] + rand.Float64()*3 - 1.5
- return min(max(value, slices.Min(values)), slices.Max(values))
+ base := values[rand.IntN(len(values))]
+ low, high := max(slices.Min(values), base-1.5), min(slices.Max(values), base+1.5)
+ return low + rand.Float64()*(high-low)
}
// Duration 返回毫秒间隔对应的时长
diff --git a/internal/waa/runtime.go b/internal/waa/runtime.go
index 6b04183d..999ab976 100644
--- a/internal/waa/runtime.go
+++ b/internal/waa/runtime.go
@@ -150,7 +150,7 @@ const newChatElements = `
// 焦点位置 prompt 为提示词输入框,result 为函数响应输入框,run、rerun 与 submit 为对应按钮
// 元素矩形按官网新对话页的布局,取值按 Firefox 以单精度浮点返回
const pointerScript = `((input, from, to, blurred, focused, rounds, types) => {` + promptElements + functionElements + settingsElements + newChatElements + `
- const section = innerWidth - 520;
+ const section = Math.max(innerWidth - 520, 220);
const box = Math.min(section, 1000);
const left = 220 + (section - box) / 2;
let turn = document.querySelector('ms-chat-turn');
@@ -167,8 +167,8 @@ const pointerScript = `((input, from, to, blurred, focused, rounds, types) => {`
const y = innerHeight - 59;
const button = [x, y, Math.fround(101.2), 32];
const top = Math.min(197.5 + 212 * (rounds - 1), innerHeight - 307.5);
- const icon = [Math.fround(left + 919 + 25 / 60), Math.fround(top - 10.5 - 5 / 60), Math.fround(15 + 11 / 60), Math.fround(15 + 11 / 60)];
- const rerunPoint = [Math.round(left + 927), Math.round(top - 3)];
+ const icon = [Math.fround(left + box - 81 + 25 / 60), Math.fround(top - 10.5 - 5 / 60), Math.fround(15 + 11 / 60), Math.fround(15 + 11 / 60)];
+ const rerunPoint = [Math.round(left + box - 73), Math.round(top - 3)];
const form = document.querySelector('ms-function-call-chunk').querySelector('form');
const field = form.querySelector('input');
const send = form.querySelector('button');
@@ -178,14 +178,14 @@ const pointerScript = `((input, from, to, blurred, focused, rounds, types) => {`
prompt: { target: textarea, point: [Math.round(left + box / 2), Math.round(innerHeight - 94.5)], nodes: [textarea, textarea.parentElement], rects: [[left + 25, innerHeight - 105, box - 50, 21], [left + 25, innerHeight - 105, box - 50, 36]] },
run: { target: run.firstElementChild, point: [Math.round(x + Math.fround(101.2) / 2), y + 16], nodes: [run.firstElementChild, run, run.parentElement], rects: [[Math.fround(x + 45), y + 6, Math.fround(24.2), 20], button, button] },
turn: { target: turn.firstElementChild, point: [Math.round(left + box / 2), Math.round(top + 62.75)], nodes: [turn], rects: [[left, top, box, 125.5]] },
- rerun: { target: rerun.querySelector('path'), point: rerunPoint, nodes: [rerun.querySelector('path'), rerun.querySelector('g'), rerun.querySelector('svg'), rerun, rerun.parentElement], rects: [icon, icon, [left + 917, top - 13, 20, 20], [left + 911, top - 19, 32, 32], [left + 867, top - 23, 120, 40]] },
+ rerun: { target: rerun.querySelector('path'), point: rerunPoint, nodes: [rerun.querySelector('path'), rerun.querySelector('g'), rerun.querySelector('svg'), rerun, rerun.parentElement], rects: [icon, icon, [left + box - 83, top - 13, 20, 20], [left + box - 89, top - 19, 32, 32], [left + box - 133, top - 23, 120, 40]] },
content: { target: turn.parentElement, point: rerunPoint, nodes: [turn.parentElement], rects: [[left, 88, box, top + 81.5]] },
answer: { target: turn.firstElementChild, point: rerunPoint, nodes: [turn.firstElementChild, turn.parentElement], rects: [[left, 88, box, top + 81.5], [left, 88, box, top + 81.5]] },
result: { target: field, point: [Math.round(left + 26 + (box - 120 - 1 / 3) / 2), Math.round(top + 247.5)], nodes: [field, field.parentElement, field.parentElement.parentElement, field.parentElement.parentElement.parentElement, form], rects: [fieldRect, fieldRect, fieldRect, [left + 26, top + 205.5, Math.fround(box - 120 - 1 / 3), 58], formRect] },
submit: { target: send, point: [Math.round(left + box - 86 - 1 / 3 + (60 + 1 / 3) / 2), Math.round(top + 247.5)], nodes: [send, form], rects: [[Math.fround(left + box - 86 - 1 / 3), top + 231.5, Math.fround(60 + 1 / 3), 32], formRect] },
};
const column = innerWidth - 300;
- for (const [name, rect] of [['selector', [column + 16, 92, 268, 36]], ['row', [innerWidth - 553, 256, 540, 50]], ['level', [column + 16, 300, 268, 40]], ['option', [column + 16, 330, 268, 48]], ['system', [column + 16, 184, 268, 48]], ['instructions', [innerWidth - 525, 356, 500, 300]], ['close', [innerWidth - 47, 13, 40, 40]], ['grounding', [innerWidth - 50, 549, 36, 20]], ['functions', [innerWidth - 50, 502, 36, 20]], ['edit', [innerWidth - 93, 497, 28, 28]], ['declarations', [innerWidth / 2 - 300, 110, 600, 320]], ['save', [innerWidth / 2 + 303, 618, 104, 36]], ['all', [innerWidth - 550, 117, 80, 36]]]) {
+ for (const [name, rect] of [['selector', [column + 16.8, 60, 268, 99]], ['row', [innerWidth - 553, 256, 540, 50]], ['level', [column + 24.8, 290, 252, 24]], ['option', [column + 16, 330, 268, 48]], ['system', [column + 16.8, 167, 268, 63]], ['instructions', [innerWidth - 525, 356, 500, 300]], ['close', [innerWidth - 47, 13, 40, 40]], ['grounding', [innerWidth - 50, 549, 36, 20]], ['functions', [innerWidth - 50, 502, 36, 20]], ['edit', [innerWidth - 104.2, 476, 51, 32]], ['declarations', [innerWidth / 2 - 300, 110, 600, 320]], ['save', [innerWidth / 2 + 303, 618, 104, 36]], ['all', [innerWidth - 550, 117, 80, 36]]]) {
const node = settings(name);
const target = node.firstElementChild ?? node;
spots[name] = { target, point: [Math.round(rect[0] + rect[2] / 2), Math.round(rect[1] + rect[3] / 2)], nodes: target === node ? [node, settingsRoot] : [target, node, settingsRoot], rects: target === node ? [rect, [column, 0, 300, innerHeight]] : [rect, rect, [column, 0, 300, innerHeight]] };
@@ -1165,6 +1165,34 @@ func (runtime *Runtime) Activate(ctx context.Context) error {
}
}
+// SetLocalStorage 把页面外部写入的 localStorage 键值同步到当前活跃 VM 的顶层 Realm
+func (runtime *Runtime) SetLocalStorage(ctx context.Context, key, value string) error {
+ keyJSON, _ := json.Marshal(key)
+ valJSON, _ := json.Marshal(value)
+ script := `localStorage.setItem(` + string(keyJSON) + `,` + string(valJSON) + `); 'ok'`
+ done := make(chan error, 1)
+ if !runtime.loop.post(func() {
+ value, err := runtime.agent.evaluate(runtime.agent.top.global, script, hostScriptName)
+ if err != nil {
+ runtime.agent.release(err)
+ done <- err
+ return
+ }
+ runtime.agent.cx.ReleaseValue(value)
+ done <- nil
+ }) {
+ return errors.New("WAA runtime 已关闭")
+ }
+ select {
+ case err := <-done:
+ return err
+ case <-runtime.loop.done:
+ return errors.New("WAA runtime 已关闭")
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
// RefreshSnapshot 生成官网刷新 Waa/Create 时携带的无绑定 snapshot,与取 proof 一样从官网取 proof 耗时中抽值并排进此前的空闲区间
func (runtime *Runtime) RefreshSnapshot(ctx context.Context) (string, error) {
runtime.operationMu.Lock()
diff --git a/internal/webui/embed.go b/internal/webui/embed.go
index 21e67a1e..94da4e03 100644
--- a/internal/webui/embed.go
+++ b/internal/webui/embed.go
@@ -70,7 +70,7 @@ func cacheControl(requestPath string) string {
// reservedPath 判断路径是否属于服务 API
func reservedPath(requestPath string) bool {
- for _, prefix := range []string{"/api", "/v1", "/v1beta", "/health"} {
+ for _, prefix := range []string{"/api", "/v1", "/v1beta", "/ws", "/health"} {
if requestPath == prefix || strings.HasPrefix(requestPath, prefix+"/") {
return true
}
diff --git a/web/package-lock.json b/web/package-lock.json
index d676f7f5..d0570e2e 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -11,8 +11,8 @@
"@fontsource-variable/google-sans-code": "5.3.2",
"@fontsource-variable/inter": "5.3.0",
"@fontsource-variable/inter-tight": "5.3.0",
- "@lobehub/icons-static-svg": "1.106.0",
- "@lucide/vue": "1.84.0",
+ "@lobehub/icons-static-svg": "1.107.0",
+ "@lucide/vue": "1.86.0",
"@material-symbols/svg-300": "0.49.0",
"@vscode/markdown-it-katex": "1.1.2",
"@wailsio/runtime": "3.1.0",
@@ -27,17 +27,17 @@
"thinking-orbs": "0.3.2",
"vue": "3.5.46",
"vue-echarts": "8.3.2",
- "vue-router": "5.5.3"
+ "vue-router": "5.6.1"
},
"devDependencies": {
"@tailwindcss/vite": "4.3.5",
"@types/node": "24.19.4",
"@typescript-eslint/parser": "8.74.0",
- "@vitejs/plugin-vue": "6.0.11",
+ "@vitejs/plugin-vue": "6.1.1",
"eslint": "10.16.0",
"eslint-config-prettier": "10.1.9",
- "eslint-plugin-oxlint": "1.95.0",
- "eslint-plugin-vue": "10.12.1",
+ "eslint-plugin-oxlint": "1.96.0",
+ "eslint-plugin-vue": "10.13.0",
"sass-embedded": "1.108.2",
"tailwindcss": "4.3.5",
"typescript": "6.0.3",
@@ -492,15 +492,15 @@
"license": "MIT"
},
"node_modules/@lobehub/icons-static-svg": {
- "version": "1.106.0",
- "resolved": "https://registry.npmjs.org/@lobehub/icons-static-svg/-/icons-static-svg-1.106.0.tgz",
- "integrity": "sha512-yRLkEGfCsOh6ZDSIPsA6HrI1ynh9gI1LECZaeFIzpuEHv9ON2i+SzwLnE2iYfW/agsms54QL+OhPde9WpEi/uA==",
+ "version": "1.107.0",
+ "resolved": "https://registry.npmjs.org/@lobehub/icons-static-svg/-/icons-static-svg-1.107.0.tgz",
+ "integrity": "sha512-eCcev8PGmtOMm67S/bzLHM/XH9XOMbdv5PW8h2gfpT7O81DbD+dz+91+I5P9YPS1HdLXViXFsHZH/jUBBvJNcA==",
"license": "MIT"
},
"node_modules/@lucide/vue": {
- "version": "1.84.0",
- "resolved": "https://registry.npmjs.org/@lucide/vue/-/vue-1.84.0.tgz",
- "integrity": "sha512-vZ3zqp8djXeuphloLxcFuQ2ehHdorPBIHXUy6H70Z62zxUoufQOqqo+pFyQRgMiZSvVtr5oCUeF45WynvBJfbw==",
+ "version": "1.86.0",
+ "resolved": "https://registry.npmjs.org/@lucide/vue/-/vue-1.86.0.tgz",
+ "integrity": "sha512-i9CR8MnbGEGiL6ldKFErdiM4/qFJrWwWsBCoW2t+hTqAZBOweNdBNJK3qfRRFf0m6L/RhRVp3gEuUHt7Q9spWw==",
"license": "ISC",
"peerDependencies": {
"vue": ">=3.0.1"
@@ -1145,9 +1145,9 @@
}
},
"node_modules/@oxlint/binding-android-arm-eabi": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.95.0.tgz",
- "integrity": "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.96.0.tgz",
+ "integrity": "sha512-SCINGNIfxMCeONnTjTQdm27XYY3zWv5olN/RIJmoTbMgphJ8JkZMeivswWqPdjwYpTAuskGNpHbevtECumuIxg==",
"cpu": [
"arm"
],
@@ -1163,9 +1163,9 @@
}
},
"node_modules/@oxlint/binding-android-arm64": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.95.0.tgz",
- "integrity": "sha512-uAIGZQ9uJVUeogeWOSboI3F7twOuM4mNuZcHXD9+LdYLcWp7J6kbtRUXJ6GVqcs5E0Cjb4emmSBK9FNrkGuhqQ==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.96.0.tgz",
+ "integrity": "sha512-jmRRp4pThMoYheXzhDrEMOHMU6X0geGSzJznkF2xhE9l0aViXNBvZrWasR5WLc3FXlc0rQAtV/o9mH1wosXZGQ==",
"cpu": [
"arm64"
],
@@ -1181,9 +1181,9 @@
}
},
"node_modules/@oxlint/binding-darwin-arm64": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.95.0.tgz",
- "integrity": "sha512-Ogh1vfHO5vshKRop/He46r+WqC5BTqonYwhB4fp9e2gvOFvg1Xi6XsHTuM/lBSH85ZcaG+DS99EMAy9GcwDong==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.96.0.tgz",
+ "integrity": "sha512-RxRoSJY2xa9/dKRzPv1rLn36OvaCwu7Qg9o+NhrSIP7FkLWackAkfbf+5bcgIC5H1r78sdWUvVAIDJKDdfkXPg==",
"cpu": [
"arm64"
],
@@ -1199,9 +1199,9 @@
}
},
"node_modules/@oxlint/binding-darwin-x64": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.95.0.tgz",
- "integrity": "sha512-kTrE1xfpQUBMMS50Ws6KY92N8OsJ8LE6JqxKqkHEY3KdsmguQ6kKVGSjzyt1HLwsSi0fQCvNRog8YRBBovD1AA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.96.0.tgz",
+ "integrity": "sha512-pokl9aeRHG0ke37GooIG/Jjd5bIFx9TDZ9//JkO0KDROJ3MIGz+KD9/hlq6siE40+auswpyaolZ4xNqzaX1VWw==",
"cpu": [
"x64"
],
@@ -1217,9 +1217,9 @@
}
},
"node_modules/@oxlint/binding-freebsd-x64": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.95.0.tgz",
- "integrity": "sha512-ho7E1VCInK0VnpneRaI1BEpe1ceJE8VjxP2O9THWdReV6bth1Q4+80kYVGGK47mHRyZ2NGztQZ2dWRo6j1lavA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.96.0.tgz",
+ "integrity": "sha512-zV8oqk0kzAFa8hsiBXz431E9DvYZuhIOveTKk7bgKmeYy1KixJ//iwdBMvD6+IGq0HAxxX2eCAbdzecC2Qsrpw==",
"cpu": [
"x64"
],
@@ -1235,9 +1235,9 @@
}
},
"node_modules/@oxlint/binding-linux-arm-gnueabihf": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.95.0.tgz",
- "integrity": "sha512-94afnouMHcnHr/OtRh07gG5LehC9M0GjiSoik3xxTtrmq6cWxXOTAhYlBtxa67u/GlycbnHlDoGJfYlTshcr/w==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.96.0.tgz",
+ "integrity": "sha512-hT4CHT09eiWrwIikLjqiQrcjF1lASaRrJR4rGwXhHQcXC8Z5ohkDOy897tV/+UK/RkDvhtX3YOV3LGultcJTxg==",
"cpu": [
"arm"
],
@@ -1253,9 +1253,9 @@
}
},
"node_modules/@oxlint/binding-linux-arm-musleabihf": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.95.0.tgz",
- "integrity": "sha512-LEeclqV1/fafxPgJWN21Bri6HBBBZpEFluq/ZH7Avvu9HjJh/XOn6WwogJqX9X7pG2aITZ2nRH39+sUKEQt2WA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.96.0.tgz",
+ "integrity": "sha512-ro+mX13ijz/Z2IIstN3TnPjoOzMZmvvS6xj/RIkyWZJveU/W5WkuFkISb81M7dxVDywHNUUljs9kGXL+ZpCkAA==",
"cpu": [
"arm"
],
@@ -1271,9 +1271,9 @@
}
},
"node_modules/@oxlint/binding-linux-arm64-gnu": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.95.0.tgz",
- "integrity": "sha512-EpXpEQKmgtkvc6RyU84LM1e3CrVDWQkgghVzf1hMGgwjBzgKAJ/QntHgnzmu5cNeLBfa7GPCY+gGXxEll8Adcg==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.96.0.tgz",
+ "integrity": "sha512-kpJqgwJ4xCzg0HiZr0IqPumqoskk7z9m+epDKC8cxuC6sS5GeX0u8XpuotC7BKto0htzq+AmpZ6/LPIqOJ2J2w==",
"cpu": [
"arm64"
],
@@ -1292,9 +1292,9 @@
}
},
"node_modules/@oxlint/binding-linux-arm64-musl": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.95.0.tgz",
- "integrity": "sha512-+96Md8c2BAgFp8nWHrUrpqba87DoU+HVJYIun6qA+QKFoeNd3xAWq1JYE6da4nVli9GgwRpfncfRePcgmQQaIQ==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.96.0.tgz",
+ "integrity": "sha512-sPqrWFuk8IsDx5ftGQVCaxRfnR95b3aXFQrknHDsb0W6UGYkhmhU6ZcirV/9Etyf44dAYo3ZMyA30bRow1sz5w==",
"cpu": [
"arm64"
],
@@ -1313,9 +1313,9 @@
}
},
"node_modules/@oxlint/binding-linux-ppc64-gnu": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.95.0.tgz",
- "integrity": "sha512-6yG99vsXct3Uv536w6Z1s03w2makRKnE0q3eJSmf+W/IwPmO56QLk8XUA6ebu/R5peCbJ67HmcWqACH+kg/6Bg==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.96.0.tgz",
+ "integrity": "sha512-41bcNpgz0TDw2bPseL18MWtiyxrkadp5XVqRPr3TmGSDO2NpXdrHQ3UbXOiSpi5Dko7H22iNg9kcl/q/TZrcWA==",
"cpu": [
"ppc64"
],
@@ -1334,9 +1334,9 @@
}
},
"node_modules/@oxlint/binding-linux-riscv64-gnu": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.95.0.tgz",
- "integrity": "sha512-Eir0Z4ldh55AsQUqVDlLF4Pw3lSFXIdAl8ZNgU8tp/gTwT9JVCzWY0o3+ys9pCcpTN0vCqBwwuQfAUxzbIgvcQ==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.96.0.tgz",
+ "integrity": "sha512-XsuYByplvx4CjLwBTDNiWEB3Igk1NVgg0jqndZA9Op59ssCqO9PYZmg8af+GMOfrOtpdiFiGnogi0PfvCihGrg==",
"cpu": [
"riscv64"
],
@@ -1355,9 +1355,9 @@
}
},
"node_modules/@oxlint/binding-linux-riscv64-musl": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.95.0.tgz",
- "integrity": "sha512-ceRx+K2WJ7C3tIv+XjZS28oAoZ7DY29ZcWChPdXG5M100phI72FRDYwGRlWZEeDfmkROnarLTMKnnrQAtsC42Q==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.96.0.tgz",
+ "integrity": "sha512-J+JcvoObB6gsi3TxaY8tu0gc2ZEcxYbKz7t0N85RurdEU1ubXHTJqKOe8D5aH3KPSmlT3+8f81UhVI4qF4WoUQ==",
"cpu": [
"riscv64"
],
@@ -1376,9 +1376,9 @@
}
},
"node_modules/@oxlint/binding-linux-s390x-gnu": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.95.0.tgz",
- "integrity": "sha512-WbD3sM08ZDk2QE6060wK/omihQKbRm+LVzKIg4W5zNTbEhYJChciqX49UZuqW59RGF+wBUxzAup7egUIESTjUA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.96.0.tgz",
+ "integrity": "sha512-wON5n7KlNpVWMhzYt9G3Ew2iuL6hHt0LV69dg51quv78mx7jOWFZp/+2ny2vARWl1542RRSip70hb7DAj2yy+Q==",
"cpu": [
"s390x"
],
@@ -1397,9 +1397,9 @@
}
},
"node_modules/@oxlint/binding-linux-x64-gnu": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.95.0.tgz",
- "integrity": "sha512-F4ST2ZkFIiLL9OKyRCyC0KQQpwM5WIv0GTcMiZuYVa6xSRJHR05iVRqst+arOVudEPkhP47EnbuoC9UfVCYDyg==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.96.0.tgz",
+ "integrity": "sha512-AURdLIDjJvUK1XjWtnQI6TJs8F3SAQOFsDeL3QQChNwKAWbCZmT4jjflXMb6hjTY6NS1mnP1Z2sWz/yLI1BvTg==",
"cpu": [
"x64"
],
@@ -1418,9 +1418,9 @@
}
},
"node_modules/@oxlint/binding-linux-x64-musl": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.95.0.tgz",
- "integrity": "sha512-hEpYDZatpuxLrWlTlkwhHZ1e8QkL02aFS55BPQX1XA9iOd+yUEADGFF1iY6z+xkw6RkpzXFrtnDFe4/JNOLSRA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.96.0.tgz",
+ "integrity": "sha512-4+qtiKtCov+b8psbs4/O3nOtNh40bZN/QYxjjmOgV7OHmcD8rBwJqV4AeeXGZ/pSUCGNYGm1sQtiy4AAhJ5xqQ==",
"cpu": [
"x64"
],
@@ -1439,9 +1439,9 @@
}
},
"node_modules/@oxlint/binding-openharmony-arm64": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.95.0.tgz",
- "integrity": "sha512-+JwIH9/uLgQXfxBvOAKzvp616m5i0fBR5ELEBHm5D+++fStBZ+74T7YW4xBpX13zNU2blr52Swoe3GTF1JyqRg==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.96.0.tgz",
+ "integrity": "sha512-eYZmZlTFgwz3c0+nLlZc+QdFTJJQ9B98vvLSk8LPJm+edhhiuLOe6jIUiLWwc52s95GKz5US05cAsVd8e5BzOA==",
"cpu": [
"arm64"
],
@@ -1457,9 +1457,9 @@
}
},
"node_modules/@oxlint/binding-win32-arm64-msvc": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.95.0.tgz",
- "integrity": "sha512-pzJgcp3WkOSchukg5y5pn5mVIQ6P83RDI79YJ9gQZKed1pOgjhrmlc5AMizjuq6/P8VifhxzBsMqYI6LLjO2TA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.96.0.tgz",
+ "integrity": "sha512-elsIvBZeDYDO3swjXGBh8kGrsVrlcDNv6X2+ASA7q02UPuAWjH5F8urTa2d32c+f7l9MFohMokdWZ82pV+oZ9Q==",
"cpu": [
"arm64"
],
@@ -1475,9 +1475,9 @@
}
},
"node_modules/@oxlint/binding-win32-ia32-msvc": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.95.0.tgz",
- "integrity": "sha512-54MeQvLRXkJqF1nEFs7wb73SrnurZJQy9fVK4NdEwumNKVwyUUxpGHhvfDMIY2NqJZS7kz0pY9uVty5664Gt1Q==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.96.0.tgz",
+ "integrity": "sha512-Sl6tX5MdGZ886jSHmeg71ijhtsELauPl4ii4pfAtrQV3W7uj+v5QF1eAZB74KySWt6sdZuNDyjfhaKGaCf6NWA==",
"cpu": [
"ia32"
],
@@ -1493,9 +1493,9 @@
}
},
"node_modules/@oxlint/binding-win32-x64-msvc": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.95.0.tgz",
- "integrity": "sha512-I/Fn+Fed1qzb1k2uRjMe2VRtRN1+ZObyU+E76B6v/Ul3Z6JdeAW5zBHSe0n5d8a0ZyU4iorzVy0Rw9LYgo3MSQ==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.96.0.tgz",
+ "integrity": "sha512-gLx6y/CsxfNZdfBfSLbVHB75AHDfV2/XdilDqPgh7oNRL6y72s75TCbMt500km+Mk5izFYNYXX8+LYR6U4n/zA==",
"cpu": [
"x64"
],
@@ -1824,9 +1824,9 @@
"license": "MIT"
},
"node_modules/@rolldown/pluginutils": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
- "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
+ "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
"license": "MIT"
},
"node_modules/@rollup/pluginutils": {
@@ -2645,13 +2645,13 @@
}
},
"node_modules/@vitejs/plugin-vue": {
- "version": "6.0.11",
- "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.11.tgz",
- "integrity": "sha512-m48lskIUJGlB6qUiYhDMI8nd2ngeidz2U4nKTjqI13cFMu5rH8JeEILPkDtK9Fk/TjBA2pkj8AlbenqDaKu+ww==",
+ "version": "6.1.1",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.1.1.tgz",
+ "integrity": "sha512-ESHe2nVa454xILK3YHLF0NCbtk6CMib3VdxAcGuyis1P6amD5WtTxkPXrQc6s6NtGzqz/Nf9aNA22wJJA8rK7g==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@rolldown/pluginutils": "^1.0.1"
+ "@rolldown/pluginutils": "^1.1.1"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
@@ -4045,22 +4045,22 @@
}
},
"node_modules/eslint-plugin-oxlint": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/eslint-plugin-oxlint/-/eslint-plugin-oxlint-1.95.0.tgz",
- "integrity": "sha512-JVl2HXdkxg7MNSTzMapg4yhCep3OsxFxFuX8RmZxF9z4/SXwXodQJIsVK4Ce3Zej1QnodlohQOC47C7OokT4AQ==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-oxlint/-/eslint-plugin-oxlint-1.96.0.tgz",
+ "integrity": "sha512-SeHiUavS7sYsVFlO0JTE3WKTeMehGiycPgSY28sfcpDex1DVwac8+8xzSWPfPEnTtcBgmMBp8X+JwIQHZMssMA==",
"dev": true,
"license": "MIT",
"dependencies": {
"jsonc-parser": "^3.3.1"
},
"peerDependencies": {
- "oxlint": "~1.95.0"
+ "oxlint": "~1.96.0"
}
},
"node_modules/eslint-plugin-vue": {
- "version": "10.12.1",
- "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.12.1.tgz",
- "integrity": "sha512-Z5hmchVWq4EEOCn131J2p/uS4hjkrC+goPV5c/YApTY68xTqV3K5IYqD0mYGupDvZ6iYoTSuhSZUoWN+gZIqZQ==",
+ "version": "10.13.0",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.13.0.tgz",
+ "integrity": "sha512-6WJaRHDEhGw+aklA2byYXtlA4Nq6JpZXRfw9OZp8lSGDcNtWcQztNSmJk11/4WyoTj9qL2/gqNZMQPL9t1lbsA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4075,10 +4075,10 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"peerDependencies": {
- "@stylistic/eslint-plugin": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0",
+ "@stylistic/eslint-plugin": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0",
"@typescript-eslint/parser": "^7.0.0 || ^8.0.0",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
- "vue-eslint-parser": "^10.3.0"
+ "vue-eslint-parser": "^10.4.2"
},
"peerDependenciesMeta": {
"@stylistic/eslint-plugin": {
@@ -5132,9 +5132,9 @@
}
},
"node_modules/oxlint": {
- "version": "1.95.0",
- "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.95.0.tgz",
- "integrity": "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA==",
+ "version": "1.96.0",
+ "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.96.0.tgz",
+ "integrity": "sha512-jyiSvUjzM6GPHNbNQSk9ov63KDusn7FJaIX4LqxJYN/VnRrEgwMplyZaoAfmVclfzxCmVhaIXLixnRJ2IAa0Hw==",
"dev": true,
"license": "MIT",
"peer": true,
@@ -5148,25 +5148,25 @@
"url": "https://github.com/sponsors/oxc-project"
},
"optionalDependencies": {
- "@oxlint/binding-android-arm-eabi": "1.95.0",
- "@oxlint/binding-android-arm64": "1.95.0",
- "@oxlint/binding-darwin-arm64": "1.95.0",
- "@oxlint/binding-darwin-x64": "1.95.0",
- "@oxlint/binding-freebsd-x64": "1.95.0",
- "@oxlint/binding-linux-arm-gnueabihf": "1.95.0",
- "@oxlint/binding-linux-arm-musleabihf": "1.95.0",
- "@oxlint/binding-linux-arm64-gnu": "1.95.0",
- "@oxlint/binding-linux-arm64-musl": "1.95.0",
- "@oxlint/binding-linux-ppc64-gnu": "1.95.0",
- "@oxlint/binding-linux-riscv64-gnu": "1.95.0",
- "@oxlint/binding-linux-riscv64-musl": "1.95.0",
- "@oxlint/binding-linux-s390x-gnu": "1.95.0",
- "@oxlint/binding-linux-x64-gnu": "1.95.0",
- "@oxlint/binding-linux-x64-musl": "1.95.0",
- "@oxlint/binding-openharmony-arm64": "1.95.0",
- "@oxlint/binding-win32-arm64-msvc": "1.95.0",
- "@oxlint/binding-win32-ia32-msvc": "1.95.0",
- "@oxlint/binding-win32-x64-msvc": "1.95.0"
+ "@oxlint/binding-android-arm-eabi": "1.96.0",
+ "@oxlint/binding-android-arm64": "1.96.0",
+ "@oxlint/binding-darwin-arm64": "1.96.0",
+ "@oxlint/binding-darwin-x64": "1.96.0",
+ "@oxlint/binding-freebsd-x64": "1.96.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.96.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.96.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.96.0",
+ "@oxlint/binding-linux-arm64-musl": "1.96.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.96.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.96.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.96.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.96.0",
+ "@oxlint/binding-linux-x64-gnu": "1.96.0",
+ "@oxlint/binding-linux-x64-musl": "1.96.0",
+ "@oxlint/binding-openharmony-arm64": "1.96.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.96.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.96.0",
+ "@oxlint/binding-win32-x64-msvc": "1.96.0"
},
"peerDependencies": {
"oxlint-tsgolint": ">=7.0.2008",
@@ -6999,9 +6999,9 @@
}
},
"node_modules/vue-eslint-parser": {
- "version": "10.4.1",
- "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.1.tgz",
- "integrity": "sha512-Gk6gRDj0n/fkRa3C3l0bBheoBckUq/Rs0F/TvMWIS6nzzx67amAViMe9CkNgsP2tXyQONvGiHQESHwFtZ3aYDA==",
+ "version": "10.5.1",
+ "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.5.1.tgz",
+ "integrity": "sha512-+6J6+BESWcaJTaYFT5lT8a+PGlhGxlAqWflxz2pkitiZqH6gPd+WmpSjM2gRe86r/EZ841yxOjHbdtvO7exRlw==",
"dev": true,
"license": "MIT",
"peer": true,
@@ -7024,9 +7024,9 @@
}
},
"node_modules/vue-router": {
- "version": "5.5.3",
- "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.5.3.tgz",
- "integrity": "sha512-F3uyE2siuOC8QLxR3YAdqtxTEgLM/+rc0Fvej7/DVo6YTY5RgLBQpm1+fYP26ITjD3Fg5rDWuzBKxIB6rjlt1w==",
+ "version": "5.6.1",
+ "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.6.1.tgz",
+ "integrity": "sha512-CgcxR/XBuqaDKwu0QnSEzosjPq7hbLXVhov5SD8CHmnh6NYjJRHuWFOfJhZvB6XCc7NGYl6sttHRxai+VUJ30g==",
"license": "MIT",
"dependencies": {
"@vue-macros/common": "^3.1.4",
@@ -7050,7 +7050,7 @@
"url": "https://github.com/sponsors/posva"
},
"peerDependencies": {
- "@pinia/colada": ">=0.21.2",
+ "@pinia/colada": "^1.4.9",
"@vue/compiler-sfc": "^3.5.34 || ^3.6.0-0 || ^4.0.0",
"pinia": "^3.0.4 || ^4.0.2",
"vite": "^7.3.0 || ^8.0.0",
diff --git a/web/package.json b/web/package.json
index b390ada7..f61da8a2 100644
--- a/web/package.json
+++ b/web/package.json
@@ -18,8 +18,8 @@
"@fontsource-variable/google-sans-code": "5.3.2",
"@fontsource-variable/inter": "5.3.0",
"@fontsource-variable/inter-tight": "5.3.0",
- "@lobehub/icons-static-svg": "1.106.0",
- "@lucide/vue": "1.84.0",
+ "@lobehub/icons-static-svg": "1.107.0",
+ "@lucide/vue": "1.86.0",
"@material-symbols/svg-300": "0.49.0",
"@vscode/markdown-it-katex": "1.1.2",
"@wailsio/runtime": "3.1.0",
@@ -34,17 +34,17 @@
"thinking-orbs": "0.3.2",
"vue": "3.5.46",
"vue-echarts": "8.3.2",
- "vue-router": "5.5.3"
+ "vue-router": "5.6.1"
},
"devDependencies": {
"@tailwindcss/vite": "4.3.5",
"@types/node": "24.19.4",
"@typescript-eslint/parser": "8.74.0",
- "@vitejs/plugin-vue": "6.0.11",
+ "@vitejs/plugin-vue": "6.1.1",
"eslint": "10.16.0",
"eslint-config-prettier": "10.1.9",
- "eslint-plugin-oxlint": "1.95.0",
- "eslint-plugin-vue": "10.12.1",
+ "eslint-plugin-oxlint": "1.96.0",
+ "eslint-plugin-vue": "10.13.0",
"sass-embedded": "1.108.2",
"tailwindcss": "4.3.5",
"typescript": "6.0.3",
diff --git a/web/src/App.vue b/web/src/App.vue
index 15a36d97..13e7a9a0 100644
--- a/web/src/App.vue
+++ b/web/src/App.vue
@@ -18,6 +18,7 @@ import type { ServiceTransition, TabID } from '@/types'
import CamoufoxBanner from '@/components/CamoufoxBanner.vue'
import UiDisclosure from '@/components/UiDisclosure.vue'
import LogsPanel from '@/components/LogsPanel.vue'
+import PageBoundary from '@/components/PageBoundary.vue'
import ThemeToggle from '@/components/ThemeToggle.vue'
import UiIcon from '@/components/UiIcon.vue'
import { useClampToggle } from '@/clamp'
@@ -74,6 +75,19 @@ watch(
},
)
+// panelNames 是各页面组件的名称,KeepAlive 按名称缓存页面,页面出错时按名称移出缓存
+const panelNames: Record = {
+ logs: 'LogsPanel',
+ accounts: 'AccountsPanel',
+ access: 'AccessPanel',
+ models: 'ModelsTable',
+ requests: 'RequestsPanel',
+ usage: 'UsagePanel',
+ settings: 'SettingsPanel',
+ version: 'VersionPanel',
+}
+const cachedPanels = Object.values(panelNames).join(',')
+
// openTab 切换页面,API 试用进入独立的试用页
function openTab(tab: TabID): void {
if (tab === 'playground') void router.push('/prompts/new_chat')
@@ -145,6 +159,7 @@ const {
visibleAccounts,
models,
catalogModels,
+ callableCatalog,
cooldowns,
requests,
config,
@@ -496,77 +511,88 @@ onMounted(revealCurrentTab)
{{ item.value ? `${item.key}=${item.value}` : item.key }} · {{ logText(item.reason) }}
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
{{ t('app.panelCrashed') }}
+
+ {{ pageError.message }}
+
+
+
+
+
+
+
+
+
+
+
+
+
{
{{ error }}
@@ -268,7 +286,7 @@ function addVocabulary(): void {
/>
-
+
{{ t('pg.functionCalling') }}
@@ -278,21 +296,21 @@ function addVocabulary(): void {
ms-button
class="edit-button ms-button-borderless"
:aria-label="t('pg.editFunctions')"
- :aria-disabled="!settings.functionCalling || locked"
- @click="settings.functionCalling && !locked && (functionsOpen = true)"
+ :aria-disabled="!settings.functionCalling || toolsLocked"
+ @click="settings.functionCalling && !toolsLocked && (functionsOpen = true)"
>
{{ t('pg.edit') }}
-
+
{{ t('pg.googleSearch') }}
@@ -318,7 +336,7 @@ function addVocabulary(): void {
@@ -326,6 +344,19 @@ function addVocabulary(): void {
+
+
{{ t('pg.voice') }}
+
+
{{ t('pg.targetLanguage') }}
+import type { IconName } from '@/playground/ui/icons'
+import UiIcon from '@/playground/ui/UiIcon.vue'
+import type { LiveSource } from './live'
+
+defineProps<{
+ buttons: readonly { source: LiveSource; icon: IconName; label: string }[]
+ sources: readonly LiveSource[]
+ below?: boolean
+ tip: (source: LiveSource) => string
+ disabled: (source: LiveSource) => boolean
+}>()
+const emit = defineEmits<{ select: [source: LiveSource, event: MouseEvent] }>()
+
+
+
+
+
+
+
diff --git a/web/src/playground/media/LiveSystemInstructions.vue b/web/src/playground/media/LiveSystemInstructions.vue
index f8b3bd23..da30b069 100644
--- a/web/src/playground/media/LiveSystemInstructions.vue
+++ b/web/src/playground/media/LiveSystemInstructions.vue
@@ -8,8 +8,9 @@ import { useInstructionPresets } from '@/playground/session'
const open = defineModel('open', { required: true })
const text = defineModel('text', { required: true })
-// locked 表示会话进行中,指令只读
-const props = defineProps<{ locked: boolean }>()
+// locked 表示会话进行中,指令只读;updatable 表示进行中的会话可以更新指令,面板显示更新按钮
+const props = defineProps<{ locked: boolean; updatable?: boolean }>()
+const emit = defineEmits<{ update: [] }>()
const { t } = useI18n()
// lockedTip 是会话进行中编辑区的官网提示
const lockedTip = computed(() => (props.locked ? t('pg.liveSystemLocked') : ''))
@@ -74,6 +75,11 @@ const { presets, selected, title, saved, saveError, currentPreset, remember, cho
:aria-label="t('pg.systemInstructions')"
@input="remember"
>
+
+
+ {{ t('pg.liveUpdateSession') }}
+
+
@@ -106,6 +112,11 @@ const { presets, selected, title, saved, saveError, currentPreset, remember, cho
min-height: 200px;
}
+.update-row {
+ display: flex;
+ justify-content: flex-end;
+}
+
.saving-status {
color: var(--color-v3-text-var);
font-size: 14px;
diff --git a/web/src/playground/media/LiveVoiceSelect.vue b/web/src/playground/media/LiveVoiceSelect.vue
index 7da1d5b4..4514e661 100644
--- a/web/src/playground/media/LiveVoiceSelect.vue
+++ b/web/src/playground/media/LiveVoiceSelect.vue
@@ -16,10 +16,20 @@ import { useSamplePlayer } from './sample'
import { voiceTraits } from './speech-voices'
const model = defineModel
({ required: true })
-const props = defineProps<{ voices: readonly VoiceDetail[]; disabled?: boolean }>()
+// none 为真时列表首项为“无”,对应空字符串
+const props = defineProps<{ voices: readonly VoiceDetail[]; disabled?: boolean; none?: boolean }>()
const { t } = useI18n()
const { playingSample, toggleSample, stopSample } = useSamplePlayer()
+// noneValue 是“无”选项在选择框中的值,选项值不能是空字符串
+const noneValue = '__none__'
+const selected = computed({
+ get: () => model.value || (props.none ? noneValue : ''),
+ set: (value: string) => {
+ model.value = value === noneValue ? '' : value
+ },
+})
+
// options 是带官网说明的音色:描述与音高
const options = computed(() =>
props.voices.map((voice) => ({
@@ -35,19 +45,24 @@ const primed = ref(false)
-
+
- {{ model }}
+ {{ model || t('pg.none') }}
+
+
+ {{ t('pg.none') }}
+
+
())
}
.empty-state {
- --count: 3;
--empty-duration: 10s;
--fill: var(--color-v3-hover);
--halo: light-dark(0.9, 1);
diff --git a/web/src/playground/media/MusicPage.vue b/web/src/playground/media/MusicPage.vue
index b248038a..24c84a97 100644
--- a/web/src/playground/media/MusicPage.vue
+++ b/web/src/playground/media/MusicPage.vue
@@ -1,5 +1,5 @@
@@ -68,7 +69,7 @@ onUnmounted(() => music.stop())
:placeholder="t('pg.realtimePromptPlaceholder')"
:aria-label="t('pg.realtimePrompt')"
@input="music.promptsChanged()"
- @keydown.enter.prevent="toggle"
+ @keydown.enter.prevent="!$event.isComposing && toggle()"
/>
-import { computed, nextTick, onUnmounted, ref, watch } from 'vue'
+import { computed, nextTick, onDeactivated, onUnmounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useConsole } from '@/console'
import { useI18n } from '@/i18n'
@@ -122,6 +122,11 @@ watch(
},
{ immediate: true },
)
+onDeactivated(() => {
+ createOpen.value = false
+ stopSample()
+ speech.stopPreview()
+})
onUnmounted(() => {
stopSample()
speech.stopPreview()
@@ -146,7 +151,7 @@ onUnmounted(() => {
-
+
diff --git a/web/src/playground/media/SpeechSettings.vue b/web/src/playground/media/SpeechSettings.vue
index 1f270cbb..483f8d86 100644
--- a/web/src/playground/media/SpeechSettings.vue
+++ b/web/src/playground/media/SpeechSettings.vue
@@ -145,7 +145,9 @@ function saveAlias(index: number, event: Event): void {
:value="speech.speakerName(index)"
:aria-label="t('pg.speakerName')"
@blur="saveAlias(index, $event)"
- @keydown.enter.prevent="($event.target as HTMLInputElement).blur()"
+ @keydown.enter.prevent="
+ !$event.isComposing && ($event.target as HTMLInputElement).blur()
+ "
@keydown.escape.prevent="editing = -1"
/>
-import { computed, onUnmounted, ref, watch } from 'vue'
+import { ref } from 'vue'
import { useI18n } from '@/i18n'
import UiIcon from '@/playground/ui/UiIcon.vue'
import MediaViewDialog from './MediaViewDialog.vue'
-import { failureText } from '../request'
-import { downloadMedia } from './api'
-// path 是服务端视频结果的下载路径,src 是已有的视频地址,aspectRatio 是视频加载前占位框的宽高比
-const props = defineProps<{ path?: string; src?: string; aspectRatio?: string }>()
-const { t, logText } = useI18n()
+// src 是视频地址
+const props = defineProps<{ src: string }>()
+const { t } = useI18n()
const element = ref()
-const downloaded = ref('')
-const error = ref('')
const playing = ref(false)
const largeView = ref(false)
// portrait 为视频是否竖屏,加载后按视频实际宽高确定
-const portrait = ref(props.aspectRatio === '9:16')
-// source 是播放的视频地址
-const source = computed(() => props.src ?? downloaded.value)
-
-watch(
- () => props.path,
- async (path, _previous, onCleanup) => {
- if (downloaded.value) URL.revokeObjectURL(downloaded.value)
- downloaded.value = ''
- error.value = ''
- if (!path) return
- const controller = new AbortController()
- onCleanup(() => controller.abort())
- try {
- const url = URL.createObjectURL(await downloadMedia(path, controller.signal))
- if (controller.signal.aborted) {
- URL.revokeObjectURL(url)
- return
- }
- downloaded.value = url
- } catch (reason) {
- if (controller.signal.aborted) return
- error.value = failureText(reason, t('pg.videoDownloadUnreachable'))
- }
- },
- { immediate: true },
-)
-onUnmounted(() => {
- if (downloaded.value) URL.revokeObjectURL(downloaded.value)
-})
+const portrait = ref(false)
// toggle 播放或暂停
function toggle(): void {
@@ -62,69 +29,64 @@ function openLargeView(): void {
// save 下载视频文件
function save(): void {
const link = document.createElement('a')
- link.href = source.value
- link.download = props.path ? `video-${props.path.split('/').at(-2)}.mp4` : 'video.mp4'
+ link.href = props.src
+ link.download = 'video.mp4'
link.click()
}
-
{{ logText(error) }}
-
-
-
-
@@ -143,11 +105,11 @@ function save(): void {
max-width: 300px;
}
-.sixteen-by-nine :is(.video, .video-placeholder) {
+.sixteen-by-nine .video {
aspect-ratio: 16 / 9;
}
-.nine-by-sixteen :is(.video, .video-placeholder) {
+.nine-by-sixteen .video {
aspect-ratio: 9 / 16;
}
@@ -158,16 +120,8 @@ function save(): void {
border-radius: 8px;
}
-.video-container.pending {
- background-color: var(--color-v3-button-container);
-}
-
-.video,
-.video-placeholder {
- width: 100%;
-}
-
.video {
+ width: 100%;
transition: scale 0.2s ease-in-out;
}
@@ -175,17 +129,6 @@ function save(): void {
scale: 1.05;
}
-.video-placeholder {
- animation: moving-gradient 1.7s linear infinite forwards;
- background: linear-gradient(
- 290deg,
- var(--color-loading-background) 40%,
- var(--color-loading-background-contrast) 50%,
- var(--color-loading-background) 60%
- );
- background-size: 800px;
-}
-
.bottom-controls-container {
position: absolute;
right: 0;
@@ -206,11 +149,4 @@ function save(): void {
background: transparent;
color: #fff;
}
-
-.video-error {
- margin: 0;
- color: var(--color-error);
- font-size: 14px;
- line-height: 21px;
-}
diff --git a/web/src/playground/media/VoiceDesignView.vue b/web/src/playground/media/VoiceDesignView.vue
new file mode 100644
index 00000000..9205a269
--- /dev/null
+++ b/web/src/playground/media/VoiceDesignView.vue
@@ -0,0 +1,809 @@
+
+
+
+
+
+
+
+
+
+ {{ t('pg.voiceNameMissing') }}
+
+
+
{{ t('pg.describeVoice') }}
+
{{ t('pg.describeVoiceDetail') }}
+
+
+
+
+ {{ t('pg.remixingBase') }} {{ baseName }}
+
+
+
+
+
+
+
+
+ {{ t('pg.remixVoice') }}
+
+
+
+
+
+
+
+
+ {{ example }}
+
+
+
+
+
+
+
+
+
+
+
+ {{ improving ? t('pg.improvingPrompt') : t('pg.improvePrompt') }}
+
+
+
+ {{
+ generating
+ ? t('pg.generatingVoice')
+ : takes.length
+ ? t('pg.regenerateVoice')
+ : t('pg.generateVoice')
+ }}
+
+
+
+
+
+
+
{{ t('pg.generatingTakes') }}
+
+
+
+
+
{{ t('pg.takesPlaceholder') }}
+
+
+ {{ t('pg.pickFavorite') }}
+
+
+
+
+
+
+
+ {{ take.voice.display_name }}
+
+ {{ playingSample === take.sample ? t('pg.playingTake') : t('pg.takeReady') }}
+
+
+
+
+
+
+
+
+
+
+ {{ t('pg.continue') }}
+
+
+
+
+
+
+
+
+
+
diff --git a/web/src/playground/media/VoicePanel.vue b/web/src/playground/media/VoicePanel.vue
index e036eda3..50a2fac1 100644
--- a/web/src/playground/media/VoicePanel.vue
+++ b/web/src/playground/media/VoicePanel.vue
@@ -28,9 +28,7 @@ const { state, voices, daikon, styles } = speech
const { playingSample, loadingSample, toggleSample, stopSample } = useSamplePlayer()
const current = computed(() => state.speakers[props.speaker]!)
const currentDetail = computed(() => speech.voiceDetail(current.value.voice))
-const { customVoices, customVoice, voiceSample, deleteVoice } = useCustomVoices()
-// customSamples 是已读取的自定义声音试听地址
-const customSamples = ref
>({})
+const { customVoices, samples, customVoice, voiceSample, deleteVoice } = useCustomVoices()
// FilterKey 是音色筛选项
type FilterKey = 'locale' | 'gender' | 'pitch' | 'trait' | 'use_case'
@@ -145,8 +143,7 @@ const customShown = computed(() => {
// playCustom 播放自定义声音的试听音频
async function playCustom(id: string): Promise {
- customSamples.value[id] ??= await voiceSample(id)
- await toggleSample(customSamples.value[id]!)
+ await toggleSample(await voiceSample(id))
}
// removeCustom 删除自定义声音,正在使用它的说话人都换回默认音色
@@ -253,9 +250,7 @@ watch(open, (value) => {
{
>
{
{
>
+import type { OrbState } from 'thinking-orbs/engine'
+import { useI18n } from '@/i18n'
+import ThinkingOrb from '@/playground/ui/ThinkingOrb.vue'
+import UiIcon from '@/playground/ui/UiIcon.vue'
+import { copyToClipboard } from '../clipboard'
+
+// VoiceReadyView 是声音创建完成的界面:名称、说明与使用、复制 ID、再创建一个声音三个操作
+withDefaults(
+ defineProps<{
+ name: string
+ voiceId: string
+ subtitle?: string
+ orb?: OrbState
+ speed?: number
+ createAnother?: boolean
+ }>(),
+ { subtitle: '', orb: 'breathing', speed: 1, createAnother: false },
+)
+defineEmits<{ use: []; createAnother: [] }>()
+const { t } = useI18n()
+
+
+
+
+
+
{{ t('pg.voiceReady').replace('{name}', name) }}
+
{{ subtitle || t('pg.voiceReadyDetail') }}
+
+
+
+ {{ t('pg.useVoice') }}
+
+
+
+ {{ t('pg.copyVoiceID') }}
+
+
+ {{ t('pg.createAnotherVoice') }}
+
+
+
+
+
+
diff --git a/web/src/playground/media/VoiceReplicaView.vue b/web/src/playground/media/VoiceReplicaView.vue
new file mode 100644
index 00000000..6472a18f
--- /dev/null
+++ b/web/src/playground/media/VoiceReplicaView.vue
@@ -0,0 +1,848 @@
+
+
+
+
+
+
+
+
+
+
+
+ {{ t('pg.replicaSampleTitle') }}
+ {{ t('pg.replicaSampleDetail') }}
+
+
+
{{ t('pg.replicaScriptCaption') }}
+
{{ t('pg.replicaScript') }}
+
+
+
+ {{
+ t('pg.recordingTimed').replace('{time}', clock(elapsed))
+ }}
+ {{ t('pg.stopRecording') }}
+
+
+
+
+
+
+ {{ t('pg.recordedSample') }}
+ {{ clock(sample.seconds) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ t('pg.recordVoice') }}
+
+
+
+
+ {{ micText }}
+
+
+
+
+
+ {{ t('pg.replicaVerifyTitle') }}
+ {{ t('pg.replicaVerifyDetail') }}
+
+
{{ t('pg.replicaConsent') }}
+
+
+
+ {{
+ t('pg.recordingTime').replace('{time}', clock(elapsed))
+ }}
+ {{ t('pg.stopRecording') }}
+
+
+
+
+
+ {{ t('pg.verificationRecorded') }}
+ {{ clock(consent.seconds) }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ t('pg.recordVerification') }}
+
+
+
+
+ {{ micText }}
+
+
+
+
+
+
+ {{ t('pg.startOver') }}
+
+
+ {{ replicating ? t('pg.replicatingVoice') : t('pg.replicateVoice') }}
+
+
+
+
+
+
+
+
+
+
+
+ “{{ previewLine }}”
+
+
+
+
+
+
+
+
{{ status }}
+
+
+
+
+
+
+ {{ t('pg.replicaChecklistSample') }}
+
+
+
+
+
+
+ {{ t('pg.replicaChecklistVerification') }}
+
+
+
+
+
+
+
+
diff --git a/web/src/playground/media/api.ts b/web/src/playground/media/api.ts
index 51748ada..2bfe4dcf 100644
--- a/web/src/playground/media/api.ts
+++ b/web/src/playground/media/api.ts
@@ -19,15 +19,14 @@ interface GenerateResponse {
}
// headers 返回带本服务 API key 的请求头
-function headers(json = true): Headers {
- const result = new Headers()
- if (json) result.set('Content-Type', 'application/json')
+function headers(): Headers {
+ const result = new Headers({ 'Content-Type': 'application/json' })
const key = apiKey()
if (key !== '') result.set('x-goog-api-key', key)
return result
}
-// post 以 JSON 调用本服务公开接口,非 2xx 时抛出上游说明
+// post 以 JSON 调用本服务公开接口,非 2xx 或保活 200 返回错误体时抛出上游说明
async function post(path: string, body: unknown, signal: AbortSignal): Promise {
const response = await fetch(path, {
method: 'POST',
@@ -36,7 +35,9 @@ async function post(path: string, body: unknown, signal: AbortSignal): Promis
signal,
})
if (!response.ok) throw new Error(await errorMessage(response))
- return (await response.json()) as T
+ const result = (await response.json()) as T & { error?: { message?: string } }
+ if (result.error) throw new Error(result.error.message)
+ return result
}
// generateContent 调用 generateContent
@@ -82,13 +83,6 @@ export async function predictImages(
return images
}
-// downloadMedia 下载本服务返回的媒体地址
-export async function downloadMedia(url: string, signal?: AbortSignal): Promise {
- const response = await fetch(url, { headers: headers(false), signal: signal ?? null })
- if (!response.ok) throw new Error(await errorMessage(response))
- return response.blob()
-}
-
// readImage 把图片文件读为内联图片
export async function readImage(file: Blob): Promise {
return {
diff --git a/web/src/playground/media/live.ts b/web/src/playground/media/live.ts
index dc515600..121c03c1 100644
--- a/web/src/playground/media/live.ts
+++ b/web/src/playground/media/live.ts
@@ -1,8 +1,8 @@
-import { computed, reactive } from 'vue'
+import { computed, reactive, watch } from 'vue'
import { jsonBody } from '@/api'
import { useConsole } from '@/console'
import { keepPage } from '@/desktop'
-import { useI18n } from '@/i18n'
+import { useI18n, type TranslationKey } from '@/i18n'
import { readPreference, writePreference } from '@/preference'
import type { Model, ThinkingLevel } from '@/types'
import { Capability, defaultChatModel, hasCode } from '../catalog'
@@ -33,6 +33,7 @@ export interface LiveSettings {
voice: string
mediaResolution: 'low' | 'medium'
thinkingLevel: ThinkingLevel | ''
+ proactiveVideo: boolean
maxContext: number
targetContext: number
functionCalling: boolean
@@ -156,14 +157,14 @@ const defaultTargetContext = 52428
// defaultSettings 返回模型的默认运行设置
function defaultSettings(model: Model | undefined): LiveSettings {
- const voices = model?.voice_details?.map((voice) => voice.name) ?? []
return {
systemInstruction: '',
- voice: voices.includes('Zephyr') ? 'Zephyr' : (voices[0] ?? 'Zephyr'),
+ voice: model?.default_voice ?? '',
mediaResolution: 'medium',
thinkingLevel: model?.capabilities?.thinking_level
? (model.default_thinking_level ?? 'MINIMAL')
: '',
+ proactiveVideo: false,
maxContext: defaultMaxContext,
targetContext: defaultTargetContext,
functionCalling: false,
@@ -233,6 +234,18 @@ const currentModel = computed(() =>
)
const variant = computed(() => liveVariantOf(currentModel.value))
+// canUpdate 返回进行中的对话会话能否在会话中更新,要求模型目录带有对应的能力码
+function canUpdate(code: number) {
+ return computed(
+ () =>
+ state.status === 'live' &&
+ variant.value === 'conversation' &&
+ hasCode(currentModel.value, code),
+ )
+}
+const canUpdateInstructions = canUpdate(Capability.UpdateInstructions)
+const canUpdateTools = canUpdate(Capability.UpdateTools)
+
// selectModel 切换模型并恢复该模型的默认运行设置
function selectModel(id: string): void {
disconnect()
@@ -313,11 +326,48 @@ function clearTranscripts(): void {
outputOpen = false
}
-// send 发送一帧客户端消息
-function send(frame: Record): void {
- if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(frame))
+// send 发送一帧客户端消息,连接已打开时返回 true
+function send(frame: Record): boolean {
+ if (socket?.readyState !== WebSocket.OPEN) return false
+ socket.send(JSON.stringify(frame))
+ return true
+}
+
+// notifyUpdate 显示会话中更新的结果
+function notifyUpdate(ok: boolean, done: TranslationKey, failed: TranslationKey): void {
+ useConsole().showNotice(useI18n().t(ok ? done : failed), ok ? 'success' : 'error')
+}
+
+// updateInstructions 把运行设置中的系统指令更新到进行中的会话,成功时返回 true
+function updateInstructions(): boolean {
+ const ok = send({ type: 'context_update', system_instruction: state.settings.systemInstruction })
+ notifyUpdate(ok, 'pg.liveInstructionsUpdated', 'pg.liveInstructionsUpdateFailed')
+ return ok
}
+// toolsUpdate 返回运行设置中的工具,会话中变化时整体更新给模型
+function toolsUpdate(): { tools: unknown; google_search: boolean } {
+ const settings = state.settings
+ return {
+ tools: settings.functionCalling ? JSON.parse(settings.functionDeclarations || '[]') : [],
+ google_search: settings.googleSearch,
+ }
+}
+
+// sentTools 是会话最近一次发给上游的工具设置
+let sentTools = ''
+
+// 进行中的会话修改函数声明与 Google 搜索后,把工具整体更新给模型
+watch(
+ () => (canUpdateTools.value ? JSON.stringify(toolsUpdate()) : sentTools),
+ (key) => {
+ if (key === sentTools) return
+ sentTools = key
+ const ok = send({ type: 'context_update', ...(JSON.parse(key) as object) })
+ notifyUpdate(ok, 'pg.liveToolsUpdated', 'pg.liveToolsUpdateFailed')
+ },
+)
+
// setupFrame 按运行设置生成 /v1/live 的 setup 帧
function setupFrame(): Record {
const settings = state.settings
@@ -330,6 +380,7 @@ function setupFrame(): Record {
target_language_code: settings.targetLanguage,
echo_target_language: settings.echoTargetLanguage,
}
+ if (settings.voice) frame.voice = settings.voice
} else if (variant.value === 'transcription') {
frame.input_modalities = ['audio']
frame.output_modalities = ['text']
@@ -342,9 +393,10 @@ function setupFrame(): Record {
} else {
frame.input_modalities = ['text', 'audio', 'image']
frame.output_modalities = ['audio']
- frame.voice = settings.voice
+ if (settings.voice) frame.voice = settings.voice
frame.media_resolution = settings.mediaResolution
if (settings.thinkingLevel) frame.thinking_level = settings.thinkingLevel.toLowerCase()
+ if (settings.proactiveVideo) frame.proactive_video = true
frame.context_window_compression = {
trigger_tokens: settings.maxContext,
target_tokens: settings.targetContext,
@@ -546,6 +598,7 @@ function connect(): Promise {
state.error = ''
state.status = 'connecting'
const frame = setupFrame()
+ sentTools = JSON.stringify(toolsUpdate())
ready = new Promise((resolve) => {
settleReady = resolve
const current = openLiveSocket()
@@ -767,7 +820,8 @@ async function toggleSource(source: LiveSource): Promise {
hasCode(currentModel.value, Capability.LiveMicrophone)
) {
const mic = await openSource('mic')
- if (mic) await startAudio(mic, 'mic')
+ if (mic && epoch !== sessionEpoch) mic.getTracks().forEach((track) => track.stop())
+ else if (mic) await startAudio(mic, 'mic')
}
}
} catch (error) {
@@ -781,6 +835,9 @@ export function useLive() {
state,
currentModel,
variant,
+ canUpdateInstructions,
+ canUpdateTools,
+ updateInstructions,
selectModel,
resetSettings,
sendText,
diff --git a/web/src/playground/media/realtime-music.ts b/web/src/playground/media/realtime-music.ts
index b95b7f95..0750a517 100644
--- a/web/src/playground/media/realtime-music.ts
+++ b/web/src/playground/media/realtime-music.ts
@@ -216,6 +216,8 @@ async function pause(): Promise {
// stop 停止播放并关闭会话
function stop(): void {
+ window.clearTimeout(promptTimer)
+ window.clearTimeout(configTimer)
send({ type: 'playback', playback_control: 'stop' })
send({ type: 'close' })
socket?.close()
diff --git a/web/src/playground/media/voice-recorder.ts b/web/src/playground/media/voice-recorder.ts
new file mode 100644
index 00000000..67eb9908
--- /dev/null
+++ b/web/src/playground/media/voice-recorder.ts
@@ -0,0 +1,65 @@
+import { base64Bytes, bytesToBase64, pcmToWav } from '../bytes'
+import { startPcmCapture } from './pcm-capture'
+
+// RecordedAudio 是一段录好的音频:16 kHz 单声道 16 位 WAV 的 Base64、可直接播放的地址与整秒时长(至少 1 秒)
+export interface RecordedAudio {
+ data: string
+ url: string
+ seconds: number
+}
+
+// Recorder 是一路正在进行的录音,stop 结束录音并返回录音
+export interface Recorder {
+ stop(): Promise
+}
+
+// MicrophoneProblem 是麦克风不可用的原因:没有设备、浏览器未授权、其他原因
+export type MicrophoneProblem = 'missing' | 'denied' | 'failed'
+
+// MicrophoneError 是录音无法开始时抛出的错误
+export class MicrophoneError extends Error {
+ constructor(readonly problem: MicrophoneProblem) {
+ super(problem)
+ }
+}
+
+const rate = 16000
+
+// startRecording 请求麦克风并开始录音
+export async function startRecording(): Promise {
+ if (!navigator.mediaDevices?.getUserMedia) throw new MicrophoneError('missing')
+ let stream: MediaStream
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: true })
+ } catch (error) {
+ const name = error instanceof Error ? error.name : ''
+ if (name === 'NotFoundError' || name === 'DevicesNotFoundError')
+ throw new MicrophoneError('missing')
+ if (['NotAllowedError', 'PermissionDeniedError', 'SecurityError'].includes(name))
+ throw new MicrophoneError('denied')
+ throw new MicrophoneError('failed')
+ }
+ const chunks: Uint8Array[] = []
+ const release = () => stream.getTracks().forEach((track) => track.stop())
+ let capture
+ try {
+ capture = await startPcmCapture(stream, (chunk) => chunks.push(base64Bytes(chunk)))
+ } catch {
+ release()
+ throw new MicrophoneError('failed')
+ }
+ return {
+ async stop() {
+ capture.stop()
+ release()
+ const wav = pcmToWav(chunks, rate)
+ const bytes = new Uint8Array(await wav.arrayBuffer())
+ if (bytes.length <= 44) throw new MicrophoneError('failed')
+ return {
+ data: bytesToBase64(bytes),
+ url: URL.createObjectURL(wav),
+ seconds: Math.max(1, Math.round((bytes.length - 44) / (rate * 2))),
+ }
+ },
+ }
+}
diff --git a/web/src/playground/media/voices.ts b/web/src/playground/media/voices.ts
index 10d1c5aa..4da94e4c 100644
--- a/web/src/playground/media/voices.ts
+++ b/web/src/playground/media/voices.ts
@@ -1,7 +1,7 @@
import { ref } from 'vue'
import { apiKey, errorMessage } from '../request'
-// CustomVoice 是本服务 /v1beta/voices 保存的一个自定义声音:描述、生成时使用的预置音色与可选的试听音频
+// CustomVoice 是本服务 /v1beta/voices 保存的一个自定义声音:描述(prompted)或由录音得出的描述(replicated)、生成时使用的预置音色与可选的试听音频
export interface CustomVoice {
id: string
type: string
@@ -13,8 +13,8 @@ export interface CustomVoice {
// customVoices 是已保存的自定义声音,最新的在前
const customVoices = ref([])
-// samples 按声音 ID 缓存试听音频的 data 地址
-const samples = new Map()
+// samples 是声音 ID 到试听音频 data 地址的缓存,创建与首次播放时写入,删除声音时清除
+const samples = ref>({})
// headers 返回带本服务 API key 的请求头
function headers(): Headers {
@@ -38,44 +38,91 @@ function sampleURL(voice: CustomVoice): string {
// loadVoices 读取已保存的自定义声音
async function loadVoices(): Promise {
- const result = await request<{ voices?: CustomVoice[] }>('?type=prompted&page_size=1000')
+ const result = await request<{ voices?: CustomVoice[] }>(
+ '?type=prompted&type=replicated&page_size=1000',
+ )
customVoices.value = result.voices ?? []
}
-// createVoice 以名称与描述创建一个自定义声音,返回带试听音频的声音
+// addVoice 把新创建的声音写入列表与试听缓存
+function addVoice(voice: CustomVoice): CustomVoice {
+ samples.value[voice.id] = sampleURL(voice)
+ customVoices.value = [voice, ...customVoices.value.filter((item) => item.id !== voice.id)]
+ return voice
+}
+
+// createVoice 以名称与描述创建一个自定义声音,baseVoice 非空时在该预置音色或自定义声音上按描述修改,返回带试听音频的声音
async function createVoice(
displayName: string,
input: string,
model: string,
signal: AbortSignal,
+ baseVoice = '',
): Promise {
- const voice = await request('', {
- method: 'POST',
- body: JSON.stringify({
- store: true,
- voice: { type: 'prompted', display_name: displayName, model, prompted: { input } },
+ return addVoice(
+ await request('', {
+ method: 'POST',
+ body: JSON.stringify({
+ store: true,
+ voice: {
+ type: 'prompted',
+ display_name: displayName,
+ model,
+ base_voice: baseVoice || undefined,
+ prompted: { input },
+ },
+ }),
+ signal,
}),
- signal,
- })
- samples.set(voice.id, sampleURL(voice))
- customVoices.value = [voice, ...customVoices.value.filter((item) => item.id !== voice.id)]
- return voice
+ )
+}
+
+// replicateVoice 以样本录音与确认录音(16 位 PCM WAV 的 Base64)创建一个复刻声音,返回带试听音频的声音
+async function replicateVoice(
+ displayName: string,
+ model: string,
+ source: string,
+ consent: string,
+ signal: AbortSignal,
+): Promise {
+ const audio = (data: string) => ({ data, mime_type: 'audio/wav' })
+ return addVoice(
+ await request('', {
+ method: 'POST',
+ body: JSON.stringify({
+ voice: {
+ type: 'replicated',
+ display_name: displayName,
+ model,
+ replicated: { source_audio: audio(source), consent_audio: audio(consent) },
+ },
+ }),
+ signal,
+ }),
+ )
+}
+
+// improvePrompt 把声音描述改写得更具体
+async function improvePrompt(input: string): Promise {
+ return (
+ await request<{ input: string }>(':improvePrompt', {
+ method: 'POST',
+ body: JSON.stringify({ input }),
+ })
+ ).input
}
// deleteVoice 删除一个自定义声音
async function deleteVoice(id: string): Promise {
await request(`/${encodeURIComponent(id)}`, { method: 'DELETE' })
- samples.delete(id)
+ delete samples.value[id]
customVoices.value = customVoices.value.filter((voice) => voice.id !== id)
}
-// voiceSample 返回自定义声音试听音频的 data 地址,首次播放时读取
+// voiceSample 返回自定义声音试听音频的 data 地址,缓存中没有时读取
async function voiceSample(id: string): Promise {
- const cached = samples.get(id)
- if (cached) return cached
- const url = sampleURL(await request(`/${encodeURIComponent(id)}`))
- samples.set(id, url)
- return url
+ samples.value[id] ??= sampleURL(await request(`/${encodeURIComponent(id)}`))
+ return samples.value[id]!
}
// customVoice 返回 ID 对应的自定义声音
@@ -83,7 +130,17 @@ function customVoice(id: string): CustomVoice | undefined {
return customVoices.value.find((voice) => voice.id === id)
}
-// useCustomVoices 返回自定义声音列表与操作
+// useCustomVoices 返回自定义声音列表、试听地址缓存与操作
export function useCustomVoices() {
- return { customVoices, loadVoices, createVoice, deleteVoice, voiceSample, customVoice }
+ return {
+ customVoices,
+ samples,
+ loadVoices,
+ createVoice,
+ replicateVoice,
+ improvePrompt,
+ deleteVoice,
+ voiceSample,
+ customVoice,
+ }
}
diff --git a/web/src/playground/protocols.ts b/web/src/playground/protocols.ts
index 0e890315..a1d2067d 100644
--- a/web/src/playground/protocols.ts
+++ b/web/src/playground/protocols.ts
@@ -1074,6 +1074,17 @@ function interactionsDecoder(): Decoder {
let answerBytes = 0
let textStart = 0
let inText = false
+ let pendingCall:
+ | { name: string; id: string; args: Record; argsText: string }
+ | undefined
+ // flushCall 把流式累加完成的 function_call 步骤写出为单个片段,避免参数丢失或重复卡片
+ const flushCall = (update: StreamUpdate) => {
+ if (pendingCall === undefined) return
+ const args =
+ pendingCall.argsText !== '' ? parseArguments(pendingCall.argsText) : pendingCall.args
+ emit(update, { functionCall: { name: pendingCall.name, args, id: pendingCall.id } })
+ pendingCall = undefined
+ }
// emit 写入一个片段:待用的思考签名附到非思考片段,回答正文计入字节位置
const emit = (update: StreamUpdate, part: Part) => {
if (signature !== '' && !part.thought) {
@@ -1139,11 +1150,20 @@ function interactionsDecoder(): Decoder {
const update: StreamUpdate = { parts: [] }
switch (value.event_type) {
case 'step.start': {
+ flushCall(update)
const start = record(value.step)
kind = stringOf(start.type)
inText = false
- if (kind !== 'thought' && kind !== 'model_output')
+ if (kind === 'function_call') {
+ pendingCall = {
+ name: stringOf(start.name),
+ id: stringOf(start.id),
+ args: record(start.arguments),
+ argsText: typeof start.arguments === 'string' ? start.arguments : '',
+ }
+ } else if (kind !== 'thought' && kind !== 'model_output') {
for (const part of interactionToolParts(start)) emit(update, part)
+ }
break
}
case 'step.delta': {
@@ -1154,7 +1174,11 @@ function interactionsDecoder(): Decoder {
if (part) emit(update, part)
} else if (delta.type === 'text_annotation_delta')
cite(update, delta.annotations, textStart)
- else if (kind === 'model_output') {
+ else if (delta.type === 'arguments_delta' && pendingCall !== undefined) {
+ if (typeof delta.arguments === 'string') pendingCall.argsText += delta.arguments
+ else if (delta.arguments && typeof delta.arguments === 'object')
+ pendingCall.args = { ...pendingCall.args, ...record(delta.arguments) }
+ } else if (kind === 'model_output') {
if (delta.type === 'text' && !inText) textStart = answerBytes
inText = delta.type === 'text'
const part = interactionContentPart(delta, false)
@@ -1163,7 +1187,11 @@ function interactionsDecoder(): Decoder {
update.parts.push({ text: '', thoughtSignature: delta.signature })
break
}
+ case 'step.stop':
+ flushCall(update)
+ break
case 'interaction.completed':
+ flushCall(update)
finish(update, record(value.interaction))
break
case undefined:
diff --git a/web/src/playground/recording.ts b/web/src/playground/recording.ts
index e1ba9980..635100cc 100644
--- a/web/src/playground/recording.ts
+++ b/web/src/playground/recording.ts
@@ -1,7 +1,7 @@
import { onDeactivated, onUnmounted, ref } from 'vue'
import { useConsole } from '@/console'
import { useI18n } from '@/i18n'
-import { apiKey, failureText } from './request'
+import { apiKey, errorMessage, failureText } from './request'
import { audioInput } from './shell/preferences'
// useAudioRecording 管理麦克风录音与转写,录音结果交给组件处理
@@ -57,8 +57,9 @@ export function useAudioRecording(onAudio: (audio: Blob) => void | Promise
headers,
body: form,
})
+ if (!response.ok) throw new Error(await errorMessage(response))
const value = (await response.json()) as { text?: string; error?: { message?: string } }
- if (!response.ok) throw new Error(value.error?.message ?? response.statusText)
+ if (value.error?.message) throw new Error(value.error.message)
return value.text?.trim() ?? ''
} catch (error) {
showNotice(failureText(error, t('pg.transcribeUnreachable')), 'error')
diff --git a/web/src/playground/request.ts b/web/src/playground/request.ts
index 759c5037..ee407c78 100644
--- a/web/src/playground/request.ts
+++ b/web/src/playground/request.ts
@@ -309,12 +309,15 @@ export function apiKey(): string {
return (useConsole().config.value?.proxy_api_key ?? '').split(',')[0]!.trim()
}
-// errorMessage 读取 Gemini API 错误正文中的说明
+// errorMessage 读取 Gemini API 错误正文中的说明,Interactions 的错误正文是数组包装的
export async function errorMessage(response: Response): Promise {
const text = await response.text()
try {
- const value = JSON.parse(text) as { error?: { message?: string } }
- return value.error?.message ?? text
+ const parsed = JSON.parse(text) as
+ | { error?: { message?: string } }
+ | { error?: { message?: string } }[]
+ const value = Array.isArray(parsed) ? parsed[0] : parsed
+ return value?.error?.message ?? text
} catch {
return text || response.statusText
}
diff --git a/web/src/playground/run-keys.ts b/web/src/playground/run-keys.ts
index 644d4334..b4839f85 100644
--- a/web/src/playground/run-keys.ts
+++ b/web/src/playground/run-keys.ts
@@ -19,16 +19,16 @@ export function useRunTooltip(running: () => boolean): ComputedRef {
)
}
-// appends 与官网 _.cjd 一致:不在输入法组合中的 Alt 加 Enter 追加
+// appends 与官网 _.cjd 一致:不在输入法组合与连按中的 Alt 加 Enter 追加
export function appends(event: KeyboardEvent): boolean {
- return event.key === 'Enter' && event.altKey && !event.isComposing
+ return event.key === 'Enter' && event.altKey && !event.isComposing && !event.repeat
}
-// submits 与官网 _.uT 一致:手机上不带修饰键的 Enter 换行,输入法组合与追加不运行;Ctrl + Enter 模式下 Mac 用 ⌘、其他平台用 Ctrl 加 Enter 运行,Enter 模式下不带 Shift 与该修饰键的 Enter 运行
+// submits 与官网 _.uT 一致:手机上不带修饰键的 Enter 换行,输入法组合、连按与追加不运行;Ctrl + Enter 模式下 Mac 用 ⌘、其他平台用 Ctrl 加 Enter 运行,Enter 模式下不带 Shift 与该修饰键的 Enter 运行
export function submits(event: KeyboardEvent): boolean {
const plain =
event.key === 'Enter' && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
- if ((phone && plain) || event.isComposing || appends(event)) return false
+ if ((phone && plain) || event.isComposing || event.repeat || appends(event)) return false
const command = mac ? event.metaKey : event.ctrlKey
return submitKey.value === 'ctrl-enter'
? event.key === 'Enter' && command
diff --git a/web/src/playground/shell/CommandPalette.vue b/web/src/playground/shell/CommandPalette.vue
index 351077c8..6f67f614 100644
--- a/web/src/playground/shell/CommandPalette.vue
+++ b/web/src/playground/shell/CommandPalette.vue
@@ -253,7 +253,7 @@ function onKeydown(event: KeyboardEvent): void {
void nextTick(() =>
list.value?.querySelector('.result-item.selected')?.scrollIntoView({ block: 'nearest' }),
)
- } else if (event.key === 'Enter') {
+ } else if (event.key === 'Enter' && !event.isComposing) {
event.preventDefault()
if (mode.value === 'prompt' && chosen.value) void sendPrompt(chosen.value, query.value)
else items.value[Math.max(selected.value, 0)]?.run()
diff --git a/web/src/playground/shell/LeftNav.vue b/web/src/playground/shell/LeftNav.vue
index 5961c203..977aa0c5 100644
--- a/web/src/playground/shell/LeftNav.vue
+++ b/web/src/playground/shell/LeftNav.vue
@@ -168,10 +168,11 @@ function consoleTab(tab: string): RouteLocationRaw {
.nav-content.narrow {
position: fixed;
- top: 0;
+ top: var(--desktop-titlebar, 0px);
bottom: 0;
left: 0;
width: 220px;
+ height: auto;
padding: 0 8px;
background-color: var(--color-v3-surface-container);
transform: translate(-100%);
diff --git a/web/src/playground/shortcuts.ts b/web/src/playground/shortcuts.ts
index b0a7e9c0..d9a51438 100644
--- a/web/src/playground/shortcuts.ts
+++ b/web/src/playground/shortcuts.ts
@@ -20,7 +20,7 @@ export function useRunSettingsPanel(
// onKeydown 处理运行设置面板与主输入框的快捷键,对话框打开时不处理
function onKeydown(event: KeyboardEvent): void {
- if (event.defaultPrevented || document.querySelector('[role="dialog"]')) return
+ if (event.defaultPrevented || event.repeat || document.querySelector('[role="dialog"]')) return
if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === 's') {
event.preventDefault()
settingsOpen.value = !settingsOpen.value
diff --git a/web/src/playground/styles/run-settings.css b/web/src/playground/styles/run-settings.css
index 60dca629..6282fbdc 100644
--- a/web/src/playground/styles/run-settings.css
+++ b/web/src/playground/styles/run-settings.css
@@ -107,12 +107,3 @@
.ms-run-settings .settings-group-header + .ui-collapse > .toggle-row:first-child {
margin-top: 4px;
}
-
-.ms-run-settings .settings-note {
- margin: 8px 0 0;
- padding-top: 16px;
- border-top: 1px solid var(--color-v3-outline-var);
- color: var(--color-v3-text-var);
- font-size: 12px;
- line-height: 18px;
-}
diff --git a/web/src/playground/ui/ThinkingOrb.vue b/web/src/playground/ui/ThinkingOrb.vue
index b4f50ad9..684e1e74 100644
--- a/web/src/playground/ui/ThinkingOrb.vue
+++ b/web/src/playground/ui/ThinkingOrb.vue
@@ -4,12 +4,17 @@ import { onMounted, onUnmounted, ref, watch } from 'vue'
import { useTheme } from '@/theme'
// ThinkingOrb 是官网 thinking-orb 的点阵球动画
-const props = defineProps<{ state: OrbState }>()
+// speed 是动画速度的倍数,默认 1
+const props = withDefaults(defineProps<{ state: OrbState; speed?: number }>(), { speed: 1 })
// size 是点阵球的边长
const size = 64
const canvas = ref()
const { theme } = useTheme()
let stop: (() => void) | undefined
+// presetSpeed 是当前状态预设的动画速度
+let presetSpeed = 1
+// offset 抵消倍数变化前后的时间差,切换倍数时画面连续,单位秒
+let offset = 0
// start 按状态、尺寸与配色逐帧绘制,首帧在进入视口后的动画帧中绘制,离开视口或页面隐藏时暂停
function start(): void {
@@ -22,6 +27,7 @@ function start(): void {
element.width = Math.round(size * ratio)
element.height = Math.round(size * ratio)
const { mode, speed, opts } = resolvePreset(props.state, size)
+ presetSpeed = speed
const dark = theme.value === 'dark'
const paint = (time: number): void => {
context.setTransform(ratio, 0, 0, ratio, 0, 0)
@@ -36,7 +42,7 @@ function start(): void {
let running = false
let visible = true
const tick = (): void => {
- paint((performance.now() / 1000) * speed)
+ paint((performance.now() / 1000) * speed * props.speed + offset)
if (running) frame = requestAnimationFrame(tick)
}
const resume = (): void => {
@@ -68,6 +74,12 @@ function start(): void {
onMounted(start)
watch([() => props.state, theme], start)
+watch(
+ () => props.speed,
+ (next, previous) => {
+ offset += (performance.now() / 1000) * presetSpeed * (previous - next)
+ },
+)
onUnmounted(() => stop?.())
diff --git a/web/src/playground/ui/UiSlidingPanel.vue b/web/src/playground/ui/UiSlidingPanel.vue
index d095c080..377970c4 100644
--- a/web/src/playground/ui/UiSlidingPanel.vue
+++ b/web/src/playground/ui/UiSlidingPanel.vue
@@ -83,7 +83,7 @@ function focusInitial(event: Event): void {
.ms-panel {
position: fixed;
z-index: 901;
- top: 0;
+ top: var(--desktop-titlebar, 0px);
right: 0;
bottom: 0;
display: flex;
diff --git a/web/src/playground/ui/icons.ts b/web/src/playground/ui/icons.ts
index 2a69a035..f99d5f74 100644
--- a/web/src/playground/ui/icons.ts
+++ b/web/src/playground/ui/icons.ts
@@ -15,6 +15,7 @@ import symbol_attach_money from '@material-symbols/svg-300/outlined/attach_money
import symbol_audio_file from '@material-symbols/svg-300/outlined/audio_file.svg?raw'
import symbol_bar_chart from '@material-symbols/svg-300/outlined/bar_chart.svg?raw'
import symbol_cable from '@material-symbols/svg-300/outlined/cable.svg?raw'
+import symbol_casino from '@material-symbols/svg-300/outlined/casino.svg?raw'
import symbol_chat from '@material-symbols/svg-300/outlined/chat.svg?raw'
import symbol_chat_bubble from '@material-symbols/svg-300/outlined/chat_bubble.svg?raw'
import symbol_check from '@material-symbols/svg-300/outlined/check.svg?raw'
@@ -68,12 +69,14 @@ import symbol_movie_edit from '@material-symbols/svg-300/outlined/movie_edit.svg
import symbol_music_note from '@material-symbols/svg-300/outlined/music_note.svg?raw'
import symbol_network_intelligence_history from '@material-symbols/svg-300/outlined/network_intelligence_history.svg?raw'
import symbol_notifications from '@material-symbols/svg-300/outlined/notifications.svg?raw'
+import symbol_pause from '@material-symbols/svg-300/outlined/pause.svg?raw'
import symbol_pause_circle from '@material-symbols/svg-300/outlined/pause_circle.svg?raw'
import symbol_photo_camera from '@material-symbols/svg-300/outlined/photo_camera.svg?raw'
import symbol_play_arrow from '@material-symbols/svg-300/outlined/play_arrow.svg?raw'
import symbol_play_circle from '@material-symbols/svg-300/outlined/play_circle.svg?raw'
import symbol_podcasts from '@material-symbols/svg-300/outlined/podcasts.svg?raw'
import symbol_progress_activity from '@material-symbols/svg-300/outlined/progress_activity.svg?raw'
+import symbol_record_voice_over from '@material-symbols/svg-300/outlined/record_voice_over.svg?raw'
import symbol_refresh from '@material-symbols/svg-300/outlined/refresh.svg?raw'
import symbol_reset_settings from '@material-symbols/svg-300/outlined/reset_settings.svg?raw'
import symbol_rocket_launch from '@material-symbols/svg-300/outlined/rocket_launch.svg?raw'
@@ -82,6 +85,7 @@ import symbol_save from '@material-symbols/svg-300/outlined/save.svg?raw'
import symbol_search from '@material-symbols/svg-300/outlined/search.svg?raw'
import symbol_settings from '@material-symbols/svg-300/outlined/settings.svg?raw'
import symbol_share from '@material-symbols/svg-300/outlined/share.svg?raw'
+import symbol_shuffle from '@material-symbols/svg-300/outlined/shuffle.svg?raw'
import symbol_speed from '@material-symbols/svg-300/outlined/speed.svg?raw'
import symbol_sports_esports from '@material-symbols/svg-300/outlined/sports_esports.svg?raw'
import symbol_star from '@material-symbols/svg-300/outlined/star.svg?raw'
@@ -96,6 +100,7 @@ import symbol_toll from '@material-symbols/svg-300/outlined/toll.svg?raw'
import symbol_token from '@material-symbols/svg-300/outlined/token.svg?raw'
import symbol_tune from '@material-symbols/svg-300/outlined/tune.svg?raw'
import symbol_upload from '@material-symbols/svg-300/outlined/upload.svg?raw'
+import symbol_verified from '@material-symbols/svg-300/outlined/verified.svg?raw'
import symbol_video_camera_front from '@material-symbols/svg-300/outlined/video_camera_front.svg?raw'
import symbol_videocam from '@material-symbols/svg-300/outlined/videocam.svg?raw'
import symbol_voice_selection from '@material-symbols/svg-300/outlined/voice_selection.svg?raw'
@@ -245,6 +250,11 @@ export const icons = {
help: symbol_help,
lightbulb: symbol_lightbulb,
collapseContent: symbol_collapse_content,
+ casino: symbol_casino,
+ pause: symbol_pause,
+ recordVoiceOver: symbol_record_voice_over,
+ shuffle: symbol_shuffle,
+ verified: symbol_verified,
} as const
// IconName 是界面可用的图标语义名
diff --git a/web/src/quota.ts b/web/src/quota.ts
index 889f1cbb..84c983b8 100644
--- a/web/src/quota.ts
+++ b/web/src/quota.ts
@@ -1,6 +1,6 @@
import { apiVisible } from '@/apiModels'
import { splitReason } from '@/cooldowns'
-import type { Account, Cooldown, Model, ServiceConfig, UsagePair } from '@/types'
+import type { Account, Cooldown, ServiceConfig, UsagePair } from '@/types'
// QuotaStatus 是账户在一个模型上的额度状态:available 可以接收请求,cooling 短时冷却,exhausted 额度用尽,unavailable 账户本身不可用
export type QuotaStatus = 'available' | 'cooling' | 'exhausted' | 'unavailable'
@@ -16,23 +16,9 @@ export function usableAccount(account: Account): boolean {
return account.enabled && usableStates.has(account.state)
}
-// callableModels 返回账户目录中公开 API 提供、按账户权益能调用的模型:access_modes 为空时任何权益可用,含 3 时 Pro 与 Ultra 可用,含 4 时 Ultra 可用
-function callableModels(
- account: Account,
- catalog: Model[],
- config: ServiceConfig | null,
-): string[] {
- const modes = new Map(catalog.map((model) => [model.id, model.access_modes ?? []]))
- return account.models.filter((id) => {
- if (!apiVisible({ id }, config)) return false
- const access = modes.get(id) ?? []
- return (
- access.length === 0 ||
- (access.includes(3) &&
- (account.benefit_tier === 'Pro' || account.benefit_tier === 'Ultra')) ||
- (access.includes(4) && account.benefit_tier === 'Ultra')
- )
- })
+// callableModels 返回账户可以调用且公开 API 提供的模型:能否调用由后端按选号的同一判定给出,公开 API 是否提供由设置决定
+function callableModels(account: Account, config: ServiceConfig | null): string[] {
+ return account.callable_models.filter((id) => apiVisible({ id }, config))
}
// QuotaEntry 是一个账户在一个模型上的额度状态与决定它的冷却
@@ -88,7 +74,6 @@ function quotaEntry(account: Account, cooldown: Cooldown | undefined): QuotaEntr
export function poolModels(
accounts: Account[],
cooldowns: Cooldown[],
- catalog: Model[],
now: number,
config: ServiceConfig | null,
): Map {
@@ -96,7 +81,7 @@ export function poolModels(
const pool = new Map()
for (const account of accounts) {
const own = active.get(account.id)
- for (const id of callableModels(account, catalog, config)) {
+ for (const id of callableModels(account, config)) {
let model = pool.get(id)
if (model === undefined) {
model = {
@@ -154,14 +139,13 @@ export interface PoolAccount {
export function poolAccounts(
accounts: Account[],
cooldowns: Cooldown[],
- catalog: Model[],
now: number,
config: ServiceConfig | null,
): PoolAccount[] {
const active = activeCooldowns(cooldowns, now)
return accounts.map((account) => {
const own = active.get(account.id)
- const models = callableModels(account, catalog, config)
+ const models = callableModels(account, config)
const row: PoolAccount = {
account,
total: models.length,
diff --git a/web/src/style.css b/web/src/style.css
index 0a1bdec0..30bf1ef5 100644
--- a/web/src/style.css
+++ b/web/src/style.css
@@ -35,14 +35,10 @@
--text-xs--line-height: calc(1.125 / 0.8125);
--text-sm: 0.9375rem;
--text-sm--line-height: calc(1.375 / 0.9375);
- --radius-xs: 1px;
--radius-sm: 2px;
--radius-md: 3px;
--radius-lg: 4px;
--radius-xl: 6px;
- --radius-2xl: 6px;
- --radius-3xl: 8px;
- --radius-4xl: 8px;
}
@utility page-x {
@@ -102,14 +98,12 @@
--color-green-300: #15803d;
--color-green-400: #1a7f37;
--color-green-900: #22c55e;
- --color-yellow-100: #854d0e;
--color-yellow-300: #a16207;
--color-yellow-400: #b45309;
--color-amber-200: #92400e;
--color-amber-300: #b45309;
--color-amber-700: #d97706;
--color-amber-900: #f59e0b;
- --color-red-100: #991b1b;
--color-red-200: #b91c1c;
--color-red-300: #dc2626;
--color-red-400: #dc2626;
diff --git a/web/src/tooltip.ts b/web/src/tooltip.ts
index 492b9065..9baf979a 100644
--- a/web/src/tooltip.ts
+++ b/web/src/tooltip.ts
@@ -9,6 +9,40 @@ let timer = 0
let shown: HTMLElement | null = null
// pending 是等待显示提示的元素
let pending: HTMLElement | null = null
+// hovered 是当前指针悬停的带提示元素
+let hovered: HTMLElement | null = null
+// delegated 表示文档级委托监听器已注册
+let delegated = false
+
+// ensureDelegation 在文档上注册一次提示的悬停与聚焦委托监听器
+function ensureDelegation(): void {
+ if (delegated) return
+ delegated = true
+ document.addEventListener('pointerover', (event) => {
+ const target =
+ event.target instanceof Element ? event.target.closest('[data-tooltip]') : null
+ if (target === hovered) return
+ if (hovered !== null) hideTooltip()
+ hovered = target
+ if (target && target.dataset.tooltip) showTooltip(target)
+ })
+ document.addEventListener('pointerout', (event) => {
+ if (hovered === null) return
+ const related = event.relatedTarget
+ if (related instanceof Node && hovered.contains(related)) return
+ hovered = null
+ hideTooltip()
+ })
+ document.addEventListener('focusin', (event) => {
+ const target = event.target
+ if (target instanceof HTMLElement && target.dataset.tooltip) showTooltip(target)
+ })
+ document.addEventListener('focusout', (event) => {
+ const target = event.target
+ if (target === shown || target === pending) hideTooltip()
+ })
+ document.addEventListener('pointerdown', hideTooltip, true)
+}
// tooltipElement 返回全局共用的提示浮层
function tooltipElement(): HTMLDivElement {
@@ -64,18 +98,18 @@ function place(element: HTMLDivElement, rect: DOMRect, position: string, gap: nu
// showTooltip 在目标元素旁显示其 data-tooltip 文字,API 试用页用官网样式,管理端用站内样式
export function showTooltip(target: HTMLElement): void {
if (!target.dataset.tooltip) return
- if (
- target.dataset.tooltipOverflow !== undefined &&
- target.scrollWidth <= target.clientWidth &&
- target.scrollHeight <= target.clientHeight + 1
- )
- return
window.clearTimeout(timer)
pending = target
timer = window.setTimeout(() => {
pending = null
const text = target.dataset.tooltip
if (!text) return
+ if (
+ target.dataset.tooltipOverflow !== undefined &&
+ target.scrollWidth <= target.clientWidth &&
+ target.scrollHeight <= target.clientHeight + 1
+ )
+ return
const studio = document.documentElement.classList.contains('studio')
const element = tooltipElement()
element.className = studio ? 'ms-tooltip visible' : 'ui-tooltip visible'
@@ -90,26 +124,23 @@ export function showTooltip(target: HTMLElement): void {
}, 300)
}
-// hideTooltip 隐藏提示
+// hideTooltip 隐藏提示,提示没有显示时不修改浮层
function hideTooltip(): void {
window.clearTimeout(timer)
+ pending = null
+ if (shown === null) return
tip?.classList.remove('visible')
shown = null
- pending = null
}
// vTooltip 显示悬停与键盘聚焦提示,值为空时不显示
export const vTooltip: Directive = {
mounted(element, binding) {
+ ensureDelegation()
element.dataset.tooltip = binding.value ?? ''
if (binding.modifiers.overflow) element.dataset.tooltipOverflow = ''
const position = (['below', 'left', 'right'] as const).find((name) => binding.modifiers[name])
if (position) element.dataset.tooltipPosition = position
- element.addEventListener('pointerenter', () => showTooltip(element))
- element.addEventListener('pointerleave', hideTooltip)
- element.addEventListener('focus', () => showTooltip(element))
- element.addEventListener('blur', hideTooltip)
- element.addEventListener('pointerdown', hideTooltip)
},
updated(element, binding) {
if (binding.value === binding.oldValue) return
@@ -119,6 +150,7 @@ export const vTooltip: Directive
capability_options?: Record
voice_details?: VoiceDetail[]
+ // default_voice 是 Live 模型默认选中的音色,实时翻译模型默认不选
+ default_voice?: string
languages?: Language[]
access_modes?: number[]
paid?: boolean
@@ -387,6 +391,8 @@ export interface Model {
// agent_model 是 agent 默认使用的模型 ID
agent_model?: string
channels?: UpstreamChannel[]
+ // unavailable 是本服务调用不了模型的原因:只对付费 API key 开放,或上游没有提供任何方法;调用得了时没有
+ unavailable?: 'paid_api_key' | 'no_methods'
}
export type ThinkingLevel = 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'EXTRA_HIGH'
@@ -504,6 +510,7 @@ export interface ServiceConfig {
media_output: 'inline' | 'url'
media_base_url: string
build_chat_models: boolean
+ build_chat_protocol: 'auto' | 'agency' | 'legacy'
// hide_models 是逗号分隔、不在公开 API 中提供的目录模型 ID
hide_models: string
// generate_content_accounts 是逗号分隔、被迁移到任务接口的模型改走 GenerateContent 的账户 ID