opencode-anyrouter-auth 0.0.0-stage → 0.1.1

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/DESIGN.md ADDED
@@ -0,0 +1,255 @@
1
+ # AnyRouter provider: implementation contract
2
+
3
+ This document describes the behavior this package implements. It is not a
4
+ claim that live site policy, WAF settings or Turnstile availability will remain
5
+ stable.
6
+
7
+ ## Requirements
8
+
9
+ | ID | Requirement | Acceptance evidence |
10
+ | --- | --- | --- |
11
+ | R1 | Expose password, GitHub, LinuxDO, browser-session, system access-token and model API-key login paths. Ask only questions relevant to the selected path. | Prompt and authorize tests, plus an isolated Magpie host login. |
12
+ | R2 | Treat AnyRouter login and daily check-in as separate operations. | Site-client and provider tests assert `sign_in` is called explicitly after password or session setup. |
13
+ | R3 | Make unattended check-in opt-in and require a site password or imported session. | Disabled, missing-credential, wrong-user, captcha, inactive, failed and daily-deduplication tests. |
14
+ | R4 | Use `anyrouter.top` for login and every site API. Allow only `anyrouter.top` or the confirmed `fcapp.run` endpoint for model API traffic. | URL-boundary, session-origin, WAF-cookie and migration tests. |
15
+ | R5 | Use native Magpie account records, account selection and failover. Do not build a hidden account pool in `fetch`. | Concurrent-account tests and installed-gateway failover test. |
16
+ | R6 | Keep site credentials and model keys separate. Never send cookies, passwords, system tokens or `New-API-User` to inference endpoints. | Header-boundary and selected-account tests. |
17
+ | R7 | Preserve model/request overrides, discover models per account and do not invent default models or limits. | Catalog, model-metadata and protocol-family tests. |
18
+ | R8 | Protect Responses, Chat Completions, Anthropic Messages and Gemini, streaming and non-streaming. | Protocol fixtures, compressed HTTP/SSE tests, cancellation and deadline tests. |
19
+ | R9 | Preserve the first request body; repair only exact recoverable Responses history errors; retry within the AnyRouter budget. | Byte-level preservation, negative classification, retry-budget and failed-output tests. |
20
+ | R10 | Do not expose secrets or request bodies in logs; do not modify other providers or host configuration. | Config-isolation, log-redaction and source-inspection tests. |
21
+ | R11 | Remain portable across Node and Bun without a separate proxy or OS-specific command dependency. | Node suite, installed host test and installed gateway test. |
22
+
23
+ ## Research conclusion
24
+
25
+ The AnyRouter frontend does not use a successful login response as proof of
26
+ daily check-in. The observed contract is:
27
+
28
+ ```text
29
+ password check-in:
30
+ GET /login (only when WAF bootstrap is needed)
31
+ GET /api/status
32
+ POST /api/user/login?turnstile=
33
+ POST /api/user/sign_in body: {}
34
+
35
+ session check-in:
36
+ GET /api/user/self
37
+ POST /api/user/sign_in body: {}
38
+ ```
39
+
40
+ The WAF fallback first performs one navigation-style `/login` request to collect
41
+ the same anonymous cookies a browser obtains before login. If the response is a
42
+ recognized AnyRouter `acw_sc__v2` JS challenge, the plugin executes only that
43
+ bounded inline script in an isolated VM with no network, filesystem or process
44
+ objects, captures the challenge-set cookie, and retries once. It never loops or
45
+ tries to solve Turnstile. If the challenge cannot be completed, the request is
46
+ reported as requiring the browser-session handoff.
47
+
48
+ `sign_in` is a separate site request. It carries the selected site session,
49
+ `New-API-User` and `X-Requested-With: XMLHttpRequest`; it must not carry the
50
+ model API key as `Authorization`. This differs from the AgentRouter baseline,
51
+ where the login response's `checked_in` field can describe the daily result.
52
+
53
+ `/api/status` currently exposes a dynamic `turnstile_check` flag. When it is
54
+ true, password login is refused before credentials are sent. The plugin does
55
+ not solve Turnstile. A recognized AnyRouter `acw_sc__v2` inline challenge is
56
+ executed in the bounded isolated VM described above; other WAF challenges use
57
+ the browser-session handoff.
58
+
59
+ ## Ownership and modules
60
+
61
+ - Magpie owns account storage, account selection, concurrency, routing,
62
+ cross-account failover and check-in scheduling.
63
+ - `index.mjs` assembles provider hooks and wraps only this provider's inference
64
+ transport with the request filter.
65
+ - `lib/accounts.mjs` owns versioned credentials, site selection, UID identity,
66
+ migration and capability calculation.
67
+ - `lib/site-client.mjs` owns status, password login, profile reads, session
68
+ handoff, key lookup and `sign_in`. It is not wrapped by inference retries.
69
+ - `lib/provider.mjs` owns login UX, account persistence, usage and check-in
70
+ orchestration.
71
+ - `lib/catalog.mjs` and `lib/model-metadata.mjs` own model discovery and
72
+ per-field metadata resolution.
73
+ - `lib/responses-filter.mjs` and `lib/protocols.mjs` own one selected-provider
74
+ attempt, protocol completion checks and permitted retries/cleanup.
75
+
76
+ ## Authentication and persistence
77
+
78
+ The six methods are independent native buttons:
79
+
80
+ | Mode | Check-in capability | Site reads | Persistent site secret |
81
+ | --- | --- | --- | --- |
82
+ | Password, check-in off | No | Read-only session | Session and selected model key; password is not persisted |
83
+ | Password, check-in on | Yes | Read-only session | Session, selected model key, username and explicitly authorized password |
84
+ | GitHub | Optional opt-in | Read-only session | Imported AnyRouter session and selected model key |
85
+ | LinuxDO | Optional opt-in | Read-only session | Imported AnyRouter session and selected model key |
86
+ | Browser session | Optional opt-in | Read-only session | Imported AnyRouter session and selected model key |
87
+ | System access token | No | Read-only, if accepted | Site token, numeric user ID and selected model key |
88
+ | Model API key | No | No site reads | Inference key only |
89
+
90
+ Password login performs `status -> login -> profile -> key lookup`. The login
91
+ response is checked against the profile UID before persistence. If the site
92
+ returns `turnstile_check: true`, no password request is sent.
93
+
94
+ GitHub, LinuxDO and browser-session methods complete login in the user's
95
+ browser. The user supplies a `/api/user/self` request copied as cURL or a JSON
96
+ session export. Clipboard text is parsed as data, never executed. Only known
97
+ AnyRouter origins, a `session` Cookie, optional WAF cookies and a numeric
98
+ `New-Api-User` are accepted. The plugin performs a read-only profile request and
99
+ requires the returned UID to match the selected account.
100
+
101
+ The account's site UID is authoritative. Reauthentication, profile refresh and
102
+ check-in must not replace it with another user's data. A display alias is not
103
+ an account identity. New account names use the verified profile email, then
104
+ username, then UID; legacy remarks remain labels and are not promoted to email.
105
+
106
+ Read existing model keys only. Use the sole active key or an explicitly selected
107
+ numeric key ID. Never call the system-token reset endpoint, create a key, rotate
108
+ a key or delete a key implicitly. A keyless but otherwise successful site login
109
+ is not a usable inference account.
110
+
111
+ ## Site and model API endpoints
112
+
113
+ The only supported site origin for login, session import, profile reads, key
114
+ lookup, usage and check-in is:
115
+
116
+ - `https://anyrouter.top`
117
+
118
+ Model API traffic may use either confirmed endpoint:
119
+
120
+ - `https://anyrouter.top`
121
+ - `https://a-ocnfniawgw.cn-shanghai.fcapp.run`
122
+
123
+ The account stores the selected model API endpoint separately from the fixed
124
+ site URL. Selecting the `fcapp.run` API endpoint must not change login, session
125
+ handoff, profile, key lookup, usage or check-in traffic. Site credentials are
126
+ not copied into inference credentials. Explicit user model API overrides remain
127
+ available for manually declared models, but they do not change the fixed site
128
+ origin.
129
+
130
+ An account selects one model API endpoint. Retries stay on that endpoint;
131
+ cross-endpoint replay is deliberately excluded to avoid duplicate inference
132
+ charges. Magpie's native cross-account failover remains available.
133
+
134
+ Cookie merging is case-preserving for values and handles `Set-Cookie` rotation,
135
+ expiry and deletion. Site requests use Chrome-style browser headers with the
136
+ `anyrouter.top` `Origin`/`Referer`, including Chrome client hints. These headers
137
+ are best-effort only: they do not emulate a browser TLS fingerprint. A
138
+ recognized `acw_sc__v2` inline challenge is executed in the bounded isolated VM,
139
+ then retried once with the cookie it sets. Unrecognized WAF challenges remain
140
+ manual-action errors and are not retried in a background loop.
141
+
142
+ ## Check-in and balances
143
+
144
+ Check-in requires an explicit account opt-in, a verified UID and either a saved
145
+ password or an imported session. Magpie schedules the call; the plugin has no
146
+ independent timer.
147
+
148
+ For password mode, check-in logs in and verifies the profile before calling
149
+ `sign_in`. For session mode, it verifies the profile with a read-only request
150
+ before calling `sign_in`. The returned session cookies are merged only after
151
+ the account identity is rechecked.
152
+
153
+ Terminal outcomes are `claimed`, `done`, `captcha`, `inactive` and `ineligible`.
154
+ They are deduplicated for the same site UID and Beijing calendar day. A
155
+ `failed` outcome, including an HTTP-200 `success:false` response, is not marked
156
+ complete and is not persisted as a daily result, so a later scheduled attempt
157
+ may retry it. Concurrent calls for the same account/day are coalesced.
158
+
159
+ Usage is read-only. It never falls back to a password login. A missing quota,
160
+ WAF block or site failure produces an unknown balance, not zero. The wallet
161
+ balance may inform native routing, but check-in rewards do not create a fake
162
+ midnight reset window.
163
+
164
+ ## Models and request boundaries
165
+
166
+ No model is enabled by default. Official AnyRouter endpoints discover models
167
+ through `https://anyrouter.top/api/pricing`, using `model_name` as the model ID,
168
+ without probing `/v1/models`. Discovery uses the account's site session or system
169
+ access token plus `New-Api-User` when available; API-key-only accounts read
170
+ anonymously. Inference keys are never sent to the pricing endpoint, and choosing
171
+ the alternate inference endpoint does not move site discovery there.
172
+
173
+ Pricing supplies catalog entries and their metadata, not a guarantee of API-key
174
+ permissions; actual inference still enforces those permissions. Public registry
175
+ metadata only enriches discovered or explicitly configured models. A pricing
176
+ failure preserves explicitly configured models with the host fallback marker,
177
+ without declaring the inference key expired. Custom non-official gateways retain
178
+ their `/models` discovery, with pricing used only for metadata enrichment.
179
+
180
+ Protocol defaults:
181
+
182
+ - `claude-*` and `*-cc-format`: Anthropic Messages.
183
+ - `gemini-*`: Gemini.
184
+ - Other names: Responses.
185
+
186
+ Explicit user model, SDK and API settings take precedence. Metadata resolution
187
+ is field-wise: user declaration, authenticated discovery, provider pricing,
188
+ corresponding registry, exact manufacturer model, conservative family
189
+ consensus, then host fallback. `context`, `input` and `output` remain distinct.
190
+ The registry must not invent an input ceiling or an effort tier.
191
+
192
+ Native request headers are authoritative overrides. Account headers fill missing
193
+ fields but are not merged across models. The plugin selects the inference auth
194
+ header from the outgoing protocol and never forwards site credentials. It may
195
+ restore the codex client identity for Responses when compatibility headers are
196
+ enabled, but account overrides still win.
197
+
198
+ ## AnyRouter retry policy
199
+
200
+ `index.mjs` selects the `anyrouter` profile by default:
201
+
202
+ | Category | Maximum additional retries | Base delays |
203
+ | --- | ---: | --- |
204
+ | Resource/history mismatch | 1 | 1 s |
205
+ | Rate limit | 3 | 2, 5, 10 s plus jitter |
206
+ | Transport | 4 | 1, 2, 4, 8 s |
207
+ | Availability | 2 | 5, 15 s |
208
+ | Total | 8 | bounded by the total deadline |
209
+
210
+ `Retry-After`, `retry-after-ms` and `x-ms-retry-after-ms` are lower bounds.
211
+ An empty `429` response is classified as a rate-limit retry; empty `503` and
212
+ `504` responses are availability retries. A JSON quota, authentication,
213
+ permission or model error is not retried merely because its HTTP status is
214
+ 429/5xx. AnyRouter failover across accounts remains a separate Magpie operation.
215
+
216
+ ## Transport invariants
217
+
218
+ 1. Preserve the original body for the first request and for ordinary retries.
219
+ 2. Only an exact Responses resource/history error can authorize cleanup.
220
+ 3. Keep portable message/tool pairs. Refuse references, compaction or encrypted
221
+ items that cannot be reconstructed instead of silently dropping context.
222
+ 4. Do not apply Responses cleanup to Chat, Anthropic or Gemini. Do not guess
223
+ thinking/signature repairs.
224
+ 5. Hold SSE content and client tool calls until a protocol-valid terminal event.
225
+ Discard all failed-attempt output. A legitimate refusal or length stop is
226
+ terminal, not a transport failure.
227
+ 6. Keep usage trailers where the protocol requires them. Comments alone do not
228
+ count as Codex SSE activity; non-content progress events are used while
229
+ buffering.
230
+ 7. Keepalive does not reset the upstream idle or total deadline. Cancellation
231
+ aborts both reading and backoff.
232
+ 8. Fast failures preserve status and routing headers. After SSE commitment,
233
+ late failures are encoded in-band with their original status/code; never
234
+ append bare JSON or fake completion.
235
+ 9. Bound request and response memory. Oversize output fails without delivering a
236
+ partial winning stream.
237
+ 10. Retrying can duplicate upstream inference or hosted-tool side effects; the
238
+ plugin does not claim exactly-once execution.
239
+
240
+ ## Release gates
241
+
242
+ - [x] Versioned account state, six login paths and conditional check-in persistence.
243
+ - [x] Independent `sign_in`, UID checks, Beijing-day deduplication and failed-result retry behavior.
244
+ - [x] Fixed `anyrouter.top` site traffic, two confirmed model API endpoints and WAF cookie handling.
245
+ - [x] Responses, Chat, Anthropic and Gemini protection with bounded AnyRouter retries.
246
+ - [x] Node unit/integration suite passes.
247
+ - [x] Installed Magpie host integration passes with isolated HOME.
248
+ - [x] Installed Magpie gateway integration passes with isolated HOME and account failover.
249
+ - [ ] Live AnyRouter password/GitHub/LinuxDO/check-in validation with a real account.
250
+ - [x] Final documentation and package dry-run match this tree.
251
+ - [x] Checksum manifest is regenerated and verified.
252
+
253
+ The live validation gate is intentionally manual because it can change account
254
+ state and may require Turnstile. Automated tests do not use real credentials,
255
+ make paid inference calls or mutate a user's Magpie configuration.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alexcarterio and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
1
+ # AnyRouter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Magpie 的 AnyRouter 供应商插件:六种登录入口、独立的每日签到、原生多账号路由,以及面向 AnyRouter 拥堵场景的保守重试和四协议请求保护。
4
+
5
+ 插件只包装本供应商的模型请求,不启动后台代理,不改 Codex 配置,也不给其他供应商安装全局拦截器。运行时使用标准 Web API、Node 兼容的只读 API 和隔离 VM,在 Magpie 的 Bun 插件宿主中运行。
6
+
7
+ ## 结论:登录不等于签到
8
+
9
+ AnyRouter 和 AgentRouter 的签到契约不同。AgentRouter 可以在登录响应中读取 `checked_in`,把一次登录当作签到;AnyRouter 前端则单独调用签到接口:
10
+
11
+ ```text
12
+ 密码账号签到:
13
+ GET /login (建立匿名会话;仅 WAF 重试时)
14
+ GET /api/status
15
+ POST /api/user/login?turnstile=
16
+ POST /api/user/sign_in body: {}
17
+
18
+ 已有会话签到:
19
+ GET /api/user/self
20
+ POST /api/user/sign_in body: {}
21
+ ```
22
+
23
+ 因此本插件不会因为“登录成功”“刷新了余额”或“拿到了模型 key”就宣称签到成功。`sign_in` 的响应才是签到结果。`sign_in` 只带站点 Cookie、`New-API-User`、`X-Requested-With: XMLHttpRequest` 和浏览器请求头,不带模型 `Authorization`。
24
+
25
+ AnyRouter 的 Turnstile 开关是动态的。`/api/status` 返回 `turnstile_check: true` 时,插件不会发送密码登录,也不会尝试破解验证码;请先在浏览器完成登录,再导入站点会话。对于 AnyRouter 返回的阿里云式 `acw_sc__v2` JS 盾,插件只执行响应中站点自己的内联挑战脚本,在隔离 VM 中捕获它设置的 Cookie 后重试一次;脚本大小、执行时间和可用对象都受限。如果挑战无法完成或遇到 Turnstile,插件会停止并提示改用浏览器会话入口。
26
+
27
+ ## 安装
28
+
29
+ ```sh
30
+ magpie plugin add opencode-anyrouter-auth
31
+ magpie plugin add github:roiding/opencode-anyrouter-auth
32
+ magpie plugin add /path/to/opencode-anyrouter-auth
33
+ magpie plugin login anyrouter
34
+ ```
35
+
36
+ 账号密码和系统访问令牌入口依赖 Magpie 的 keyless 登录支持。插件与社区 AnyRouter 插件共用供应商 ID `anyrouter`;同时安装时用 Magpie 的插件选择功能决定由哪一个服务该供应商,不串联两份认证实现。
37
+
38
+ 旧记录中的 API key、站点会话、用户 ID、显式端点及请求头会通过兼容层读取。不会删除账号、重置令牌、自动创建模型 key,也不会把旧备注误当成邮箱。旧密码本身不是自动签到授权;必须在新登录流程中明确选择开启。
39
+
40
+ ## 登录入口
41
+
42
+ | 入口 | 需要提供 | 每日签到 | 余额 |
43
+ | --- | --- | --- | --- |
44
+ | 账号密码 | AnyRouter 站点用户名或邮箱、密码;可处理 `acw_sc__v2` JS 盾,Turnstile 仍需浏览器 | 可选;开启后保存密码 | 有效会话允许时读取 |
45
+ | GitHub | 浏览器完成 GitHub 登录,再交接 AnyRouter 会话 | 可选;保存会话 | 有效会话允许时读取 |
46
+ | LinuxDO | 浏览器完成 LinuxDO 登录,再交接 AnyRouter 会话 | 可选;保存会话 | 有效会话允许时读取 |
47
+ | 浏览器会话 | 浏览器完成登录及 WAF/JS 盾后,导入已登录的 AnyRouter 会话 | 可选;保存会话 | 有效会话允许时读取 |
48
+ | 系统访问令牌 | AnyRouter 系统令牌和数字用户 ID | 不支持 | 站点权限允许时读取 |
49
+ | 模型 API key | 模型调用密钥 | 不支持 | 不查询账号余额 |
50
+
51
+ 登录、会话、签到和账号查询固定使用 `anyrouter.top`。模型 API 端点在每个登录入口中直接选择 `anyrouter.top` 或 `https://a-ocnfniawgw.cn-shanghai.fcapp.run`。账号密码、GitHub、LinuxDO、浏览器会话和系统访问令牌入口会读取账号已有的模型 key:
52
+
53
+ - 只有一个有效 key 时直接使用。
54
+ - 有多个有效 key 时,要求用户在高级设置中填写数字 key ID。
55
+ - 没有有效 key 时明确失败,请用户先在站点创建或启用 key。
56
+ - 不调用 `/api/user/token`,不重置系统令牌,不自动创建、旋转或删除模型 key。
57
+
58
+ 系统访问令牌和模型 API key 是不同凭据,不能混用。模型 API key 入口只提供模型发现和推理请求保护。
59
+
60
+ ## GitHub、LinuxDO 与浏览器会话
61
+
62
+ 这三个入口都走“浏览器完成正常登录,再把 AnyRouter 会话交给插件”的流程,不重放已被消费的 OAuth code。
63
+
64
+ 1. 在 Magpie 登录界面选择入口,打开 AnyRouter 登录页。
65
+ 2. 在浏览器完成 GitHub、LinuxDO 或普通账号登录。
66
+ 3. 打开浏览器 DevTools 的 Network,刷新 AnyRouter 账号页,找到本站的 `GET /api/user/self`,选择 Copy as cURL(bash 格式)。
67
+ 4. 将复制内容粘贴到 Magpie 的登录交接框。
68
+
69
+ 也可以粘贴包含以下字段的 JSON:
70
+
71
+ ```json
72
+ {
73
+ "cookie": "session=...; acw_tc=...; cdn_sec_tc=...; acw_sc__v2=...",
74
+ "userId": "123"
75
+ }
76
+ ```
77
+
78
+ 插件只解析文本,不执行 cURL 或任何 shell 命令。只接受 `anyrouter.top` 的 `/api/user/self` 请求;`session` Cookie 和数字 `New-Api-User` 必须存在。浏览器客户端头只用于站点接口,不会混入模型请求。
79
+
80
+ 粘贴内容属于敏感凭据,只应保存在本机 Magpie 认证文件中。不要把 Cookie、密码或 cURL 粘贴到聊天、Issue 或日志。
81
+
82
+ ## 每日签到
83
+
84
+ 签到默认关闭,必须同时满足三个条件:
85
+
86
+ 1. 添加账号时明确选择“是 - 保存密码用于每日签到”,或为会话入口选择“是 - 保存会话用于每日签到”。
87
+ 2. 账号有可用的站点密码或未过期会话,以及经过校验的站点 UID。
88
+ 3. 在 Magpie 的 **设置(Settings)› 额度(Allowances)** 中打开 AnyRouter 签到开关,并按需打开具体账号的开关。
89
+
90
+ 宿主负责每日调度。插件不创建自己的后台定时器,也不会在余额查询失败时偷偷登录签到。
91
+
92
+ 签到行为:
93
+
94
+ - 密码模式先读取 `/api/status`,再登录并校验 `/api/user/self`,最后单独调用 `/api/user/sign_in`。如果状态或登录请求返回可识别的 `acw_sc__v2` JS 盾,插件在隔离 VM 中执行站点自己的挑战脚本、合并 `acw_tc`/`cdn_sec_tc`/`acw_sc__v2` 后重试一次;不循环重试。
95
+ - 会话模式先只读校验 `/api/user/self`,再调用 `sign_in`,不使用密码。
96
+ - 站点返回的用户 ID 必须匹配目标账号;不匹配时不覆盖另一个账号的会话。
97
+ - 同一账号同一天的并发签到会合并。
98
+ - 北京时间的当天去重只在 `claimed`、`done`、`captcha`、`inactive`、`ineligible` 等终态上生效。
99
+ - HTTP 200 但 `success:false` 且映射为 `failed` 的结果不会标记当天完成,也不会写入签到日期,之后仍可重试。
100
+ - 验证码、WAF、密码错误、账号无权限或接口未开放不会被当作“签到成功”。
101
+
102
+ 签到结果含义:
103
+
104
+ | outcome | 含义 |
105
+ | --- | --- |
106
+ | `claimed` | 本次签到请求成功,且未识别为今日已签到 |
107
+ | `done` | 今日已经签到,或并发调用已合并 |
108
+ | `captcha` | 需要浏览器完成 Turnstile 或 WAF 验证 |
109
+ | `inactive` | 站点当前没有开放签到活动或接口 |
110
+ | `ineligible` | 账号无权限,或凭据/会话失效 |
111
+ | `failed` | 限流、暂时不可用或其他未完成结果;不写当天完成标记 |
112
+
113
+ AnyRouter 的签到奖励会增加钱包余额,但不等于每天自动重置模型额度。余额缺失、WAF 拦截或接口失败时显示未知,不会伪造为零,也不会伪造午夜刷新窗口。
114
+
115
+ ## 站点、模型 API 与 WAF
116
+
117
+ 固定站点(登录、会话、签到、余额和账号查询):
118
+
119
+ - `anyrouter.top`
120
+
121
+ 模型 API 端点:
122
+
123
+ - `https://anyrouter.top`
124
+ - `https://a-ocnfniawgw.cn-shanghai.fcapp.run`(备用 API)
125
+
126
+ API 端点选择不会改变登录、会话导入、签到、余额查询或模型目录发现地址。上述站点操作始终只访问 `anyrouter.top`,备用 API 域名只用于 `/v1` 或 `/v1beta` 模型推理请求。
127
+
128
+ 每个账号在登录时选择一个模型 API 端点。插件重试会留在该账号所选端点内,不会在一次请求中自动切换到另一个 API 域名,以避免重复计费;跨账号切换仍由 Magpie 的原生故障转移负责。
129
+
130
+ 站点会话可能包含 `session`、`acw_tc`、`cdn_sec_tc`、`acw_sc__v2` 等 Cookie。导入时一并保留;登录和签到过程中,站点返回的更新 Cookie 会合并回账号记录。
131
+
132
+ 遇到可识别的 AnyRouter JS 盾页时,插件会执行站点自己的内联挑战脚本,最多重试一次;脚本在隔离 VM 中运行,不能访问网络、文件或进程,并限制脚本大小和执行时间。无法完成挑战时返回需要人工处理的错误,不会在后台循环刷新、破解 Turnstile 或把站点 Cookie 发送给第三方。站点操作使用 Chrome 风格请求头,并设置 `anyrouter.top` 的 `Origin`/`Referer`。
133
+
134
+ ## 模型与请求头
135
+
136
+ **没有默认模型。** 官方端点的模型目录从 `https://anyrouter.top/api/pricing` 获取,以返回条目的 `model_name` 作为模型 ID,不依赖 `/v1/models`。已有站点登录态时携带账号的 Cookie / 系统访问令牌和 `New-Api-User`;仅 API Key 模式尝试匿名读取,不会把推理 key 发给站点接口。
137
+
138
+ pricing 中的协议、能力和上限信息直接用于模型目录,公共注册表只补充元数据,不额外增加模型。目录展示不代表当前 API key 一定有权调用每个模型,实际权限仍由推理接口校验。读取失败时保留显式配置的模型并标记发现失败,不会把站点会话失效误报为推理 key 失效。自定义非官方网关仍使用其 `/models` 接口发现模型,pricing 仅补充已有模型的元数据。
139
+
140
+ 模型协议映射:
141
+
142
+ - `claude-*` 和 `*-cc-format` 默认按 Anthropic Messages。
143
+ - `gemini-*` 默认按 Gemini。
144
+ - 其他模型默认按 Responses。
145
+
146
+ 用户显式声明的 SDK、模型和 API 地址优先。模型元数据逐字段解析:用户覆盖、账号声明、本站 pricing、对应注册表、原厂型号、可信同族信息、宿主已有字段。`context`、`input`、`output` 分别表示总上下文、输入上限和输出上限,不互相冒充。
147
+
148
+ 模型请求原样透传 Magpie 已合并的本次请求和当前模型头。账号自定义头可以覆盖默认头,但不混合其他模型的头。兼容客户端标识默认开启,只在 Responses 协议上恢复 codex 客户端身份;账号自定义头始终优先。
149
+
150
+ 认证头按出站协议选择 Bearer、`x-api-key` 或 `x-goog-api-key`。站点 Cookie、系统访问令牌、密码和 `New-API-User` 不会发送到模型接口。账号自定义头不能覆盖认证、Cookie、Host、连接和长度等受管理字段。
151
+
152
+ ## 重试与请求保护
153
+
154
+ AnyRouter 常年拥堵,因此默认使用 `anyrouter` 重试配置,而不是上游的宽松默认值:
155
+
156
+ - 单次选定供应商调用最多额外重试 8 次。
157
+ - 资源不匹配最多 1 次,限流最多 3 次,传输错误最多 4 次,可用性错误最多 2 次。
158
+ - 退避从 1 秒到 15 秒左右,限流退避带少量抖动,并遵守 `Retry-After`。
159
+ - 裸 `429` 按限流处理;裸 `503`、`504` 按可用性处理。
160
+ - 带 JSON 的余额不足、无效 key、权限拒绝和模型不存在错误不会因为 HTTP 429 或 5xx 被误重试。
161
+ - 总期限、上游空闲期限、客户端取消和响应大小上限始终优先。
162
+
163
+ 这里的 8 次是插件内一次选定供应商调用的上限,不是 Magpie 整个账号故障转移链的总次数。Magpie 的跨账号切换是外层行为。
164
+
165
+ 请求保护覆盖 Responses、Chat Completions、Anthropic Messages 和 Gemini 的流式与非流式请求:
166
+
167
+ 1. 首次请求保留原始字节;普通重试也保留,不预先删历史、不替换模型。
168
+ 2. 只有 Responses 的明确资源不匹配或 `invalid_encrypted_content` 才允许清理历史。
169
+ 3. 清理保留消息、图片、phase、工具参数/结果和 `call_id` 配对;不能安全恢复的服务端引用会明确失败。
170
+ 4. 其他协议不套用 Responses 字段删除,不猜测 thinking、signature 或 thoughtSignature 修复。
171
+ 5. SSE 在确认协议终止前不交付正文或客户端工具调用;失败尝试整体丢弃。
172
+ 6. 快速错误保留 HTTP 状态和响应头;保活提交 SSE 后,后续错误通过带原始状态和错误码的 SSE 事件交付,不伪造完成。
173
+
174
+ 保活默认每 10 秒发送不含正文、响应 ID 或工具调用的进度事件。它不重置上游空闲期限,也不保证上游工具只执行一次;重试可能产生重复计费或重复副作用。
175
+
176
+ ## 开关与参数
177
+
178
+ 供应商开关“安全重试加密历史错误”只控制请求保护,不影响登录、签到或账号选择。默认开启。
179
+
180
+ 插件选项示例:
181
+
182
+ ```json
183
+ {
184
+ "quotaPerUnit": 500000,
185
+ "filter": {
186
+ "enabled": true,
187
+ "retryProfile": "anyrouter",
188
+ "deadlineMs": 1800000,
189
+ "idleTimeoutMs": 120000,
190
+ "keepaliveMs": 10000,
191
+ "maxBufferBytes": 67108864,
192
+ "maxRequestBytes": 67108864
193
+ }
194
+ }
195
+ ```
196
+
197
+ `retryProfile` 默认由插件入口设为 `anyrouter`。将 `filter.enabled` 设为 `false` 或关闭供应商开关,可绕过请求保护;登录和站点接口本来就不受这个模型请求过滤器包装。
198
+
199
+ 日志只记录结构化事件、类别、计数和耗时,不记录请求正文、密码、Cookie、令牌、授权码或 state。
200
+
201
+ ## 开发与验收
202
+
203
+ ```sh
204
+ npm test
205
+ node --test test/provider.test.mjs test/site-client.test.mjs
206
+ node --test test/anyrouter-retry.test.mjs
207
+ ```
208
+
209
+ 普通测试使用模拟响应和本地 HTTP 服务,不读取真实账号,也不调用收费模型。真实宿主/网关测试默认跳过,必须显式提供已安装路径:
210
+
211
+ ```sh
212
+ MAGPIE_TEST_HOST=/path/to/host.js \
213
+ MAGPIE_TEST_BUN=/path/to/bun \
214
+ npm run test:host
215
+
216
+ MAGPIE_TEST_BINARY=/path/to/magpie \
217
+ MAGPIE_TEST_BUN=/path/to/bun \
218
+ npm run test:gateway
219
+ ```
220
+
221
+ 这些测试创建隔离 HOME、临时账号和回环服务,结束后清理,不修改现有 Magpie 配置。可选的 `MAGPIE_TEST_SSE_IDLE=1` 会运行约四分钟的真实网关 SSE 空闲测试。
222
+
223
+ 本包自包含,不捆绑上游源码。旧通用入口 `generic.mjs` 继续保留给非 AnyRouter 场景,默认入口只注册 AnyRouter。
224
+
225
+ ## 来源与许可
226
+
227
+ 行为来源、参考项目和派生关系见 [UPSTREAM.md](UPSTREAM.md),实现契约见 [DESIGN.md](DESIGN.md)。本包使用 MIT License。
package/UPSTREAM.md ADDED
@@ -0,0 +1,96 @@
1
+ # Upstream Sources and Provenance
2
+
3
+ This package is a MIT-licensed derivative of the local
4
+ `opencode-agentrouter-auth` working tree:
5
+
6
+ - Source workspace: `/Users/roiding/Documents/ChatGPT/opencode-agentrouter-auth`
7
+ - Source HEAD: `ed4e25fba0b23fd5cfca3d38713df44aab04f428`
8
+ (2026-10-29, "Fix model capabilities, SSE liveness, and account identity")
9
+ - Repository: https://github.com/roiding/opencode-agentrouter-auth
10
+ - The AnyRouter version copies the provider/account/filter architecture as a
11
+ baseline from that working tree, including its local uncommitted changes,
12
+ then replaces the site authentication and check-in contract.
13
+
14
+ The AgentRouter baseline itself records these behavioral references:
15
+
16
+ - https://github.com/ZhaoJun233/agentrouter-magpie-plugin
17
+ - Pinned commit: `1049163f2cd95b39b55b9ca23b1d91b139a80423`.
18
+ - Behavioral reference for the Magpie account, login, catalog and wallet
19
+ integration; no AgentRouter runtime source is bundled here.
20
+ - https://github.com/yidu456/magpie-auto-codex-filter
21
+ - Policy basis: commit `cd68b072ddf3475203d42661d9cdca3a93212100`.
22
+ - Copyright (c) 2026 alexcarterio and contributors.
23
+ - `lib/responses-filter.mjs` adapts the policy to Web Fetch streams;
24
+ `lib/protocols.mjs` adds protocol-specific framing and error handling.
25
+
26
+ ## AnyRouter behavior research
27
+
28
+ The AnyRouter-specific flow was checked against the public frontend and status
29
+ endpoints on 2026-10-30:
30
+
31
+ - Status: https://anyrouter.top/api/status
32
+ - Frontend bundle observed: https://anyrouter.top/assets/index-Dultz3N6.js
33
+ - User-confirmed alternate model API endpoint:
34
+ https://a-ocnfniawgw.cn-shanghai.fcapp.run
35
+
36
+ The frontend's daily action is a separate `POST /api/user/sign_in` request. A
37
+ successful password login or a profile read is not itself proof of a daily
38
+ reward. The plugin therefore uses:
39
+
40
+ ```text
41
+ password: [/login on WAF fallback] -> /api/status -> /api/user/login?turnstile= -> /api/user/sign_in
42
+ session: /api/user/self -> /api/user/sign_in
43
+ ```
44
+
45
+ At the time of inspection `/api/status` reported `turnstile_check:false`, but
46
+ this is a dynamic site setting. The implementation checks it before sending a
47
+ password and treats `true` as a browser-action requirement. The site may also
48
+ return an Aliyun-style WAF challenge. A recognized `acw_sc__v2` inline
49
+ challenge is executed in a bounded isolated VM, its cookie is captured, and the
50
+ request is retried once. Turnstile and unrecognized challenges are not solved;
51
+ browser-session handoff remains the fallback.
52
+
53
+ Additional behavior references:
54
+
55
+ - https://github.com/cita-777/metapi/blob/main/src/server/services/platforms/newApi.ts
56
+ - https://github.com/awsl404/magpie-api-checkin
57
+
58
+ These are references for New API-style site operations and check-in behavior,
59
+ not bundled source. AnyRouter's actual status, session, Turnstile and WAF
60
+ responses remain authoritative.
61
+
62
+ ## Magpie compatibility
63
+
64
+ The isolated host and gateway tests were run on 2026-10-30 with:
65
+
66
+ - Magpie `0.1.1993`
67
+ - Bun `1.4.4`
68
+
69
+ The plugin uses the host's keyless API-method support, native account storage,
70
+ native account failover and native check-in scheduling. It does not patch
71
+ Magpie configuration files, launch a separate proxy or assume a fixed account
72
+ pool.
73
+
74
+ Model metadata and SSE liveness references remain relevant to this derivative:
75
+
76
+ - Raw public registry: https://models.dev/api.json
77
+ - Codex Responses SSE handling:
78
+ https://github.com/openai/codex/blob/main/codex-rs/codex-api/src/sse/responses.rs
79
+ - Magpie's native gateway may hold lead events while another account is tried;
80
+ the plugin's keepalive and timeout behavior is therefore tested through the
81
+ installed gateway, not only through unit fixtures.
82
+
83
+ Account identity behavior inherited from the baseline:
84
+
85
+ - New accounts use a UID-verified profile's email, then username, then UID;
86
+ legacy remarks are labels, not canonical emails.
87
+ - Display aliases are set through Magpie after login. The plugin does not
88
+ repurpose the `email` prompt as an alias or patch `providers.json`.
89
+ - Refreshes preserve existing account names and UIDs so native aliases and
90
+ name-keyed settings are not orphaned.
91
+ - Usage omits the optional site username from `usage.user`, so a site login
92
+ does not become a third account name.
93
+
94
+ This package is self-contained. Runtime sources, tests and documentation live
95
+ at the repository root; update this record whenever a new external behavior
96
+ reference changes an implementation decision.