opencode-agentrouter-auth 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,7 +2,15 @@
2
2
 
3
3
  [使用说明](<README.md>) · [优化设计与兼容边界](<docs/OPTIMIZATION.md>)
4
4
 
5
- 本页记录源码行为,当前版本为 **0.1.12**。npm 可用版本以官方 registry 查询为准;文档和源码更新不代表远程网关升级或模型验证成功。
5
+ 本页记录源码行为,当前版本为 **0.1.13**。npm 可用版本以官方 registry 查询为准;文档和源码更新不代表远程网关升级或模型验证成功。
6
+
7
+ ## 0.1.13 — 2026-12-04
8
+
9
+ - 完成 [Issue #23](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/issues/23) 与 [PR #24](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/pull/24)(合并提交 `2e5da55`):新增默认开启的**实际模型校验**([model-guard.mjs](<model-guard.mjs>)),比较 Gemini Native(`modelVersion`)、Responses(`model` / `response.model`)、Chat(`model`)与 Anthropic Messages(`model` / `message_start.message.model`)的协议模型元数据;明确错配时整条丢弃并复用同一份已处理请求。总请求次数可手动设置,最小 2、默认 3(包含首次请求),连续错配达到预算后返回 HTTP 400(`agentrouter_model_mismatch`,`retryable: false`)并停止;任意一次匹配即只返回该次回答。
10
+ - 在 AgentRouter 编辑页新增官方 `magpie.panels` 校验面板(`ui/model-guard.{html,js,css}`),开启后显示次数数字框、关闭时隐藏,保存 `modelGuardEnabled` / `maxModelAttempts`;采用 `button[type="button"]` 的 `click` 与 `Enter` 键保存(兼容 Magpie `sandbox="allow-scripts"` 与 `form-action 'none'` 沙箱策略)及官方主题变量 `--magpie-line` / `--magpie-red` / `--magpie-card`,不把数值放入仅支持布尔值的 `auth.options`。
11
+ - 开启校验时成功 JSON / SSE 完整暂存后交付,覆盖末尾模型字段、后续变化及错配后晚到错误;每次读取上限为 64 MiB / 10 分钟,取消、读取失败或检查未完成时不放行部分回答。安全解析最后的 `/models/...` 路径段与 URI 编码,显式非 JSON 或非法 UTF-8 请求体直接透传;零输出前置错误(如空 `response.created` 紧接 `response.failed`)交由 `explainResponse` 保留上游 429 / 业务错误,`isGuardTerminalResponse` 保护终态 400 不被二次改写。缺失模型声明无法验证,普通上游错误不因校验追加重试。
12
+ - 新增 70 项模型校验合成回归测试([model-guard.test.mjs](<model-guard.test.mjs>)),覆盖 JSON / SSE、次数配置、请求重放、取消、读取边界、面板沙箱及零输出错误隔离,并在文档同步记录流式显示延迟、重复计费、上游内置工具可能重复执行风险与不自动重试边界的模型错配例外。
13
+ - npm 安装示例、当前登录流程与升级指南固定到 0.1.13,GitHub Release 附带完整 tarball(含 `model-guard.mjs` 与 `ui/`)及 `SHA256SUMS`。
6
14
 
7
15
  ## 0.1.12 — 2026-12-03
8
16
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AgentRouter 插件(magpie)
2
2
 
3
- 给 magpie 接入 AgentRouter [国际站](https://agentrouter.org/)或[国内站](https://ps.air-outer.com/):支持 API Key、GitHub 与系统访问令牌登录,提供模型调用、余额与用量查询、每日签到、**可自定义请求头**,以及可独立开关的文字替换、历史内联和 Codex 会话资源清理。
3
+ 给 magpie 接入 AgentRouter [国际站](https://agentrouter.org/)或[国内站](https://ps.air-outer.com/):支持 API Key、GitHub 与系统访问令牌登录,提供模型调用、余额与用量查询、每日签到、**可自定义请求头**,以及可独立开关的实际模型校验、文字替换、历史内联和 Codex 会话资源清理。
4
4
 
5
5
  ## 文档导航
6
6
 
@@ -8,11 +8,32 @@
8
8
  - [安全政策](<SECURITY.md>):敏感信息处理与私密漏洞报告。
9
9
 
10
10
  - [优化设计与升级指南](<docs/OPTIMIZATION.md>):问题背景、与参考项目的取舍、兼容边界、升级/回滚与本地验证。
11
- - [更新日志](<CHANGELOG.md>):0.1.12 登录占位 0/0 余额防覆写修复、0.1.11 上游 Gemini Native 自动适配、会话资源清理与历史版本的变化。
11
+ - [更新日志](<CHANGELOG.md>):0.1.13 实际模型校验与尝试次数设置、0.1.12 登录占位 0/0 余额防覆写修复、0.1.11 上游 Gemini Native 自动适配、会话资源清理与历史版本的变化。
12
12
  - [本地签到说明](<LOCAL-CHECKIN.md>):独立签到工具的使用与安全边界。
13
13
 
14
14
  > 仓库源码更新不等于 npm 发布或你的网关已升级。请按升级指南自行验证;不要把真实 Cookie、访问令牌、私有词表或抓包提交到仓库。
15
15
 
16
+ ### 0.1.13:实际模型校验与尝试次数设置(PR #24)
17
+
18
+ 上游可能把请求的模型路由到其他模型。例如请求 `gemini-4-carbon`,响应 `modelVersion` 却是 `3.1-flash-lite-05-2026`。0.1.13 起默认开启校验:成功响应明确报告其他模型时,整条丢弃,再发送同一份已处理请求;只有匹配的回答才交给客户端。
19
+
20
+ 在 **AgentRouter 提供商编辑页 → 实际模型校验** 面板中设置 **校验实际返回模型**。开启后显示 **最多请求次数** 数字框,关闭时隐藏,修改后点击 **保存设置**。次数包含首次请求,**最小 2、默认 3**;3 只是初始值,不是可填写的上限,可以设为 5、10 等更大的整数。默认 3 次表示首次请求加最多 2 次重试;任意一次匹配即返回,连续错配达到设定次数则返回 HTTP 400、`agentrouter_model_mismatch`、请求模型、各次实际模型和尝试次数,并停止插件重试。
21
+
22
+ 面板使用 Magpie 官方的 `magpie.panels` 与本插件选项桥接接口。原生 `auth.options` 仅支持布尔开关,因此数字框和开关在同一面板保存,不添加第二个控制开关。没有面板支持的宿主可通过本插件的 JSON 选项配置,保存后重新加载插件:
23
+
24
+ ```json
25
+ { "modelGuardEnabled": true, "maxModelAttempts": 3 }
26
+ ```
27
+
28
+ `modelGuardEnabled: false` 关闭校验;缺省仍开启。数字框拒绝小于 2 或非整数的输入;手动编辑 JSON 时,小于 2 的整数按 2 处理,无效值回退到 3。应保留已有 `retryAfterSeconds` 等其他选项。
29
+
30
+ - **模型依据**:仅比较 API ID,去除首尾空白和开头的 `models/`,不进行别名、日期版本或模糊匹配。Gemini Native 检查 URL 中的请求模型与响应 `modelVersion`;Responses / Chat 检查请求 `model` 与响应 `model` / `response.model`;Anthropic Messages 检查响应 `model` / `message_start.message.model`。不扫描回答正文或工具参数中的同名字段。
31
+ - **显示延迟**:为发现末尾才报告的实际模型,开启时先完整暂存 HTTP 200 的 JSON / SSE,校验后再交付,流式回答会等生成结束才显示。暂存后的字节与应用响应头保留,移除失效的 `content-length`、`content-encoding`、`transfer-encoding`。关闭校验恢复原有流式路径。
32
+ - **失败边界**:缺少可识别模型字段时无法判断,保留响应;编码、非 JSON 请求或畸形 URL 等无法识别请求模型时透传。错误响应不因模型校验追加重试;若在零输出前置元数据(如空 `response.created`)后即遇到 `response.failed` / 错误事件,保留上游限流或业务错误并交由 `response.mjs` 诊断;若已出现错配输出或有效工具调用后才出现上游错误,整条丢弃并直接返回终态 400(不经 `response.mjs` 二次改写)。取消后不开始下一次尝试。每次响应检查或请求流暂存上限为 **64 MiB / 10 分钟**,超限、超时或读取失败时返回 400,不放行部分回答。
33
+ - **重复请求影响**:错配重试仍可能重复计费,或重复执行上游内置工具;丢弃客户端可见的工具调用不能撤回服务端已经执行的动作。重试复用相同的已处理正文、认证头和取消信号,不删历史、不切账号、不降级模型。400 用来停止插件预算内的尝试,不能禁止宿主或客户端另行发起请求。模型字段只是服务商的声明,不能证明实际运行的模型身份。
34
+
35
+ 该功能为既有“不新增自动重试”边界确立了明确的模型错配例外,不会将普通限流、业务错误或网络失败变成新的重试入口。实现见 [model-guard.mjs](<model-guard.mjs>) 与 [ui/model-guard.html](<ui/model-guard.html>),专项验证运行 `npm run test:model-guard`。
36
+
16
37
  ### 0.1.12:修复登录占位 0/0 余额误覆写(Issue #21)
17
38
 
18
39
  - **识别登录占位零值**:当 `/api/user/self` 失败并回退到 `POST /api/user/login` 时,`signIn()` 不再把登录响应中的占位 `quota === 0 && used_quota === 0` 当作真实 `$0.00` 余额覆写缓存;真实耗尽账号(`quota === 0 && used_quota > 0`)与正余额零消耗账号(`quota > 0 && used_quota === 0`)保持兼容。
@@ -54,7 +75,7 @@
54
75
  ### 0.1.9:可配置 429 等待时间
55
76
 
56
77
  - 已识别的 429 限流缺省等待 **10 秒**。在主导航 **插件 → 已安装 → agentrouter → 选项** 修改 `retryAfterSeconds` 并保存;这是插件级默认值,账号 metadata 中的同名字段可覆盖它。详见[自定义 429 等待时间](<#自定义-429-等待时间>)。
57
- - 保留上游明确提供的等待提示,兼容 JSON 和 SSE;插件不自动重试。
78
+ - 保留上游明确提供的等待提示,兼容 JSON 和 SSE;限流诊断不自动重试。
58
79
  - 原版 magpie 0.1.3906 的冷却下限为 60 秒,小于一分钟的实际倒计时还需要宿主支持;本 npm 包不包含宿主二进制补丁。
59
80
 
60
81
  ### 0.1.8:系统访问令牌接入,移除未通过真实验证的 LinuxDo 登录
@@ -65,7 +86,7 @@
65
86
  - **移除 LinuxDo OAuth 登录入口。** 真实验证结论:`connect.linux.do` 授权后回落到站点注册路由 `https://agentrouter.org/oauth/linuxdo`(并非请求里的 `/oauth/linuxdo/magpie` 子路径),站点前端在该路由挂载时立即请求 `/api/oauth/linuxdo`(真实验证记录到 1 次、HTTP 403)并跳转控制台,地址栏不再保留 `code`/`state`,插件侧手动回填在任何兑换请求之前即被拒绝。公开资料没有关于 LinuxDo redirect_uri 匹配语义的说明,站点前端确认该路由为精确匹配且没有任何可抑制自动兑换的标志位。
66
87
  - 移除范围包含 LinuxDo 方法、其常量、`/api/status` 的 `linuxdo_client_id` 读取与死代码 `codeOf`;GitHub 登录链路、提问形状与密钥筛选规则不变。
67
88
 
68
- > **本页登录流程适用于 0.1.12。** 下方命令固定该版本,安装前先查询 npm 官方 registry;源码版本号不等于已发布或你的网关已升级。0.1.7 曾发布 LinuxDo 登录入口,0.1.8 已将其移除,这不改变 0.1.7 已安装账号保存的数据。
89
+ > **本页登录流程适用于 0.1.13。** 下方命令固定该版本,安装前先查询 npm 官方 registry;源码版本号不等于已发布或你的网关已升级。0.1.7 曾发布 LinuxDo 登录入口,0.1.8 已将其移除,这不改变 0.1.7 已安装账号保存的数据。
69
90
 
70
91
  ### 0.1.7:站点选择与 LinuxDo 登录
71
92
 
@@ -89,7 +110,7 @@
89
110
 
90
111
  ### 0.1.4 变更
91
112
 
92
- - 历史版本改进了系统令牌遮蔽输入和可选签到配置;当前操作请以下文 0.1.12 登录流程为准。
113
+ - 历史版本改进了系统令牌遮蔽输入和可选签到配置;当前操作请以下文 0.1.13 登录流程为准。
93
114
  - 修复完整历史消息含空 `logprobs: []` 时漏掉内联重放的情况,保留工具关联、非空概率数据、引用注释和不透明状态。
94
115
  - 无法恢复仅存在于其他上游资源的历史或加密状态;这是范围受限的兼容补充,并非所有跨资源错误的通用解法。
95
116
 
@@ -105,19 +126,19 @@
105
126
 
106
127
  ```bash
107
128
  # 在有 Node.js / npm 的终端查询目标版本;确认可用后再安装
108
- npm view opencode-agentrouter-auth@0.1.12 version --registry=https://registry.npmjs.org
129
+ npm view opencode-agentrouter-auth@0.1.13 version --registry=https://registry.npmjs.org
109
130
 
110
131
  # Docker:查询成功后安装,容器名按你的实际部署修改
111
- docker exec magpie magpie plugin add npm:opencode-agentrouter-auth@0.1.12
132
+ docker exec magpie magpie plugin add npm:opencode-agentrouter-auth@0.1.13
112
133
 
113
134
  # 或者,本地 / 原生进程部署
114
- magpie plugin add npm:opencode-agentrouter-auth@0.1.12
135
+ magpie plugin add npm:opencode-agentrouter-auth@0.1.13
115
136
  ```
116
137
 
117
138
  - Docker 与原生进程命令二选一。安装后用 `magpie plugin list --json`(Docker 中在命令前加 `docker exec magpie`)核对插件,再在面板检查 AgentRouter 的插件选项和登录状态。
118
139
  - 如果版本查询返回 `E404`,该版本在所查 registry 尚不可用;不要把源码版本号当成 npm 已发布证明,可改用下方源码安装。若仅宿主安装失败,可运行 `magpie plugin registry` 检查它实际使用的 registry;查询命令不会替你修改宿主设置。
119
140
  - 已用本地目录安装的用户,继续更新原目录即可;不要直接再添加一份 npm 插件。先备份并确认宿主如何关联插件路径、认证及选项,再决定是否迁移,避免重复注册或丢失原配置。
120
- - 固定 `@0.1.12` 便于复现;省略版本会让宿主选择版本,但并不等同于更新所有插件。`magpie plugin update` 则可能更新其他插件,不作为本插件的定点升级步骤。
141
+ - 固定 `@0.1.13` 便于复现;省略版本会让宿主选择版本,但并不等同于更新所有插件。`magpie plugin update` 则可能更新其他插件,不作为本插件的定点升级步骤。
121
142
  - 已通过 npm 安装的用户,升级或降级前须确认当前宿主的**单包替换方式以及认证/选项保留行为**;未确认前暂停操作,不直接重复执行 `plugin add`。旧版本也须经 npm 查询确认存在,不能假设仓库旧版本都已发布。下方[升级/回滚指南](<docs/OPTIMIZATION.md#11-升级与回退>)针对本地包/目录备份,不是已验证的 npm 定点降级流程。
122
143
 
123
144
  #### Docker 源码安装
@@ -145,9 +166,9 @@ magpie plugin add /path/to/agentrouter-magpie-plugin
145
166
 
146
167
  ---
147
168
 
148
- ### 2. 登录并绑定账号(0.1.12)
169
+ ### 2. 登录并绑定账号(0.1.13)
149
170
 
150
- 以下流程适用于已加载 0.1.12 的宿主,沿用 0.1.8 的登录方式;0.1.7 及更早版本的菜单不同(0.1.7 的 LinuxDo 入口已在 0.1.8 移除)。新账号运行交互式登录命令(升级既有账号不要求重新登录):
171
+ 以下流程适用于已加载 0.1.13 的宿主,沿用 0.1.8 的登录方式;0.1.7 及更早版本的菜单不同(0.1.7 的 LinuxDo 入口已在 0.1.8 移除)。新账号运行交互式登录命令(升级既有账号不要求重新登录):
151
172
  ```bash
152
173
  docker exec -it magpie magpie plugin login agentrouter
153
174
  # 非 Docker 环境直接运行:magpie plugin login agentrouter
@@ -240,7 +261,7 @@ docker exec magpie magpie quota agentrouter
240
261
  - `endpoint` / `apiBase` / `site` / `headers`:保留既有端点、站点与请求头能力。
241
262
  - `retryAfterSeconds`:已识别的 429 限流缺少上游等待提示时使用的等待秒数,默认 `10`,配置方法见下文。
242
263
 
243
- **当前提供商功能选项仅支持布尔开关,没有新增 Cookie 设置页或任意文本选项。** 不要把凭据粘贴到布尔选项;高级字段只能通过已有宿主能力或下文的手动配置路径维护。插件级 JSON 配置中的 `retryAfterSeconds` 是独立的数值选项。
264
+ **原生 `auth.options` 仅支持布尔开关,没有新增 Cookie 设置页或任意文本选项。** 模型校验面板单独保存 `modelGuardEnabled` / `maxModelAttempts`,插件级 JSON 中的 `retryAfterSeconds` 也是独立数值选项。不要把凭据粘贴到这些选项;高级认证字段只能通过已有宿主能力或下文的手动配置路径维护。
244
265
 
245
266
  ## 签到:GitHub 重新登录
246
267
 
@@ -367,7 +388,7 @@ AgentRouter 的非 Gemini 模型**不支持** `/v1/chat/completions`:
367
388
  - **不删** `previous_response_id`、`conversation` 或 `item_reference`;这些请求不做 ID 重写,因为插件并不知道它们指向的完整历史。0.1.3 的独立文本过滤仍可替换请求中可见的匹配正文,但不能处理引用背后的历史。客户端需要重发完整内联历史,或由上游固定到原资源。
368
389
  - **不删改推理及 compaction 条目**,包括它们的 ID、摘要和加密内容。`store:false` 不会让加密状态跨资源通用;不同密钥无法解密时仍须原资源。
369
390
  - 非空引用注释、未知消息字段和未知条目类型保留原样,不为修复而静默丢失内容。文件/图像/容器等资源引用也不递归删除。
370
- - 只处理最多 4 MiB 的 JSON 请求;读取 Request 副本最多 2 秒,支持取消。超限、非 JSON、压缩正文和其他端点不改写。不会自动重试,更不会重放用户历史。
391
+ - 只处理最多 4 MiB 的 JSON 请求;读取 Request 副本最多 2 秒,支持取消。超限、非 JSON、压缩正文和其他端点不改写。历史内联本身不会发起重试;独立模型校验只在明确错配时复用处理后的同一请求,不因资源错误删减历史再发送。
371
392
  - 关闭提供商选项 **内联发送完整的 Responses 历史** 只停用无损内联;本地词表和默认关闭的有损清理独立生效。三个正文选项都关闭才恢复原始正文透传。只有服务端引用、没有完整内联正文的旧会话,不保证仅升级插件就能继续。
372
393
 
373
394
  以上是 `portable-responses` 的无损兼容边界;默认关闭的 `codex-session-repair` 是另一个有损模式,其删减范围与风险见页首说明。不能把开启清理后请求成功理解为原有上下文已完整恢复。
@@ -490,7 +511,7 @@ magpie 识别流内错误为 429 后,可能立即换账号,再对同一账
490
511
  - 正常响应逐字节透传。已有正文、推理或工具调用后的错误不重新包装,避免丢失部分输出
491
512
  或诱发工具重复执行。未知错误、普通 429、截断流也不会凭空变成 token 限流。
492
513
  - 只检查最多 **64 KiB / 15 秒** 的流前缀;超过任一边界就原样放行,不缓存整段回答。
493
- 插件自身不发起重试,也不绕过上游限制;默认 `magpie.maxConcurrency` 保持 **2**。
514
+ 插件不因限流发起重试,也不绕过上游限制;默认 `magpie.maxConcurrency` 保持 **2**。
494
515
 
495
516
  > 看到这个 429:遵循等待提示,降低并发并评估上下文大小。如果持续发生,应向上游提供
496
517
  > request-id 查询真实阈值。插件修复的是错误识别与退避信息,不会增加上游可用容量。
@@ -507,7 +528,7 @@ magpie 识别流内错误为 429 后,可能立即换账号,再对同一账
507
528
 
508
529
  接受正整数或纯数字字符串;空值、零、负数、小数、其他类型或超出 JavaScript 安全整数范围的值回退为 10 秒。需要单独设置某个账号时,可在它已有的 `metadata` 中加入同名字段,覆盖插件选项;兼容宿主传入的同名顶层字段。手工修改账号配置后须重新加载插件,且应保留已有 key 和其他字段。完整文件结构见 [手动配置格式](<#手动配置文件格式plugin-authjson>)。
509
530
 
510
- 上游已经给出的等待提示优先,秒数、HTTP 日期和毫秒头均保持原值。这个配置只为已识别的限流补充等待时间,不改变错误分类;余额不足、内容拒绝及未知错误不会因此获得新的等待提示。插件仍不发起自动重试,实际重试由宿主决定。
531
+ 上游已经给出的等待提示优先,秒数、HTTP 日期和毫秒头均保持原值。这个配置只为已识别的限流补充等待时间,不改变错误分类;余额不足、内容拒绝及未知错误不会因此获得新的等待提示。插件不因这些错误发起自动重试,宿主的重试另行决定;模型错配校验有独立的尝试次数预算。
511
532
 
512
533
  **宿主兼容性:**原版 magpie 0.1.3906 的限流冷却至少为 60 秒,即使插件返回 `Retry-After: 10` 也会显示约一分钟。要让倒计时使用小于一分钟的配置,宿主还需支持按 AgentRouter 的等待提示冷却;只升级本插件不能解除原版宿主的下限。
513
534
 
@@ -526,7 +547,7 @@ JSON 仅在 HTTP **200 / 400 / 429** 时检查副本,最多 **64 KiB / 2 秒**
526
547
 
527
548
  当封套同时包含可识别的数值状态和错误代码时,以状态为准;类型按限流、繁忙、服务故障区分。认证、权限、余额、配额和内容策略等明确业务错误优先,**不会被包装为暂时性服务故障**。已有 token 限流、内容拦截、跨资源历史与空输出的专用类型不变。
528
549
 
529
- 改写后的响应保留上游代码与消息(`error.code` / `error.upstream`)、request-id,以及 `Retry-After`(包括 HTTP 日期)和上游毫秒等待头;仅清除失效的正文长度、编码和摘要头。已识别的 429 在缺少等待提示时使用 `retryAfterSeconds`(默认 10 秒);其他错误不补等待时间。调用是否重试由宿主决定,插件不会多发一次 POST、切换账号或降级历史。
550
+ 改写后的响应保留上游代码与消息(`error.code` / `error.upstream`)、request-id,以及 `Retry-After`(包括 HTTP 日期)和上游毫秒等待头;仅清除失效的正文长度、编码和摘要头。已识别的 429 在缺少等待提示时使用 `retryAfterSeconds`(默认 10 秒);其他错误不补等待时间。`response.mjs` 的错误诊断不会追加 POST、切换账号或降级历史;独立模型校验的错配重试及完整暂存规则见页首。
530
551
 
531
552
  SSE 仍只观察首个有效内容或未知事件之前最多 **64 KiB / 15 秒** 的前缀。增量解析兼容混合换行、注释、多行 `data:` 与跨块 UTF-8;重复 `event:` 取最后一个值,只移除冒号后的一个可选空格。已知字段内出现未知数据形状时也立即结束诊断,透传原始字节并保留取消、背压及超时中的在途读取;不发送心跳、不缓存整段回答、不观察已经放行的后续事件。相关实现见 [response.mjs](<response.mjs>)。
532
553
 
@@ -1,8 +1,10 @@
1
- # 0.1.12 优化与兼容边界
1
+ # 0.1.13 优化与兼容边界
2
2
 
3
3
  [使用说明](<../README.md>) · [版本记录](<../CHANGELOG.md>) · [MIT 许可](<../LICENSE>)
4
4
 
5
- 本文说明 **0.1.12** 的登录占位 `0 / 0` 余额防覆写与 WAF 错误透传修复,以及延续的 0.1.11 上游 Gemini Native(`@ai-sdk/google` + `/v1beta`)自动适配、可选会话资源清理、中文功能选项、可配置限流等待、站点选择、系统访问令牌接入与兼容能力。安装命令固定 0.1.12,先查询 npm 官方 registry 确认可用;源码、npm 包和宿主实际加载版本应分别核对。下文保留既有优化与安全边界,示例不含真实请求、账号或凭据。
5
+ 本文说明 **0.1.13** 的实际模型校验与可配置错配重试、0.1.12 的登录占位 `0 / 0` 余额防覆写与 WAF 错误透传修复,以及延续的 0.1.11 上游 Gemini Native(`@ai-sdk/google` + `/v1beta`)自动适配、可选会话资源清理、中文功能选项、可配置限流等待、站点选择、系统访问令牌接入与兼容能力。安装命令固定 0.1.13,先查询 npm 官方 registry 确认可用;源码、npm 包和宿主实际加载版本应分别核对。下文保留既有优化与安全边界,示例不含真实请求、账号或凭据。
6
+
7
+ 0.1.13 新增默认开启的**实际模型校验**([PR #24](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/pull/24) / [Issue #23](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/issues/23)),为原有“不自动重试”约定确立了明确的模型错配例外。`modelGuardEnabled` 默认开启,`maxModelAttempts` 是包含首次请求的总次数,最小 2、默认 3;3 不是设置上限。该变化会完整暂存成功 JSON / SSE 后再交付,延后流式显示,并可能因重复请求增加计费或重复上游内置工具动作。关闭校验恢复原有流式路径。细节见下文第 10 节和 [使用说明](<../README.md#0113实际模型校验与尝试次数设置pr-24>)。
6
8
 
7
9
  0.1.12 在 `signIn()`、`balance()` 与 `usageOf()` 中排除 `/api/user/login` 占位 `quota === 0 && used_quota === 0` 导致的 `$0.00 / $0.00` 误覆写,在已确认 WAF 拦截时保留 `blocked` 原因并直接回退 `spendOf()`,并在非 WAF 场景且登录返回 `Set-Cookie: session=...` 时补查一次 `/api/user/self`(不发送空/过期 `Authorization` 头)。
8
10
 
@@ -23,7 +25,7 @@
23
25
  - **历史 ID 不能任意删除。** 只有内容完整、形状已知的条目才能内联;服务端引用、推理和加密状态不能靠删字段恢复。
24
26
  - **文本替换与历史内联相互独立。** 本地词表只修改获准的普通正文;内联开关不应改变文字过滤器识别空 `logprobs: []` 的能力。
25
27
 
26
- 本插件仍运行在既有宿主中,不新增独立服务、仪表盘、遥测、自动重试或账号切换。默认处理仍保持上述无损边界;仅用户显式开启 `codex-session-repair` 时允许按其已说明范围删减发送副本,不能将这种有损结果当作上下文完整恢复。
28
+ 本插件仍运行在既有宿主中,不新增独立服务、仪表盘、遥测或账号切换。除模型校验开启时明确错配的有界重复请求外,不为普通错误新增自动重试。历史处理仍保持上述无损边界;仅用户显式开启 `codex-session-repair` 时允许按其已说明范围删减发送副本,不能将这种有损结果当作上下文完整恢复。
27
29
 
28
30
  完整 assistant 消息去掉顶层查找 ID 后,正文仍使用 `output_text` 并保留空注释/概率字段;不得误转为仅适用于其他角色的 `input_text`。此修复不改变 reasoning、引用和未知字段的保留规则,也不承诺不透明状态跨资源可用。
29
31
 
@@ -36,8 +38,8 @@
36
38
  | 参考与取舍 | 本插件的决定 |
37
39
  | --- | --- |
38
40
  | 显式错误分类、有界诊断 | 采用保守白名单及有界观察,不能确定时保留原始数据 |
39
- | 流式处理 | 只检查 SSE 前导,正常或未知数据按原始字节放行 |
40
- | 多层自动重试路径 | 不移植;不同分支的重试次数不能当作一个清晰的总预算,插件选择完全不追加尝试 |
41
+ | 流式处理 | `response.mjs` 仅检查 SSE 前导;独立模型校验开启时先完整暂存,以识别末尾或变化的模型声明 |
42
+ | 多层自动重试路径 | 不移植;只有明确模型错配可以使用同一份已处理请求和单一总次数预算重试,不为普通上游错误追加尝试 |
41
43
  | 独立代理、控制台和遥测 | 不引入;宿主继续负责部署、路由和运维 |
42
44
  | 历史剥离或降级 | 不作为默认行为;独立的有损清理须显式开启,不删除工具关联,不以请求成功宣称历史完整恢复 |
43
45
 
@@ -45,7 +47,7 @@
45
47
 
46
48
  ## 3. 模块职责与处理顺序
47
49
 
48
- 请求侧顺序为:检查适用端点与正文 → 有界读取 → 可选有损会话资源清理(默认关闭)→ 本地普通正文过滤 → 可选完整历史内联 → 仅在实际修改时重新序列化。响应侧独立执行有界诊断。
50
+ 请求侧顺序为:检查适用端点与正文 → 有界读取 → 可选有损会话资源清理(默认关闭)→ 本地普通正文过滤 → 可选完整历史内联 → 仅在实际修改时重新序列化。随后独立模型校验按设置执行完整响应检查和错配次数预算,最后由 `response.mjs` 执行原有有界错误诊断;每次错配尝试复用同一份已处理请求,不再次改写历史。
49
51
 
50
52
  | 模块 | 职责 |
51
53
  | --- | --- |
@@ -54,7 +56,8 @@
54
56
  | [session-repair.mjs](<../session-repair.mjs>) | 只清理发送副本中已识别的资源绑定;原对象和客户端文件不变,空输入/不可重放的工具数据明确报错 |
55
57
  | [content-filter.mjs](<../content-filter.mjs>) | 加载私有字面量词表,保护代码、工具数据和不透明内容 |
56
58
  | [response.mjs](<../response.mjs>) | JSON 错误分类、SSE 前导观察、失败说明与原始流转交 |
57
- | [index.mjs](<../index.mjs>) | 对接宿主选项及 fetch;一次宿主 fetch 调用至多发起一次上游 fetch;缺失 key 时本地拒绝 |
59
+ | [model-guard.mjs](<../model-guard.mjs>) | 协议模型字段校验、完整响应暂存、可重放请求快照与错配总次数预算;普通上游错误不触发校验重试 |
60
+ | [index.mjs](<../index.mjs>) | 对接宿主选项及 fetch;缺失 key 时本地拒绝,只有模型校验明确错配才在设定次数内再次发送 |
58
61
 
59
62
  共享读取器是内部模块,不新增根入口公开 API。0.1.5 没有新增依赖、环境变量、提供商选项或登录配置迁移。
60
63
 
@@ -90,7 +93,7 @@ Key 选择规则:只有一把启用且完整的 Key 时直接使用;填写
90
93
 
91
94
  ### 旧配置与签到:保留账号设置
92
95
 
93
- 新账号默认 `agentrouter.org`;选择国内站的新账号显式保存 `apiBase: https://ps.air-outer.com/v1`。模型地址仍依次采用显式 endpoint、已存 apiBase、默认国际站;旧账号只有 `site: air` 时不会自动切换模型端点。升级不改写旧账号 key、site、headers 或其他设置。GitHub 与系统访问令牌方式会询问站点和凭据,其余问题(端点、请求头、用户名密码、Cookie)不再作为登录问卷出现。当前插件选项只有布尔开关,**没有新增 Cookie 设置页**。需要高级配置时先备份,再使用 [README 的既有手动配置格式](<../README.md#手动配置文件格式plugin-authjson>);不要把凭据写进布尔选项。
96
+ 新账号默认 `agentrouter.org`;选择国内站的新账号显式保存 `apiBase: https://ps.air-outer.com/v1`。模型地址仍依次采用显式 endpoint、已存 apiBase、默认国际站;旧账号只有 `site: air` 时不会自动切换模型端点。升级不改写旧账号 key、site、headers 或其他设置。GitHub 与系统访问令牌方式会询问站点和凭据,其余问题(端点、请求头、用户名密码、Cookie)不再作为登录问卷出现。原生 `auth.options` 只有布尔开关,模型校验使用独立面板和本插件 JSON 选项,**没有新增 Cookie 设置页**。需要高级配置时先备份,再使用 [README 的既有手动配置格式](<../README.md#手动配置文件格式plugin-authjson>);不要把凭据写进布尔选项。
94
97
 
95
98
  GitHub Cookie 是可选签到续期的高权限会话,不随升级自动采集或启用。本次未新增任何自动登录或签到续期机制。远程网关会将凭据保存在远程服务器;格式正确不代表会话有效、账号匹配或可通过 WAF。不得公开 Cookie、令牌或回调,也不能绕过授权确认、2FA 或验证码。
96
99
 
@@ -105,6 +108,8 @@ GitHub Cookie 是可选签到续期的高权限会话,不随升级自动采集
105
108
  - `send-codex-headers`:**发送 Codex 客户端请求头**,默认开启,与正文选项独立。
106
109
  - `codex-session-repair`:**清理 Codex 会话的旧资源绑定(有损)**,默认关闭。由既有 `input.magpie.option(provider, key)` 读取,每次请求按最新已保存值决定是否清理;支持 `confirm` 的宿主提供风险确认,不新增页面或认证字段。
107
110
 
111
+ 实际模型校验的 `modelGuardEnabled` / `maxModelAttempts` 使用本插件 JSON 选项,并由 provider 面板一起保存。校验默认开启,次数最小 2、默认 3,包含首次请求;关闭后隐藏次数输入框并恢复原有流式行为。
112
+
108
113
  429 的缺省等待时间通过原生插件 JSON 选项 `retryAfterSeconds` 配置,默认 10 秒。`package.json` 的 `magpie.options` 提供示例,宿主通过插件入口第二个参数传入已保存选项。账号 `metadata.retryAfterSeconds` 可覆盖它,同名顶层账号字段继续沿用既有优先级。原生页面保存后宿主重载插件;手工修改账号配置后须重新加载插件或重启宿主。数值不放入仅支持布尔值的 `auth.options`。
109
114
 
110
115
  以下表格以 `codex-session-repair` 关闭为前提。开启清理时,先在发送副本中执行其已说明的删减,再独立执行表中的过滤与内联。
@@ -246,18 +251,23 @@ Markdown 采取保守策略,而不是试图实现完整语法解析器:
246
251
  实体头只在正文确实重建时调整:
247
252
 
248
253
  - 请求改写移除 `content-length`、`content-md5`、`digest`、`content-digest`。
249
- - 响应改写设为 JSON,并移除 `content-length`、`content-encoding`、`transfer-encoding`、`etag`、`content-md5`、`digest`。
254
+ - 错误诊断改写设为 JSON,并移除 `content-length`、`content-encoding`、`transfer-encoding`、`etag`、`content-md5`、`digest`。模型校验暂存成功响应时保留字节和应用头,仅移除 `content-length`、`content-encoding`、`transfer-encoding`。
250
255
  - 不改写的路径保留原始正文和对应响应头;默认客户端标识开关与用户配置头仍遵循插件既有规则。不要把 Cookie 或 Authorization 当作普通客户端标识示例传播。
251
256
 
252
- **一次宿主 fetch 至多一次上游 fetch;缺失 key 时为零。** 插件不追加 POST,不切账号、不重放工具、不降级历史;宿主自身的重试、路由和故障转移是另一层策略,必须分别配置和核查。返回 429/503 或等待头不等于插件执行了重试,也不能保证宿主一定按同样策略等待。
257
+ **普通错误不追加上游 fetch;缺失 key 时为零。** 唯一明确的例外是开启实际模型校验后,成功响应明确报告其他模型:丢弃该响应并在用户设置的总次数内发送同一份已处理请求。默认总次数为 3(首次加最多 2 次重试),最小 2,可以填写更大的整数;连续错配达到预算即返回 400,任意一次匹配只交付那次响应。异常、认证、余额、限流和内容策略错误不扩大此预算或触发校验重试。
258
+
259
+ 校验只读取协议模型元数据,不扫描正文或工具参数;缺失声明时无法确认模型而透传。完整暂存覆盖晚到或变化的字段,每次响应检查或请求流读取限制 64 MiB / 10 分钟;取消、超限、超时和读取失败时不放行部分回答。零输出前置元数据紧接上游错误时交由 `response.mjs` 保留限流/业务错误,错配输出与后续上游错误并存时直接终止,不把错配工具调用交给客户端。
260
+
261
+ 插件不因错配而删减历史、切账号或降级模型,但重复请求可能重复计费或再次执行上游内置工具;丢弃回复不能撤销服务端动作。默认开启完整暂存会延后流式显示,关闭后恢复原路径。宿主自身的重试、路由和故障转移是另一层策略,必须分别核查;400 仅表示插件停止本次尝试,不能禁止客户端重新请求。
253
262
 
254
263
  ## 11. 升级与回退
255
264
 
256
- 1. 阅读 [使用说明](<../README.md>) 和 [版本记录](<../CHANGELOG.md>),核对来源:npm 安装固定 0.1.12 并先查询官方 registry;本地包/目录安装应核对提交、包版本和宿主实际运行版本。不能把源码版本号当成 npm 发布或远程网关升级证明。
265
+ 1. 阅读 [使用说明](<../README.md>) 和 [版本记录](<../CHANGELOG.md>),核对来源:npm 安装固定 0.1.13 并先查询官方 registry;本地包/目录安装应核对提交、包版本和宿主实际运行版本。不能把源码版本号当成 npm 发布或远程网关升级证明。
257
266
  2. 在受保护的位置备份当前插件版本、私有词表及宿主管理的配置;不要将凭据备份加入公开仓库。
258
- 3. 使用已核验的完整本地包或完整插件目录升级,不能只覆盖入口文件。[body-inspection.mjs](<../body-inspection.mjs>) 与 0.1.10 新增的 [session-repair.mjs](<../session-repair.mjs>) 是运行时必需模块,漏带会导致模块加载失败。
267
+ 3. 使用已核验的完整本地包或完整插件目录升级,不能只覆盖入口文件。[body-inspection.mjs](<../body-inspection.mjs>) 与 0.1.10 新增的 [session-repair.mjs](<../session-repair.mjs>) 是运行时必需模块;0.1.13 还必需 [model-guard.mjs](<../model-guard.mjs>) 及 `ui/` 面板文件,漏带会导致加载或面板失败。
259
268
  4. 无需迁移认证字段或环境变量;升级前后核对旧 key、site 和其他设置不变,不必重新登录。新增有损开关默认关闭,旧开关值不改写。重新加载插件,让运行中的 loader 使用新源码与规则快照。先确认独立开关组合符合自己的使用意图。
260
269
  5. 如只需停用正文变换,可关闭三个正文选项;这不会停用响应诊断。需要完整回退时,恢复此前验证过的完整版本并重新加载,不混用新旧模块。
270
+ 回退到 0.1.12 会失去实际模型校验([model-guard.mjs](<../model-guard.mjs>))与 Magpie 提供商编辑页校验面板(`ui/`)。
261
271
  回退到 0.1.11 会失去 [Issue #21](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/issues/21) 的登录占位 `0 / 0` 余额拦截与 WAF 错误透传修复。
262
272
  回退到 0.1.10 会失去上游 Gemini Native(`@ai-sdk/google` + `/v1beta`)自动分流、路径归一化、`x-goog-api-key` 注入以及单元素数组错误封套识别。
263
273
  回退到 0.1.9 会失去会话资源清理开关和本次中文功能说明,恢复旧开关行为;不会恢复已经在先前发送副本中丢弃的上下文,也不改写客户端文件。
@@ -278,6 +288,8 @@ npm pack --dry-run
278
288
 
279
289
  Python 命令仅执行维护脚本的测试部分,不调用 Docker。这些回归不需要真实账号或凭据;不要用真实登录或生产请求替代合成回归。
280
290
 
291
+ 0.1.13 发布准备在 Windows、Node.js v24.22.1、Python 3.13.12 上完成 **Node.js 438 项、policy 13 项、Python 2 项**本地回归;打包预检为 20 个文件,包含 `model-guard.mjs` 与 `ui/` 面板资源,不包含测试文件、私有词表、凭据或会话记录。[PR #24](https://github.com/ZhaoJun233/agentrouter-magpie-plugin/pull/24)(合并提交 `2e5da55`)的 GitHub Actions CI(Linux/Windows × Node 20/22/24)、`PR policy` 与 `CodeQL analysis` 均通过。合成检查不代表真实模型调用、浏览器面板操作或宿主升级已验证。
292
+
281
293
  0.1.12 发布准备在 Windows、Node.js v24.22.1、Python 3.13.12 上完成 **Node.js 369 项、policy 13 项、Python 2 项**本地回归;打包预检为 16 个文件,不包含测试文件、私有词表、凭据或会话记录,包含提交 `bec3cfd` 的登录占位 `0 / 0` 余额拦截、WAF 错误透传与非 WAF 会话补查修复。合成检查不代表 npm 已完成发布、浏览器开关操作或宿主升级已验证。
282
294
 
283
295
  0.1.11 发布准备在 Windows、Node.js v24.22.1、Python 3.13.12 上完成 **Node.js 364 项、policy 13 项、Python 2 项**本地回归;打包预检为 16 个文件,不包含测试文件、私有词表、凭据或会话记录。提交 `1aa6df7` 与 `30ed417` 的 GitHub Actions CI(Linux/Windows × Node 20/22/24)与 CodeQL 均通过。合成检查不代表 npm 已完成发布、浏览器开关操作或宿主升级已验证。
@@ -300,6 +312,7 @@ PR 作者报告的真实账号复测为 2 次 `/api/token` 请求、0 次 `/api/
300
312
  - [文本过滤回归](<../content-filter.test.mjs>) 与 [请求内联回归](<../request-replay.test.mjs>):四种开关组合、空/非空概率数据、无变化字节、幂等性、工具及不透明状态保留。
301
313
  - [会话清理回归](<../session-repair.test.mjs>):默认关闭、仅布尔 `true` 开启、请求间即时切换、客户端输入保留、工具关联、空输入/不透明工具零请求、独立开关组合及既有读取边界。
302
314
  - [Gemini 兼容回归](<../gemini-compat.test.mjs>):按 `supported_endpoint_types`(及 `gemini-*` 兜底)分流至 `@ai-sdk/google` `/v1beta`、1M 上下文与 `variants` 声明、`/v1/models/...` → `/v1beta/models/...` 路径归一化、`x-goog-api-key` 与 Codex UA 协同、Gemini 正文免于 `/responses` 改写及单元素数组错误封套处理。
315
+ - [模型校验回归](<../model-guard.test.mjs>):Gemini Native / Responses / Chat / Anthropic 协议模型元数据校验、末尾与变更模型字段暂存、可配置 `maxModelAttempts` 与 `modelGuardEnabled` 开关、不可重放请求流快照、取消与 64 MiB / 10 分钟边界、面板沙箱交互资源、`URIError` 与非 JSON 请求透传、零输出前置错误保留及终态 400 防二次改写。
303
316
 
304
317
  ## 13. 已知非保证
305
318
 
package/index.mjs CHANGED
@@ -3,6 +3,7 @@ import { prepareRequest } from "./request.mjs";
3
3
  import { loadTextFilter } from "./content-filter.mjs";
4
4
  import { parseGithubCookie } from "./github-cookie.mjs";
5
5
  import { SessionRepairError } from "./session-repair.mjs";
6
+ import { fetchWithModelGuard, isGuardTerminalResponse } from "./model-guard.mjs";
6
7
 
7
8
  // AgentRouter (agentrouter.org) for magpie / OpenCode.
8
9
  //
@@ -1149,6 +1150,9 @@ export const AgentRouterAuthPlugin = async (input, options = {}) => {
1149
1150
  const portableResponses = () => input?.magpie?.option?.(PROVIDER, "portable-responses") !== false;
1150
1151
  const textFilterEnabled = () => input?.magpie?.option?.(PROVIDER, "text-filter") !== false;
1151
1152
  const sessionRepairEnabled = () => input?.magpie?.option?.(PROVIDER, "codex-session-repair") === true;
1153
+ // Provider panels save typed plugin options; auth.options only supports
1154
+ // booleans in Magpie. Keep the panel's toggle and count in one settings store.
1155
+ const modelGuardEnabled = () => options?.modelGuardEnabled !== false;
1152
1156
  return {
1153
1157
  // The provider before anyone signs in: the models the vendor serves, so the
1154
1158
  // row has something to show, and the shape each listed one takes.
@@ -1300,7 +1304,7 @@ export const AgentRouterAuthPlugin = async (input, options = {}) => {
1300
1304
 
1301
1305
  // Inline replay avoids resource-local item lookups when complete contents
1302
1306
  // are present. Server-only references and unknown kinds stay untouched.
1303
- // Response normalization preserves successful bytes and never retries.
1307
+ // Only explicit model mismatches retry, up to the user's attempt limit.
1304
1308
  async loader(getAuth, provider) {
1305
1309
  const auth = (await getAuth()) ?? {};
1306
1310
  const textFilter = textFilterEnabled() ? await loadTextFilter() : null;
@@ -1339,7 +1343,11 @@ export const AgentRouterAuthPlugin = async (input, options = {}) => {
1339
1343
  type: "invalid_request_error", code: error.code, message: error.message,
1340
1344
  } }, { status: 400 });
1341
1345
  }
1342
- return explainResponse(await fetch(target, prepared), {
1346
+ const guarded = await fetchWithModelGuard(target, prepared, {
1347
+ enabled: modelGuardEnabled(), maxAttempts: options?.maxModelAttempts,
1348
+ });
1349
+ if (isGuardTerminalResponse(guarded)) return guarded;
1350
+ return explainResponse(guarded, {
1343
1351
  retryAfterSeconds: meta(auth, "retryAfterSeconds") ?? options?.retryAfterSeconds,
1344
1352
  });
1345
1353
  },
@@ -0,0 +1,297 @@
1
+ // Check provider protocol metadata before releasing any answer or tool call.
2
+ // Even a matching first event is held: some relays report the real model late.
3
+ const MAX_BYTES = 64 * 1024 * 1024;
4
+ const INSPECTION_MS = 10 * 60 * 1000;
5
+ const DEFAULT_MAX_ATTEMPTS = 3;
6
+ const GEMINI_MODEL_ACTION = /^\/models\/([^/:]+(?:\/[^/:]+)*):(?:generateContent|streamGenerateContent)$/;
7
+ const guardTerminalResponses = new WeakSet();
8
+ const normalize = value => typeof value === "string" ? value.trim().replace(/^models\//, "") : "";
9
+
10
+ export function modelAttemptLimit(value) {
11
+ const parsed = typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value;
12
+ if (typeof parsed !== "number" || !Number.isSafeInteger(parsed)) return DEFAULT_MAX_ATTEMPTS;
13
+ return Math.max(2, parsed);
14
+ }
15
+
16
+ class InspectionError extends Error {}
17
+
18
+ function stopped(signal) {
19
+ if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError");
20
+ }
21
+
22
+ function terminal(code, message, details = {}) {
23
+ // 400 is intentional: 429 and 5xx invite SDK/gateway retries and failover.
24
+ const response = Response.json({ error: {
25
+ type: "invalid_request_error", code, message, retryable: false, ...details,
26
+ } }, { status: 400 });
27
+ guardTerminalResponses.add(response);
28
+ return response;
29
+ }
30
+
31
+ export function isGuardTerminalResponse(response) {
32
+ return guardTerminalResponses.has(response);
33
+ }
34
+
35
+ async function readBytes(stream, { signal, maxBytes, timeoutMs }) {
36
+ stopped(signal);
37
+ if (!stream) return new Uint8Array();
38
+ const reader = stream.getReader();
39
+ const chunks = [];
40
+ let length = 0, timer, abort;
41
+ const interrupted = new Promise((_, reject) => {
42
+ timer = setTimeout(() => reject(new InspectionError("模型校验读取超时")), timeoutMs);
43
+ abort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
44
+ signal?.addEventListener("abort", abort, { once: true });
45
+ if (signal?.aborted) abort();
46
+ });
47
+ try {
48
+ for (;;) {
49
+ const { value, done } = await Promise.race([reader.read(), interrupted]);
50
+ if (done) break;
51
+ length += value.byteLength;
52
+ if (length > maxBytes) throw new InspectionError("模型校验正文超过 64 MiB 上限");
53
+ // Own the bytes: a producer may reuse its buffer on the next read.
54
+ chunks.push(value.slice());
55
+ }
56
+ const bytes = new Uint8Array(length);
57
+ let offset = 0;
58
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
59
+ return bytes;
60
+ } catch (error) {
61
+ // Never await cancellation: an upstream stream may not settle its cancel().
62
+ void reader.cancel(error).catch(() => {});
63
+ throw error;
64
+ } finally {
65
+ clearTimeout(timer);
66
+ signal?.removeEventListener("abort", abort);
67
+ try { reader.releaseLock(); } catch {}
68
+ }
69
+ }
70
+
71
+ async function snapshotBody(target, init, limits) {
72
+ const body = init.body !== undefined ? init.body : (target instanceof Request ? target.body : null);
73
+ if (body == null || typeof body === "string") return body;
74
+ if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0));
75
+ if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();
76
+ if (body instanceof Blob || body instanceof URLSearchParams) return body;
77
+ if (typeof body.getReader === "function") return readBytes(body, limits);
78
+ throw new InspectionError("模型校验无法重放该请求正文");
79
+ }
80
+
81
+ async function bodyText(body) {
82
+ if (typeof body === "string") return body;
83
+ if (body instanceof Uint8Array) {
84
+ try { return new TextDecoder("utf-8", { fatal: true }).decode(body); } catch { return null; }
85
+ }
86
+ if (body instanceof Blob && body.size <= MAX_BYTES) return body.text();
87
+ return null;
88
+ }
89
+
90
+ function requestRoute(target, init) {
91
+ let url;
92
+ try { url = new URL(target instanceof Request ? target.url : target); } catch { return null; }
93
+ if ((init.method ?? (target instanceof Request ? target.method : "GET")).toUpperCase() !== "POST") return null;
94
+ const idx = url.pathname.lastIndexOf("/models/");
95
+ if (idx >= 0) {
96
+ const gemini = GEMINI_MODEL_ACTION.exec(url.pathname.slice(idx));
97
+ if (gemini) {
98
+ try { return { protocol: "gemini", model: normalize(decodeURIComponent(gemini[1])) }; } catch { return null; }
99
+ }
100
+ }
101
+ if (url.pathname.endsWith("/responses")) return { protocol: "responses" };
102
+ if (url.pathname.endsWith("/chat/completions")) return { protocol: "chat" };
103
+ if (url.pathname.endsWith("/messages")) return { protocol: "anthropic" };
104
+ return null;
105
+ }
106
+
107
+ function hasResponsesPartOutput(part) {
108
+ if (!part || typeof part !== "object") return true;
109
+ if (!["output_text", "summary_text", "refusal"].includes(part.type)) return true;
110
+ if (Object.keys(part).some(key => !["type", "text", "refusal", "annotations", "logprobs"].includes(key))) return true;
111
+ return (part.text !== undefined && (typeof part.text !== "string" || part.text.length > 0)) ||
112
+ (part.refusal !== undefined && (typeof part.refusal !== "string" || part.refusal.length > 0)) ||
113
+ (part.annotations !== undefined && (!Array.isArray(part.annotations) || part.annotations.length > 0)) ||
114
+ (part.logprobs !== undefined && (!Array.isArray(part.logprobs) || part.logprobs.length > 0));
115
+ }
116
+
117
+ function hasResponsesItemOutput(item) {
118
+ if (!item || typeof item !== "object") return true;
119
+ if (item.type !== "message" && item.type !== "reasoning") return true;
120
+ if (Object.keys(item).some(key => !["type", "id", "role", "status", "content", "summary"].includes(key))) return true;
121
+ for (const key of ["content", "summary"]) {
122
+ if (item[key] !== undefined && (!Array.isArray(item[key]) || item[key].some(hasResponsesPartOutput))) return true;
123
+ }
124
+ return false;
125
+ }
126
+
127
+ function inspectPayload(payload, protocol, result, event = "") {
128
+ if (Array.isArray(payload)) {
129
+ for (const entry of payload) inspectPayload(entry, protocol, result, event);
130
+ return;
131
+ }
132
+ if (!payload || typeof payload !== "object") return;
133
+ const failure = event === "error" || event === "response.failed" || payload.type === "error" ||
134
+ payload.type === "response.failed" || payload.error != null || payload.response?.error != null ||
135
+ (protocol === "responses" && payload.status === "failed") ||
136
+ payload.response?.status === "failed";
137
+ if (failure) result.upstreamFailure = true;
138
+ // Named diagnostic/tool events are not model declarations.
139
+ if (event && event !== "message" && event !== "error" &&
140
+ !(protocol === "responses" && event.startsWith("response.")) &&
141
+ !(protocol === "anthropic" && /^(?:message_|content_block_|ping$)/.test(event))) return;
142
+ if (!failure && typeof payload.type === "string" &&
143
+ ((protocol === "responses" && !payload.type.startsWith("response.")) ||
144
+ (protocol === "anthropic" && !/^(?:message(?:_|$)|content_block_|ping$)/.test(payload.type)))) return;
145
+ const hasOutput = protocol === "gemini" ? Array.isArray(payload.candidates) && payload.candidates.some(item => item?.content?.parts?.length > 0)
146
+ : protocol === "responses" ? (typeof payload.delta === "string" && payload.delta.length > 0) ||
147
+ (payload.item != null && hasResponsesItemOutput(payload.item)) ||
148
+ (payload.part != null && hasResponsesPartOutput(payload.part)) ||
149
+ (Array.isArray(payload.output) ? payload.output.some(hasResponsesItemOutput) : payload.output != null) ||
150
+ (Array.isArray(payload.response?.output) ? payload.response.output.some(hasResponsesItemOutput) : payload.response?.output != null)
151
+ : protocol === "anthropic" ? payload.content?.length > 0 || payload.message?.content?.length > 0 ||
152
+ payload.content_block != null || payload.delta != null
153
+ : Array.isArray(payload.choices) && payload.choices.some(choice => {
154
+ const item = choice?.delta ?? choice?.message;
155
+ return item && (item.content || item.refusal || item.reasoning || item.reasoning_content ||
156
+ item.tool_calls?.length > 0 || item.function_call);
157
+ });
158
+ if (hasOutput) result.sawOutput = true;
159
+ const candidates = protocol === "gemini" ? [payload.modelVersion]
160
+ : protocol === "responses" ? [payload.model, payload.response?.model]
161
+ : protocol === "anthropic" ? [payload.model, (payload.type === "message_start" || event === "message_start") ? payload.message?.model : undefined]
162
+ : [payload.model];
163
+ for (const candidate of candidates) {
164
+ const model = normalize(candidate);
165
+ const models = failure ? result.failureModels : result.models;
166
+ if (model && !models.includes(model)) models.push(model);
167
+ }
168
+ }
169
+
170
+ function inspectSse(text, protocol, result) {
171
+ let name = "", data = "", hasData = false;
172
+ function dispatch() {
173
+ if (name === "error" || name === "response.failed") result.upstreamFailure = true;
174
+ if (data && data !== "[DONE]") {
175
+ let payload;
176
+ try { payload = JSON.parse(data); } catch { /* Preserve unknown protocol data. */ }
177
+ inspectPayload(payload, protocol, result, name);
178
+ }
179
+ name = ""; data = ""; hasData = false;
180
+ }
181
+ // Includes CRLF/CR/LF, multiline data, last event field and a final frame
182
+ // without a newline. Comments and text inside tool/answer bodies are ignored.
183
+ function line(line) {
184
+ if (!line) { dispatch(); return; }
185
+ const colon = line.indexOf(":");
186
+ const field = colon < 0 ? line : line.slice(0, colon);
187
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
188
+ if (field === "event") name = value;
189
+ if (field === "data") { data += (hasData ? "\n" : "") + value; hasData = true; }
190
+ }
191
+ const newline = /\r\n|\r|\n/g;
192
+ let start = 0, match;
193
+ while ((match = newline.exec(text))) {
194
+ line(text.slice(start, match.index));
195
+ start = newline.lastIndex;
196
+ }
197
+ if (start < text.length) line(text.slice(start));
198
+ dispatch();
199
+ }
200
+
201
+ async function inspectResponse(response, protocol, limits) {
202
+ const type = response.headers.get("content-type") ?? "";
203
+ if (response.status !== 200 || !/text\/event-stream|\bjson\b/i.test(type)) return { response };
204
+ const bytes = await readBytes(response.body, limits);
205
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
206
+ const result = { models: [], failureModels: [], sawOutput: false, upstreamFailure: false };
207
+ if (/text\/event-stream/i.test(type)) inspectSse(text, protocol, result);
208
+ else {
209
+ let payload;
210
+ try { payload = JSON.parse(text); } catch { /* Let the client handle invalid JSON. */ }
211
+ inspectPayload(payload, protocol, result);
212
+ }
213
+ const headers = new Headers(response.headers);
214
+ // fetch may have decoded compression. The reconstructed body has its own
215
+ // framing, so wire encoding/length must not be advertised on the replay.
216
+ for (const name of ["content-length", "content-encoding", "transfer-encoding"]) headers.delete(name);
217
+ return {
218
+ ...result,
219
+ response: new Response(bytes, { status: response.status, statusText: response.statusText, headers }),
220
+ };
221
+ }
222
+
223
+ export async function fetchWithModelGuard(target, init = {}, {
224
+ enabled = true, maxAttempts = DEFAULT_MAX_ATTEMPTS, maxBytes = MAX_BYTES, timeoutMs = INSPECTION_MS,
225
+ } = {}) {
226
+ if (!enabled) return fetch(target, init);
227
+ const attemptLimit = modelAttemptLimit(maxAttempts);
228
+ const route = requestRoute(target, init);
229
+ if (!route) return fetch(target, init);
230
+ const signal = init.signal ?? (target instanceof Request ? target.signal : undefined);
231
+ const limits = { signal, maxBytes, timeoutMs };
232
+ let prepared = init;
233
+ let sending = false;
234
+ try {
235
+ stopped(signal);
236
+ const headers = new Headers(target instanceof Request ? target.headers : undefined);
237
+ new Headers(init.headers ?? {}).forEach((value, key) => headers.set(key, value));
238
+ // Gemini identifies its model in the URL. Other compressed or non-JSON
239
+ // request bodies have no inspectable requested ID and keep passthrough.
240
+ const encoded = headers.has("content-encoding") && headers.get("content-encoding").toLowerCase() !== "identity";
241
+ if (encoded && !route.model) {
242
+ sending = true;
243
+ return await fetch(target, init);
244
+ }
245
+ const mediaType = headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
246
+ if (!route.model && mediaType && mediaType !== "application/json" && !mediaType.endsWith("+json")) {
247
+ sending = true;
248
+ return await fetch(target, init);
249
+ }
250
+ const body = await snapshotBody(target, init, limits);
251
+ if (body != null) prepared = { ...init, body };
252
+ if (!route.model) {
253
+ const text = await bodyText(body);
254
+ let json;
255
+ if (text != null) {
256
+ try { json = JSON.parse(text); } catch { /* No identifiable model. */ }
257
+ }
258
+ route.model = normalize(json?.model);
259
+ }
260
+ // Missing metadata is inconclusive, never a reason to retry.
261
+ if (!route.model) {
262
+ sending = true;
263
+ return await fetch(target, prepared);
264
+ }
265
+ const actualModels = [];
266
+ for (let attempt = 1; attempt <= attemptLimit; attempt++) {
267
+ stopped(signal);
268
+ sending = true;
269
+ const upstream = await fetch(target, prepared);
270
+ sending = false;
271
+ const inspected = await inspectResponse(upstream, route.protocol, limits);
272
+ stopped(signal);
273
+ const declaredModels = inspected.upstreamFailure
274
+ ? (inspected.sawOutput ? [...(inspected.models ?? []), ...(inspected.failureModels ?? [])] : [])
275
+ : (inspected.models ?? []);
276
+ const mismatch = declaredModels.find(model => model !== route.model);
277
+ if (!mismatch) return inspected.response;
278
+ actualModels.push(mismatch);
279
+ if (inspected.upstreamFailure) return terminal("agentrouter_model_mismatch",
280
+ `AgentRouter 返回了不匹配的模型(请求 ${route.model},实际 ${mismatch}),随后上游报告错误。已丢弃整条回答并停止,未继续重试。`,
281
+ { requested_model: route.model, actual_model: mismatch, actual_models: actualModels,
282
+ attempts: attempt, upstream_failure: true });
283
+ // The complete upstream body was consumed and none of its bytes escaped.
284
+ if (attempt === attemptLimit) return terminal("agentrouter_model_mismatch",
285
+ `AgentRouter 连续 ${attemptLimit} 次返回了不匹配的模型:请求 ${route.model},实际 ${mismatch}。已丢弃全部错配回答并停止。`,
286
+ { requested_model: route.model, actual_model: mismatch, actual_models: actualModels, attempts: attempt });
287
+ }
288
+ } catch (error) {
289
+ stopped(signal);
290
+ if (sending) throw error; // Preserve existing transport-error handling.
291
+ if (!(error instanceof InspectionError)) {
292
+ // Transport/read/decode failures also stop; partial output is never safe.
293
+ return terminal("agentrouter_model_inspection_failed", "AgentRouter 模型校验未能完整读取响应,已丢弃本次回答并停止。");
294
+ }
295
+ return terminal("agentrouter_model_inspection_failed", `${error.message},已停止,未放行未校验的回答。`);
296
+ }
297
+ }
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "opencode-agentrouter-auth",
3
- "version": "0.1.12",
4
- "description": "适用于 magpie 和 OpenCode 的 AgentRouter 插件:国际/国内站选择、API Key/GitHub/系统访问令牌登录、自定义请求头、余额与签到、上游 Gemini Native 自动适配、文字替换、历史内联及可选的 Codex 会话资源清理",
3
+ "version": "0.1.13",
4
+ "description": "适用于 magpie 和 OpenCode 的 AgentRouter 插件:国际/国内站选择、API Key/GitHub/系统访问令牌登录、自定义请求头、余额与签到、实际模型校验、上游 Gemini Native 自动适配、文字替换、历史内联及可选的 Codex 会话资源清理",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "scripts": {
8
8
  "test:policy": "node --test .github/scripts/pr-policy.test.cjs",
9
- "test": "node --test body-inspection.test.mjs usage.test.mjs loader-stream.test.mjs response-bounds.test.mjs checkin.test.mjs local-checkin.test.mjs local-checkin.integration.test.mjs windows-acl.test.mjs request-replay.test.mjs content-filter.test.mjs auth-guidance.test.mjs auth-flow.test.mjs resource-compat.test.mjs auth-request-boundary.test.mjs response-preservation.test.mjs session-repair.test.mjs gemini-compat.test.mjs",
9
+ "test": "node --test body-inspection.test.mjs usage.test.mjs loader-stream.test.mjs response-bounds.test.mjs checkin.test.mjs local-checkin.test.mjs local-checkin.integration.test.mjs windows-acl.test.mjs request-replay.test.mjs content-filter.test.mjs auth-guidance.test.mjs auth-flow.test.mjs resource-compat.test.mjs auth-request-boundary.test.mjs response-preservation.test.mjs session-repair.test.mjs gemini-compat.test.mjs model-guard.test.mjs",
10
+ "test:model-guard": "node --test model-guard.test.mjs",
10
11
  "test:gemini": "node --test gemini-compat.test.mjs",
11
12
  "test:session-repair": "node --test session-repair.test.mjs",
12
13
  "test:headers": "python3 set-ar-headers.test.py"
@@ -14,6 +15,8 @@
14
15
  "exports": "./index.mjs",
15
16
  "files": [
16
17
  "index.mjs",
18
+ "model-guard.mjs",
19
+ "ui",
17
20
  "response.mjs",
18
21
  "request.mjs",
19
22
  "session-repair.mjs",
@@ -43,9 +46,18 @@
43
46
  "url": "git+https://github.com/ZhaoJun233/agentrouter-magpie-plugin.git"
44
47
  },
45
48
  "magpie": {
49
+ "panels": [
50
+ {
51
+ "slot": "provider",
52
+ "file": "ui/model-guard.html",
53
+ "title": "实际模型校验"
54
+ }
55
+ ],
46
56
  "maxConcurrency": 2,
47
57
  "options": {
48
- "retryAfterSeconds": 10
58
+ "retryAfterSeconds": 10,
59
+ "modelGuardEnabled": true,
60
+ "maxModelAttempts": 3
49
61
  }
50
62
  }
51
63
  }
@@ -0,0 +1,123 @@
1
+ :root {
2
+ color-scheme: light dark;
3
+ }
4
+
5
+ body {
6
+ margin: 0;
7
+ padding: 14px 16px;
8
+ color: var(--magpie-fg, CanvasText);
9
+ background: var(--magpie-bg, Canvas);
10
+ font: 13px/1.5 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);
11
+ }
12
+
13
+ .panel-form {
14
+ max-width: 640px;
15
+ }
16
+
17
+ fieldset {
18
+ min-width: 0;
19
+ margin: 0;
20
+ padding: 0;
21
+ border: 0;
22
+ }
23
+
24
+ [hidden] {
25
+ display: none !important;
26
+ }
27
+
28
+ .switch-row {
29
+ display: flex;
30
+ align-items: flex-start;
31
+ justify-content: space-between;
32
+ gap: 20px;
33
+ cursor: pointer;
34
+ }
35
+
36
+ .control-title {
37
+ display: block;
38
+ font-weight: 600;
39
+ }
40
+
41
+ .control-description {
42
+ display: block;
43
+ margin: 5px 0 0;
44
+ color: var(--magpie-muted, GrayText);
45
+ font-size: 12px;
46
+ }
47
+
48
+ input[type="checkbox"] {
49
+ flex: 0 0 auto;
50
+ width: 18px;
51
+ height: 18px;
52
+ margin: 2px 0 0;
53
+ accent-color: var(--magpie-accent, Highlight);
54
+ }
55
+
56
+ .attempts-row {
57
+ display: grid;
58
+ grid-template-columns: minmax(0, 1fr) auto;
59
+ align-items: center;
60
+ column-gap: 20px;
61
+ margin-top: 16px;
62
+ }
63
+
64
+ .attempts-row p {
65
+ grid-column: 1 / -1;
66
+ }
67
+
68
+ input[type="number"] {
69
+ box-sizing: border-box;
70
+ width: 100px;
71
+ min-height: 34px;
72
+ padding: 5px 8px;
73
+ border: 1px solid var(--magpie-line, ButtonBorder);
74
+ border-radius: 6px;
75
+ color: inherit;
76
+ background: var(--magpie-card, var(--magpie-bg, Canvas));
77
+ font: inherit;
78
+ }
79
+
80
+ .actions {
81
+ margin-top: 16px;
82
+ }
83
+
84
+ button {
85
+ min-height: 32px;
86
+ padding: 5px 12px;
87
+ border: 1px solid var(--magpie-line, ButtonBorder);
88
+ border-radius: 6px;
89
+ color: inherit;
90
+ background: var(--magpie-card, var(--magpie-bg, Canvas));
91
+ font: inherit;
92
+ cursor: pointer;
93
+ }
94
+
95
+ input:focus-visible,
96
+ button:focus-visible {
97
+ outline: 2px solid var(--magpie-accent, Highlight);
98
+ outline-offset: 2px;
99
+ }
100
+
101
+ input[aria-invalid="true"] {
102
+ border-color: var(--magpie-red, #c23232);
103
+ }
104
+
105
+ fieldset:disabled .switch-row,
106
+ button:disabled {
107
+ cursor: default;
108
+ }
109
+
110
+ button:disabled {
111
+ opacity: 0.6;
112
+ }
113
+
114
+ .status {
115
+ min-height: 1.5em;
116
+ margin: 10px 0 0;
117
+ color: var(--magpie-muted, GrayText);
118
+ font-size: 12px;
119
+ }
120
+
121
+ .status[data-error="true"] {
122
+ color: var(--magpie-red, #c23232);
123
+ }
@@ -0,0 +1,36 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>实际模型校验</title>
7
+ <link rel="stylesheet" href="model-guard.css">
8
+ <script src="_magpie/bridge.js"></script>
9
+ <script src="model-guard.js" defer></script>
10
+ </head>
11
+ <body>
12
+ <div id="model-guard-form" class="panel-form" role="region" aria-label="实际模型校验">
13
+ <fieldset id="model-guard-controls" disabled>
14
+ <label class="switch-row" for="model-guard-enabled">
15
+ <span>
16
+ <span class="control-title">校验实际返回模型</span>
17
+ <span class="control-description" id="model-guard-description">开启后先完整接收并校验回答,发现模型不匹配就丢弃并重新请求。</span>
18
+ </span>
19
+ <input id="model-guard-enabled" type="checkbox" role="switch" aria-describedby="model-guard-description" aria-controls="model-guard-attempts-row">
20
+ </label>
21
+
22
+ <div id="model-guard-attempts-row" class="attempts-row" hidden>
23
+ <label class="control-title" for="max-model-attempts">最多请求次数</label>
24
+ <input id="max-model-attempts" name="maxModelAttempts" type="number" min="2" step="1" inputmode="numeric" value="3" aria-describedby="attempts-help attempts-summary" disabled>
25
+ <p id="attempts-help" class="control-description">最小 2,默认 3;也可填写 5、10 等更大的整数。次数包含首次请求,匹配后立即返回。</p>
26
+ <p id="attempts-summary" class="control-description"></p>
27
+ </div>
28
+
29
+ <div class="actions">
30
+ <button id="save-model-guard" type="button">保存设置</button>
31
+ </div>
32
+ </fieldset>
33
+ <p id="model-guard-status" class="status" role="status" aria-live="polite" aria-atomic="true">正在读取设置…</p>
34
+ </div>
35
+ </body>
36
+ </html>
@@ -0,0 +1,134 @@
1
+ (() => {
2
+ "use strict";
3
+
4
+ const controls = document.getElementById("model-guard-controls");
5
+ const enabled = document.getElementById("model-guard-enabled");
6
+ const attemptsRow = document.getElementById("model-guard-attempts-row");
7
+ const attempts = document.getElementById("max-model-attempts");
8
+ const summary = document.getElementById("attempts-summary");
9
+ const save = document.getElementById("save-model-guard");
10
+ const status = document.getElementById("model-guard-status");
11
+ let ready = false;
12
+ let saving = false;
13
+ let lastValidAttempts = 3;
14
+
15
+ const validAttempts = value => Number.isSafeInteger(value) && value >= 2;
16
+ const optionObject = value => value && typeof value === "object" && !Array.isArray(value) ? value : {};
17
+
18
+ // Keep the saved-option display in sync with the runtime's modelAttemptLimit.
19
+ // This normalization is only for stored values; invalid user edits are rejected.
20
+ function storedAttempts(value) {
21
+ const parsed = typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value;
22
+ return typeof parsed === "number" && Number.isSafeInteger(parsed) ? Math.max(2, parsed) : 3;
23
+ }
24
+
25
+ function readAttempts() {
26
+ const text = attempts.value.trim();
27
+ if (!/^\d+$/.test(text)) return null;
28
+ const value = Number(text);
29
+ return validAttempts(value) ? value : null;
30
+ }
31
+
32
+ function message(text, error = false) {
33
+ status.dataset.error = String(error);
34
+ status.setAttribute("role", error ? "alert" : "status");
35
+ status.setAttribute("aria-live", error ? "assertive" : "polite");
36
+ status.textContent = text;
37
+ }
38
+
39
+ function render() {
40
+ controls.disabled = !ready || saving;
41
+ attemptsRow.hidden = !enabled.checked;
42
+ attempts.disabled = !enabled.checked || !ready || saving;
43
+ attempts.required = enabled.checked;
44
+ const value = readAttempts();
45
+ summary.textContent = value === null
46
+ ? "请输入不小于 2 的整数。"
47
+ : `当前设置为 ${value} 次,即首次请求加最多 ${value - 1} 次重试。`;
48
+ save.textContent = saving ? "正在保存…" : "保存设置";
49
+ }
50
+
51
+ enabled.addEventListener("change", () => {
52
+ if (!enabled.checked) attempts.removeAttribute("aria-invalid");
53
+ message("设置尚未保存。");
54
+ render();
55
+ });
56
+
57
+ attempts.addEventListener("input", () => {
58
+ const value = readAttempts();
59
+ if (value !== null) lastValidAttempts = value;
60
+ attempts.removeAttribute("aria-invalid");
61
+ message("设置尚未保存。");
62
+ render();
63
+ });
64
+
65
+ // Magpie frames panels with sandbox="allow-scripts" (no allow-forms) and
66
+ // form-action 'none', so use explicit click/Enter handlers instead of form submit.
67
+ async function saveSettings() {
68
+ if (!ready || saving) return;
69
+ const requestedAttempts = readAttempts();
70
+ if (enabled.checked && requestedAttempts === null) {
71
+ attempts.setAttribute("aria-invalid", "true");
72
+ message("最多请求次数必须是不小于 2 的整数。", true);
73
+ attempts.focus();
74
+ return;
75
+ }
76
+ const nextEnabled = enabled.checked;
77
+ // Turning the feature off must remain possible with an invalid hidden field.
78
+ const nextAttempts = requestedAttempts ?? lastValidAttempts;
79
+ saving = true;
80
+ message("正在保存设置…");
81
+ render();
82
+ try {
83
+ const latest = optionObject(await window.magpie.options.get());
84
+ await window.magpie.options.set({
85
+ ...latest,
86
+ modelGuardEnabled: nextEnabled,
87
+ maxModelAttempts: nextAttempts,
88
+ });
89
+ lastValidAttempts = nextAttempts;
90
+ attempts.value = String(nextAttempts);
91
+ attempts.removeAttribute("aria-invalid");
92
+ message("设置已保存,下一次请求生效。");
93
+ } catch {
94
+ // Preserve the user's values so a failed save can be retried.
95
+ message("保存失败,设置尚未生效。请稍后再点击“保存设置”。", true);
96
+ } finally {
97
+ saving = false;
98
+ render();
99
+ }
100
+ }
101
+
102
+ save.addEventListener("click", () => {
103
+ void saveSettings();
104
+ });
105
+
106
+ attempts.addEventListener("keydown", event => {
107
+ if (event.key !== "Enter") return;
108
+ event.preventDefault();
109
+ void saveSettings();
110
+ });
111
+
112
+ async function initialize() {
113
+ try {
114
+ const bridge = window.magpie;
115
+ if (!bridge || !bridge.ready || typeof bridge.options?.get !== "function" ||
116
+ typeof bridge.options?.set !== "function") {
117
+ throw new Error("Panel bridge unavailable");
118
+ }
119
+ await bridge.ready;
120
+ const options = optionObject(await bridge.options.get());
121
+ enabled.checked = options.modelGuardEnabled !== false;
122
+ lastValidAttempts = storedAttempts(options.maxModelAttempts);
123
+ attempts.value = String(lastValidAttempts);
124
+ ready = true;
125
+ message("修改后点击“保存设置”,下一次请求生效。");
126
+ } catch {
127
+ message("无法读取设置。请在 Magpie 的 AgentRouter 编辑页打开此面板,或重新加载插件后再试。", true);
128
+ }
129
+ render();
130
+ }
131
+
132
+ render();
133
+ void initialize();
134
+ })();