magpie-plugin-loomy-auth 0.1.21 → 0.1.26
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/AGENTS.md +1 -0
- package/CHANGELOG.md +58 -0
- package/CHECKLIST.md +8 -0
- package/README.md +1 -1
- package/docs/internals.md +74 -11
- package/package.json +9 -4
- package/publish-npm.mjs +21 -7
- package/src/api.mjs +38 -7
- package/src/chat.mjs +177 -21
- package/src/constants.mjs +25 -0
- package/src/icon.mjs +4 -10
- package/src/pure.mjs +40 -4
package/src/chat.mjs
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
// 只做五件事,其余原样转发(上游本来就是 OpenAI 协议,不做协议转换):
|
|
4
4
|
//
|
|
5
5
|
// ① 换成 Loomy 的 token 双头(AI SDK 发的 Bearer 是占位值,必须覆盖)
|
|
6
|
-
// ②
|
|
6
|
+
// ② 已知不吃 `image_url` 的模型(见 `prefersTagFormat`):发送前就把
|
|
7
|
+
// `image_url` data URI 改写成 `<image_base64>` 标记
|
|
8
|
+
// ②' 图片格式兜底:模型名没命中判据、却仍因图片格式整条 400 时,
|
|
9
|
+
// 把同一个 body 改写成标记形态**本地重发一次**(见 `IMAGE_FORMAT_SAID` / `taggedBody`)
|
|
7
10
|
// ③ HTTP 200 + 信封 `{code:"100002"}` 的失效响应 → 打上
|
|
8
11
|
// `X-Magpie-Sign-In: expired`(magpie 据此标记账号)
|
|
9
12
|
// ④ 本地额度闸:**已知**两池皆空时直接回 429,不白撞上游
|
|
@@ -17,7 +20,7 @@
|
|
|
17
20
|
// 漏拦 = 上游回一次错误(有明确文案);错拦 = 一个好好的号发不出请求。
|
|
18
21
|
|
|
19
22
|
import { _pure } from "./pure.mjs"
|
|
20
|
-
import { CHAT_TIMEOUT_MS } from "./constants.mjs"
|
|
23
|
+
import { CHAT_TIMEOUT_MS, CLIENT_UA, ERROR_CODES } from "./constants.mjs"
|
|
21
24
|
import { exhausted } from "./usage.mjs"
|
|
22
25
|
|
|
23
26
|
const { businessCode, isAuthErrorCode, prefersTagFormat, rewriteImagesToTags } = _pure
|
|
@@ -32,13 +35,17 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
32
35
|
bodyText = typeof rawBody === "string" ? rawBody : await new Response(rawBody).text()
|
|
33
36
|
}
|
|
34
37
|
|
|
35
|
-
// ④ 已知耗尽:不发给上游,直接回一个明确的 429
|
|
38
|
+
// ④ 已知耗尽:不发给上游,直接回一个明确的 429。
|
|
39
|
+
// `code` 只能取 ERROR-CODES.md §3 词表(R2):耗尽在宿主眼里就是「限流 / 冷却」,
|
|
40
|
+
// 取 `rate_limited`(429 · 可退避 · 换号有救)。自造 `insufficient_points` 属于
|
|
41
|
+
// 词表外的码 —— 宿主不认识就既不退避也不换号,CI 也会直接判失败。
|
|
36
42
|
if (usageValue && exhausted(usageValue)) {
|
|
37
43
|
return jsonResponse(429, {
|
|
38
44
|
error: {
|
|
39
45
|
message: "Loomy 积分已耗尽(今日额度与永久积分均为 0),请签到或更换账号",
|
|
40
46
|
type: "rate_limit_error",
|
|
41
|
-
code:
|
|
47
|
+
code: ERROR_CODES.rateLimited,
|
|
48
|
+
status: 429,
|
|
42
49
|
},
|
|
43
50
|
})
|
|
44
51
|
}
|
|
@@ -50,38 +57,65 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
50
57
|
// 非 JSON body:原样透传
|
|
51
58
|
}
|
|
52
59
|
|
|
60
|
+
// ② 发送前预改写:已知不吃 `image_url` 的模型直接按标记形态发(省掉一次 400)
|
|
61
|
+
let alreadyTagged = false
|
|
53
62
|
if (model && prefersTagFormat(model) && bodyText) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
} catch {
|
|
59
|
-
// body 不是 JSON 时保持原样
|
|
63
|
+
const tagged = taggedBody(bodyText)
|
|
64
|
+
if (tagged !== null) {
|
|
65
|
+
bodyText = tagged
|
|
66
|
+
alreadyTagged = true
|
|
60
67
|
}
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
const incoming = new Headers(request ? request.headers : init?.headers)
|
|
64
|
-
|
|
71
|
+
// `user-agent` 必须进跳过名单:magpie 递给插件的是它自己的 `magpie/<version>`,
|
|
72
|
+
// 原样转发就是这个插件在替「第三方客户端」投标(上游网关按 `<product>/<version>` 认人,
|
|
73
|
+
// 命中即 403 TM.00000001)。下面统一换成官方 Loomy 客户端的 UA。
|
|
74
|
+
for (const key of ["authorization", "x-api-key", "token", "content-length", "host", "user-agent"]) incoming.delete(key)
|
|
65
75
|
incoming.set("token", session)
|
|
66
76
|
incoming.set("Authorization", `Bearer ${session}`)
|
|
77
|
+
incoming.set("user-agent", CLIENT_UA)
|
|
67
78
|
if (bodyText) incoming.set("Content-Type", "application/json")
|
|
68
79
|
|
|
80
|
+
// 重发与首发必须用**完全相同**的 headers / method / signal —— 只换 body。
|
|
81
|
+
// signal 在这里先定下来(不留在 fetch 参数里),否则重发会各自造一个新的超时。
|
|
82
|
+
const method = init?.method ?? request?.method ?? "POST"
|
|
83
|
+
const callerSignal = init?.signal ?? request?.signal ?? null
|
|
84
|
+
const signal = callerSignal ?? AbortSignal.timeout(CHAT_TIMEOUT_MS)
|
|
85
|
+
const target = request ? request.url : url
|
|
86
|
+
const sendOnce = (body) =>
|
|
87
|
+
fetch(target, { ...(init ?? {}), method, headers: incoming, body: body || undefined, signal })
|
|
88
|
+
|
|
69
89
|
let response
|
|
70
90
|
try {
|
|
71
|
-
response = await
|
|
72
|
-
...(init ?? {}),
|
|
73
|
-
method: init?.method ?? request?.method ?? "POST",
|
|
74
|
-
headers: incoming,
|
|
75
|
-
body: bodyText || undefined,
|
|
76
|
-
signal: init?.signal ?? request?.signal ?? AbortSignal.timeout(CHAT_TIMEOUT_MS),
|
|
77
|
-
})
|
|
91
|
+
response = await sendOnce(bodyText)
|
|
78
92
|
} catch (error) {
|
|
79
|
-
|
|
93
|
+
// 只有**调用方**主动取消才往外抛;本插件自己的超时按上游失败处理(回 502)
|
|
94
|
+
if (callerSignal?.aborted) throw error
|
|
80
95
|
return jsonResponse(502, {
|
|
81
96
|
error: { message: `Loomy 请求失败:${error?.message ?? error}`, type: "api_error" },
|
|
82
97
|
})
|
|
83
98
|
}
|
|
84
99
|
|
|
100
|
+
// ②' 图片格式兜底(实测 2026-11-08):网关的后端路由会漂移 —— 同一个 model 名
|
|
101
|
+
// 不一定落同一个后端,而讯飞自研后端(iflytek-spark-loomy / alibaba-dashscope)
|
|
102
|
+
// 对 `image_url` 一律整条 400。模型名没命中判据时,这里按**文案**认。
|
|
103
|
+
//
|
|
104
|
+
// 只在「400 + 命中文案 + 本次 body 里确实有 data URI 图片 + 尚未改写过」时重发,
|
|
105
|
+
// 且**只重发一次**:重发还失败就把第二次的 Response 原样交回去(不再加工)。
|
|
106
|
+
if (!alreadyTagged && (await isImageFormatRefusal(response))) {
|
|
107
|
+
const retryBody = taggedBody(bodyText)
|
|
108
|
+
if (retryBody !== null) {
|
|
109
|
+
try {
|
|
110
|
+
const retried = await sendOnce(retryBody)
|
|
111
|
+
response = withImageRetryHeader(retried)
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (callerSignal?.aborted) throw error
|
|
114
|
+
// 重发没拿到响应:把第一次的 400 交回去 —— 它才是上游的真实回答
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
85
119
|
// ③ 只有 JSON 响应才解析业务码;SSE 原样透传
|
|
86
120
|
const contentType = (response.headers.get("content-type") ?? "").toLowerCase()
|
|
87
121
|
if (contentType.includes("application/json")) {
|
|
@@ -107,8 +141,98 @@ export async function chatFetch({ input, init, credential, session, usageValue }
|
|
|
107
141
|
return response
|
|
108
142
|
}
|
|
109
143
|
|
|
144
|
+
/** 上游把图片格式当成整条请求有误的两句文案(2026-11-08 实测,逐字抄自错误体) */
|
|
145
|
+
const IMAGE_FORMAT_SAID = /请求有误,请重试;若多次出现请更新应用版本|暂不支持该图片格式/
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 上游是不是因为图片投递形态整条拒了 —— 只认 **400 + 上面那两句文案**。
|
|
149
|
+
*
|
|
150
|
+
* ⚠ 用 `clone()` 读:不重发时原 Response 必须原样交回去(照 `rewriteTooLongRefusal` 的做法)。
|
|
151
|
+
* ⚠ 先判状态码再读 body:只有 400 会读,2xx/SSE 连 clone 都不做。
|
|
152
|
+
*/
|
|
153
|
+
async function isImageFormatRefusal(response) {
|
|
154
|
+
if (response?.status !== 400) return false
|
|
155
|
+
let payload
|
|
156
|
+
try {
|
|
157
|
+
payload = await response.clone().json()
|
|
158
|
+
} catch {
|
|
159
|
+
return false // 不是 JSON 错误信封 ⇒ 跟我们无关
|
|
160
|
+
}
|
|
161
|
+
// ⚠ 必须是**上游错误信封**,且 `error.message` 以那句话开头。
|
|
162
|
+
// 只做 `text.includes(文案)` 会误触发:用户把报错贴进对话、或把日志当图片喂回来时,
|
|
163
|
+
// body 里本来就含这串字(本机真实发生过 —— 本会话上下文里就有它的回声)。
|
|
164
|
+
// 那时任何 400(哪怕与图片无关)都会让插件把同一个大请求再发一遍,白烧一次额度。
|
|
165
|
+
const message = payload?.error?.message
|
|
166
|
+
if (typeof payload?.error?.type !== "string" || typeof message !== "string") return false
|
|
167
|
+
return IMAGE_FORMAT_REFUSAL_MESSAGE.test(message.trim())
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 上游错误信封里的**完整**文案(不是出现在任意位置的花絮)。
|
|
172
|
+
*
|
|
173
|
+
* 用 `^…` 锚定 `error.message` 的开头:`iflytek-spark-loomy` / `alibaba-dashscope`
|
|
174
|
+
* 就是把这句话当 `message` 整句给出的(实测原文,见 docs/internals.md 的矩阵节)。
|
|
175
|
+
*/
|
|
176
|
+
const IMAGE_FORMAT_REFUSAL_MESSAGE = /^(请求有误,请重试|暂不支持该图片格式)/
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 把 body 改写成 `<image_base64>` 标记形态;
|
|
180
|
+
* 没有 data URI 图片块时返回 `null`(用来判「本次请求到底带没带图」)。
|
|
181
|
+
*/
|
|
182
|
+
function taggedBody(bodyText) {
|
|
183
|
+
if (!bodyText) return null
|
|
184
|
+
try {
|
|
185
|
+
const parsed = JSON.parse(bodyText)
|
|
186
|
+
// 已经是标记形态 ⇒ 没有「第二次」可做。不拦这一条,body 里另有多张 data URI 图时
|
|
187
|
+
// 会绕过 `alreadyTagged` 把同一个请求再发一遍(图片还是会重复计费)。
|
|
188
|
+
if (hasImageBase64Tag(parsed)) return null
|
|
189
|
+
const rewritten = rewriteImagesToTags(parsed)
|
|
190
|
+
return rewritten === parsed ? null : JSON.stringify(rewritten)
|
|
191
|
+
} catch {
|
|
192
|
+
return null // 非 JSON body 谈不上图片块
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** body 里是否已经有 `<image_base64>` 标记(说明上游要的形态已经就位) */
|
|
197
|
+
function hasImageBase64Tag(body) {
|
|
198
|
+
const messages = Array.isArray(body?.messages) ? body.messages : []
|
|
199
|
+
for (const message of messages) {
|
|
200
|
+
const content = message?.content
|
|
201
|
+
if (typeof content === "string") {
|
|
202
|
+
if (content.includes(IMAGE_BASE64_OPEN)) return true
|
|
203
|
+
} else if (Array.isArray(content)) {
|
|
204
|
+
for (const block of content) {
|
|
205
|
+
if (block?.type === "text" && typeof block.text === "string" && block.text.includes(IMAGE_BASE64_OPEN)) {
|
|
206
|
+
return true
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return false
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const IMAGE_BASE64_OPEN = "<image_base64>"
|
|
215
|
+
|
|
216
|
+
/** 重发后的响应打上排障头(只加头,body 仍是上游那条流,不解包) */
|
|
217
|
+
function withImageRetryHeader(response) {
|
|
218
|
+
const headers = new Headers(response.headers)
|
|
219
|
+
headers.set("x-loomy-image-retry", "1")
|
|
220
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
|
|
221
|
+
}
|
|
222
|
+
|
|
110
223
|
/** 「内容太长」的几种中文说法 —— 上游只说了长度,没说「上下文」 */
|
|
111
224
|
const TOO_LONG_SAID = /内容太长(了)?|内容过长/
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 上游「其实是超限」时才说得出的通用文案(2026-11-08 实测)。
|
|
228
|
+
*
|
|
229
|
+
* `iflytek-spark-loomy` / `volces-ark` / `alibaba-dashscope` 把「上下文超上限」统一抛成
|
|
230
|
+
* 这两句。⚠ 它们**只在请求体很大时**才算长度问题:请求体很小时多半是图片形态问题
|
|
231
|
+
* (走上面的兜底重发)或瞬时错误(按 502 换号)—— 所以不在这里、也不重发,
|
|
232
|
+
* 一律留给 `rewriteTooLongRefusal` 按请求体大小分流。
|
|
233
|
+
*/
|
|
234
|
+
const GENERIC_OVERFLOW_SAID = /请求有误,请重试|暂不支持该图片格式/
|
|
235
|
+
|
|
112
236
|
/** 换成 magpie `tooLongRe` 认得的中文写法(`上下文…超` 命中) */
|
|
113
237
|
const TOO_LONG_REWORDED = "上下文超出长度限制"
|
|
114
238
|
|
|
@@ -121,6 +245,34 @@ const TOO_LONG_REWORDED = "上下文超出长度限制"
|
|
|
121
245
|
*/
|
|
122
246
|
const NOT_TOO_LONG_MAX_CHARS = 2_000_000
|
|
123
247
|
|
|
248
|
+
/**
|
|
249
|
+
* 这句错误体里「上游到底说了哪一句」—— 认不出就返回 `null`。
|
|
250
|
+
*
|
|
251
|
+
* 两种形态都接受,但**都必须在 `error.message` 上**(或整份 body 本身就是一个裸 message):
|
|
252
|
+
* ① 上游错误信封 `{"error":{"message":"…"}}` → 只看 `error.message`,且要求锚定开头
|
|
253
|
+
* ② 纯文本错误体(无 JSON)→ 整份文本即 message,同样要求锚定开头
|
|
254
|
+
*
|
|
255
|
+
* 这样「用户把报错贴进对话」带来的回声(出现在消息正文中间)不会被误认成上游的话。
|
|
256
|
+
*/
|
|
257
|
+
function messagePattern(text) {
|
|
258
|
+
const tooLong = /^(内容太长(了)?|内容过长)/
|
|
259
|
+
let message = null
|
|
260
|
+
try {
|
|
261
|
+
const payload = JSON.parse(text)
|
|
262
|
+
const candidate = payload?.error?.message
|
|
263
|
+
// 有 error 信封但 message 不是字符串 ⇒ 不是「上游在说这句话」
|
|
264
|
+
if (typeof candidate !== "string") return null
|
|
265
|
+
message = candidate.trim()
|
|
266
|
+
} catch {
|
|
267
|
+
// 不是 JSON:整份当消息文本(上游偶尔直接回纯文本错误)
|
|
268
|
+
message = text.trim()
|
|
269
|
+
}
|
|
270
|
+
// 锚定开头:回声出现在正文中间的不算
|
|
271
|
+
if (tooLong.test(message)) return TOO_LONG_SAID
|
|
272
|
+
if (IMAGE_FORMAT_REFUSAL_MESSAGE.test(message)) return GENERIC_OVERFLOW_SAID
|
|
273
|
+
return null
|
|
274
|
+
}
|
|
275
|
+
|
|
124
276
|
/**
|
|
125
277
|
* 处理「内容太长了」的 400/413/422:
|
|
126
278
|
* · 请求体不大 → 502(让 magpie 换号重试)
|
|
@@ -139,11 +291,15 @@ async function rewriteTooLongRefusal(response, requestChars = 0) {
|
|
|
139
291
|
} catch {
|
|
140
292
|
return null
|
|
141
293
|
}
|
|
142
|
-
|
|
294
|
+
// ⚠ 只认**上游错误信封里的 message**,不认「整个 body 里出现过这串字」。
|
|
295
|
+
// 用户把报错贴进对话时,body 里就带着这句话;拿 text 裸匹配会把
|
|
296
|
+
// 一个与长度无关的 400 改写成「上下文超限」,让 agent 白压一次上下文。
|
|
297
|
+
const said = messagePattern(text)
|
|
298
|
+
if (said === null) return null
|
|
143
299
|
|
|
144
300
|
// 请求体远小于上限 ⇒ 这不是长度问题,是上游的瞬时错误(过载时它就这么说)
|
|
145
301
|
const momentary = requestChars > 0 && requestChars < NOT_TOO_LONG_MAX_CHARS
|
|
146
|
-
const rewritten = momentary ? text : text.replace(
|
|
302
|
+
const rewritten = momentary ? text : text.replace(said, TOO_LONG_REWORDED)
|
|
147
303
|
const outStatus = momentary ? 502 : status
|
|
148
304
|
const headers = new Headers(response.headers)
|
|
149
305
|
// body 长度变了,原来的长度/编码头不再成立
|
package/src/constants.mjs
CHANGED
|
@@ -49,6 +49,24 @@ export const SUCCESS_CODE = "000000"
|
|
|
49
49
|
/** 登录态失效的业务码(上游部分错误是 HTTP 200 + 信封 code)。 */
|
|
50
50
|
export const AUTH_ERROR_CODES = ["020002", "100002"]
|
|
51
51
|
|
|
52
|
+
/**
|
|
53
|
+
* ERROR-CODES.md §3 词表里本插件真正用到的几个码。
|
|
54
|
+
*
|
|
55
|
+
* ⚠ `code` 是**机器读**的稳定标识,只能取词表内的值 —— 自造一个码等于没给:
|
|
56
|
+
* 宿主按词表分支,词表外就是「不认识」,既不退避也不换号。CI 的「供应商插件规定」
|
|
57
|
+
* 会静态判这一条(R2),历史上 `insufficient_points` 就是这么挂的。
|
|
58
|
+
*
|
|
59
|
+
* 只列用到的;加码要改 ERROR-CODES.md,不许各插件自己造词。
|
|
60
|
+
*/
|
|
61
|
+
export const ERROR_CODES = Object.freeze({
|
|
62
|
+
/** 429 · 可退避 · 换号有救 —— 限流 / 账号冷却,本地额度闸也归这一桶 */
|
|
63
|
+
rateLimited: "rate_limited",
|
|
64
|
+
/** 503 · 可重试 —— 连不上上游(断连 / 拒连 / DNS),是上游那边出事,不是请求的问题 */
|
|
65
|
+
upstreamUnavailable: "upstream_unavailable",
|
|
66
|
+
/** 504 · 可重试 —— 等到超时 / 流被截断,宿主该退避或换号,不是「业务错误」 */
|
|
67
|
+
upstreamTimeout: "upstream_timeout",
|
|
68
|
+
})
|
|
69
|
+
|
|
52
70
|
export const REQUEST_TIMEOUT_MS = 20_000
|
|
53
71
|
export const CHAT_TIMEOUT_MS = 300_000
|
|
54
72
|
|
|
@@ -64,6 +82,13 @@ export const APP_ID = trim(process.env.LOOMY_XFYUN_APP_ID) || "GM3LOOMY"
|
|
|
64
82
|
|
|
65
83
|
export const CLIENT_MODEL_ID = "Web"
|
|
66
84
|
export const CLIENT_DEVICE_ID = "web"
|
|
85
|
+
/**
|
|
86
|
+
* 官方 Loomy 桌面客户端的 UA —— **本插件唯一的 UA 常量**。
|
|
87
|
+
* 三处出站都要用它:chat(loader 的 fetch)· 业务/积分网关 · 账号签名 API;
|
|
88
|
+
* 与签名体 `base.ua` 是同一个值。
|
|
89
|
+
* 禁止出现 `magpie/…` / `magpie-…/…` 形态:上游网关按 `<product>/<version>`
|
|
90
|
+
* 认第三方客户端,命中即 403;不显式设置时 fetch 的默认 UA(`node`)同样不合规。
|
|
91
|
+
*/
|
|
67
92
|
export const CLIENT_UA = "Loomy|Desktop|Electron|macOS"
|
|
68
93
|
export const CLIENT_VERSION = "1.0.0"
|
|
69
94
|
|