@johorion/magpie-quark-kbot 0.1.0 → 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.
Files changed (2) hide show
  1. package/index.mjs +776 -754
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -1,754 +1,776 @@
1
- // Magpie provider plugin: Quark Kbot.
2
- //
3
- // Kbot has no public API, and its requests are signed by Quark's native
4
- // security bridge (kps_wg/sign_wg + a WSG `sign`). Instead of keeping a Quark
5
- // window open for every call, this plugin talks to Kbot over plain HTTP: it
6
- // borrows the native signing material by briefly starting a headless Quark
7
- // when the cached values go stale (lib/signer.mjs), then signs and sends the
8
- // request itself (lib/direct.mjs). The result is exposed to Magpie as an
9
- // OpenAI compatible provider. Agent tasks are created with a signed
10
- // /api/v2/chat POST and polled through /api/v1/chat/snap + session/req/detail.
11
- import {
12
- PROVIDER_ID,
13
- PROVIDER_NAME,
14
- FALLBACK_MODELS,
15
- DEFAULT_MODEL,
16
- AGENT_MODEL,
17
- AGENT_API_MODEL,
18
- KBOT_AGENT_API,
19
- } from "./lib/config.mjs"
20
- import { connect, sleep } from "./lib/cdp.mjs"
21
- import { launchBrowser, closeBrowser, waitForLogin, defaultProfileDir } from "./lib/quark.mjs"
22
- import { readQuarkCookies, ProfileLocked, AppBoundEncryption } from "./lib/cookies.mjs"
23
- import {
24
- prepareKbotPage,
25
- makeBinding,
26
- bindingOf,
27
- findNativeProfile,
28
- } from "./lib/session.mjs"
29
- import {
30
- waitForChatReady,
31
- deltaFromSnapshot,
32
- } from "./lib/bridge.mjs"
33
- import {
34
- promptForMessages,
35
- sseChunk,
36
- sseDone,
37
- completionJson,
38
- errorJson,
39
- newRequestId,
40
- } from "./lib/kbot-api.mjs"
41
- import { chatRequest, chatBody, parseSse, agentSnapBody, reqDetail, SNAP_PATH } from "./lib/direct.mjs"
42
- import { signerFor, harvestWsg, saveWsg as saveWsgTo, closeAllSigners } from "./lib/signer.mjs"
43
-
44
- const CHAT_TIMEOUT_MS = 5 * 60_000
45
- // Magpie's gateway cancels a call at 3 minutes; return our own error first so
46
- // the user sees why instead of a bare 499.
47
- const AGENT_TIMEOUT_MS = 150_000
48
-
49
- // Magpie session id -> { kbotSessionId, turns }
50
- const chatSessions = new Map()
51
-
52
- // accountId -> { at, st } cached Kbot quota read (a headless read is not free).
53
- const quotaCache = new Map()
54
- const QUOTA_TTL_MS = 5 * 60_000
55
-
56
- function magpieSessionKey(accountId, sessionId) {
57
- return `${accountId}::${sessionId || "default"}`
58
- }
59
-
60
- function parseCookieHeader(header) {
61
- const out = []
62
- for (const part of String(header ?? "").split(";")) {
63
- const i = part.indexOf("=")
64
- if (i <= 0) continue
65
- const name = part.slice(0, i).trim()
66
- const value = part.slice(i + 1).trim()
67
- if (!name) continue
68
- out.push({
69
- domain: ".quark.cn",
70
- name,
71
- value,
72
- path: "/",
73
- expires: -1,
74
- secure: false,
75
- httpOnly: false,
76
- sameSite: undefined,
77
- })
78
- }
79
- // b-user-id is scoped to kbot.quark.cn; keep an extra copy there.
80
- const bid = out.find((c) => c.name === "b-user-id")
81
- if (bid) out.push({ ...bid, domain: "kbot.quark.cn" })
82
- return out
83
- }
84
-
85
- async function browserLogin(_inputs, { signal } = {}) {
86
- let launched
87
- try {
88
- // Every login opens a brand-new, signed-out Quark profile. This means
89
- // adding another account always shows the QR code instead of silently
90
- // reopening the account that is already signed in.
91
- try { await closeAllSigners() } catch { /* stop background signers */ }
92
- const profileDir = defaultProfileDir("login")
93
- launched = await launchBrowser({ kind: "quark", url: "about:blank", profileDir })
94
- const { cdp } = await connect(launched.port, "about:blank")
95
- // Belt and braces: wipe any cookie/state a reused profile might hold, so
96
- // the window cannot land on an already-signed-in Kbot page.
97
- try { await cdp.send("Network.enable") } catch { /* ignore */ }
98
- try { await cdp.send("Network.clearBrowserCookies") } catch { /* ignore */ }
99
- try { await cdp.send("Network.clearBrowserCache") } catch { /* ignore */ }
100
- for (const origin of ["https://kbot.quark.cn", "https://quark.cn", "https://passport.quark.cn", "https://chat-quark2.qianwen.com"]) {
101
- try { await cdp.send("Storage.clearDataForOrigin", { origin, storageTypes: "all" }) } catch { /* ignore */ }
102
- }
103
- await prepareKbotPage(cdp)
104
- const { state, cookies } = await waitForLogin(launched.port, {
105
- cdp,
106
- signal,
107
- timeoutMs: 8 * 60_000,
108
- })
109
- await waitForChatReady(cdp, { timeoutMs: 30_000 })
110
- const binding = makeBinding(cookies, state)
111
- binding.profileDir = launched.profileDir
112
- binding.source = "browser-login"
113
- // The sign-in window was only needed for the QR code; the profile keeps
114
- // the native login. Direct mode needs nothing else — WSG values are
115
- // harvested on demand.
116
- try { cdp.close() } catch { /* ignore */ }
117
- await closeBrowser(launched, { removeProfile: false })
118
- return {
119
- type: "success",
120
- key: JSON.stringify(binding),
121
- accountId: binding.accountId,
122
- metadata: {
123
- email: binding.name,
124
- uid: binding.uid,
125
- source: "browser-login",
126
- },
127
- }
128
- } catch (e) {
129
- if (launched) await closeBrowser(launched, { removeProfile: true })
130
- return { type: "failed", error: String(e?.message ?? e).slice(0, 500) }
131
- }
132
- }
133
-
134
- async function reuseInstalledBrowser() {
135
- let cookies
136
- try {
137
- cookies = readQuarkCookies()
138
- } catch (e) {
139
- if (e instanceof ProfileLocked) {
140
- return {
141
- type: "failed",
142
- error: "夸克浏览器正在运行,无法读取它的登录数据。请先完全退出夸克浏览器后重试,或改用「打开夸克浏览器登录」。",
143
- }
144
- }
145
- if (e instanceof AppBoundEncryption) {
146
- return {
147
- type: "failed",
148
- error: "本机夸克使用了应用绑定加密,不能直接读取 Cookie。请改用「打开夸克浏览器登录」。",
149
- }
150
- }
151
- return { type: "failed", error: String(e?.message ?? e).slice(0, 500) }
152
- }
153
- if (!cookies.length) {
154
- return { type: "failed", error: "没有在本机夸克浏览器里找到登录 Cookie,请先在夸克中登录 Kbot。" }
155
- }
156
- // Direct mode signs through Quark's native bridge, so the account needs the
157
- // installed browser's profile (its native login). Verify that it can sign
158
- // before accepting the account.
159
- const base = makeBinding(cookies, {})
160
- base.profileDir = findNativeProfile(base.uid) || ""
161
- if (!base.profileDir) {
162
- return {
163
- type: "failed",
164
- error: "直接模式需要本机夸克的原生登录(用于请求签名)。请改用「打开夸克浏览器登录」。",
165
- }
166
- }
167
- try {
168
- await harvestWsg({ profileDir: base.profileDir })
169
- return {
170
- type: "success",
171
- key: JSON.stringify(base),
172
- accountId: base.accountId,
173
- metadata: { email: base.name, uid: base.uid, source: "installed-browser" },
174
- }
175
- } catch (e) {
176
- return { type: "failed", error: `夸克登录态不可用:${String(e?.message ?? e).slice(0, 460)}` }
177
- }
178
- }
179
-
180
- async function pasteCookieLogin(inputs) {
181
- const cookies = parseCookieHeader(inputs?.cookie)
182
- if (!cookies.length) return { type: "failed", error: "Cookie 为空,请粘贴包含 __kuus 或 __uus 的 Cookie。" }
183
- const base = makeBinding(cookies, {})
184
- base.profileDir = findNativeProfile(base.uid) || ""
185
- if (!base.profileDir) {
186
- return {
187
- type: "failed",
188
- error: "直接模式需要本机夸克的原生登录(用于请求签名)。请改用「打开夸克浏览器登录」。",
189
- }
190
- }
191
- try {
192
- await harvestWsg({ profileDir: base.profileDir })
193
- return {
194
- type: "success",
195
- key: JSON.stringify(base),
196
- accountId: base.accountId,
197
- metadata: { email: base.name, uid: base.uid, source: "cookie" },
198
- }
199
- } catch (e) {
200
- return { type: "failed", error: `Cookie 校验失败:${String(e?.message ?? e).slice(0, 460)}` }
201
- }
202
- }
203
-
204
- function cookieForHost(cookies, host) {
205
- return (cookies || []).filter((c) => {
206
- const d = c.domain || ""
207
- return host === d || host.endsWith(d) || (d.startsWith(".") && host.endsWith(d.slice(1)))
208
- }).map((c) => `${c.name}=${c.value}`).join("; ")
209
- }
210
-
211
- function randomKbotId() {
212
- const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
213
- return Array.from({ length: 32 }, () => chars[Math.floor(Math.random() * chars.length)]).join("")
214
- }
215
-
216
- function headersOf(init) {
217
- try {
218
- return Object.fromEntries(new Headers(init?.headers ?? {}))
219
- } catch {
220
- return {}
221
- }
222
- }
223
-
224
- function isAgentModel(model) {
225
- return model === AGENT_MODEL || model === AGENT_API_MODEL
226
- }
227
-
228
- // Kbot answers a browser-agent request from a cookie-imported session with a
229
- // login card instead of running the task. That session has web cookies but not
230
- // Quark's native account, which the agent authorization needs.
231
- const LOGIN_CARD = "[(login_card_1)]"
232
- function loginCardError(text) {
233
- if (!String(text ?? "").includes(LOGIN_CARD)) return null
234
- return "Kbot Agent 需要完整的夸克浏览器登录(Cookie 导入的账号不支持 Agent)。请在 Magpie 中重新用「打开夸克浏览器登录」添加账号。"
235
- }
236
-
237
- function agentAnswerFromDetail(json) {
238
- const msgs = json?.data?.response_messages ?? []
239
- const parts = []
240
- for (const m of msgs) {
241
- const mime = String(m?.mime_type ?? "")
242
- if (!/^multi_load\//.test(mime) && !/^answer/.test(mime)) continue
243
- if (typeof m.content === "string" && m.content) parts.push(m.content)
244
- }
245
- return parts.join("")
246
- }
247
-
248
- /**
249
- * Drive an Agent task over plain HTTP. The page creates the task with one
250
- * signed /api/v2/chat POST, then polls /api/v1/chat/snap (snap_index 1,2,...);
251
- * each snapshot is an SSE frame whose multi_load card is the answer so far.
252
- * Yields incremental text deltas.
253
- */
254
- async function* runAgentDeltas({ session, prompt, reqId, sessionId, topicId, timeout }) {
255
- const nativeProfile = session.binding.profileDir || findNativeProfile(session.binding.uid)
256
- const signer = signerFor({ accountId: session.accountId, profileDir: nativeProfile })
257
- const cookieHeader = cookieForHost(session.binding.cookies, "chat-quark2.qianwen.com")
258
- let wsg = await signer.ensureFresh()
259
-
260
- const startBody = chatBody({
261
- reqId, sessionId, topicId, model: AGENT_API_MODEL,
262
- messages: [{ mime_type: "text/plain", content: prompt, meta_data: {}, status: "complete" }],
263
- })
264
- const doStart = () => chatRequest({ wsg, signer, body: startBody, reqId, cookieHeader, signal: AbortSignal.timeout(timeout) })
265
- let start = await doStart()
266
- if ((start.status === 401 || start.status === 403) && nativeProfile) {
267
- const text = await start.text().catch(() => "")
268
- if (/EX01[0-9]|登录|sign/i.test(text)) {
269
- const fresh = await harvestWsg({ profileDir: nativeProfile }).catch(() => null)
270
- if (fresh) { saveWsgTo(session.accountId, fresh); wsg = fresh; start = await doStart() }
271
- }
272
- }
273
- if (!start.ok) {
274
- const t = await start.text().catch(() => "")
275
- throw Object.assign(new Error(`Kbot Agent 启动失败 HTTP ${start.status}: ${t.slice(0, 200)}`), { status: start.status })
276
- }
277
-
278
- const deadline = Date.now() + timeout
279
- let emitted = ""
280
- let lastSeen = ""
281
- let stable = 0
282
- let index = 0
283
- let sawContent = false
284
- const cleanDelta = (piece) => {
285
- let out = piece
286
- if (!sawContent) out = out.replace(/^[\r\n]+/, "")
287
- if (out) sawContent = true
288
- return out
289
- }
290
- try {
291
- while (Date.now() < deadline) {
292
- index += 1
293
- const snapBody = agentSnapBody({ reqId, sessionId, topicId, model: AGENT_API_MODEL, prompt, snapIndex: index })
294
- let res
295
- try {
296
- res = await chatRequest({ wsg, signer, body: snapBody, reqId, cookieHeader, path: SNAP_PATH, signal: AbortSignal.timeout(25_000) })
297
- } catch {
298
- await sleep(2500)
299
- continue
300
- }
301
- if (!res.ok) {
302
- await res.text().catch(() => {})
303
- await sleep(2500)
304
- continue
305
- }
306
- let complete = false
307
- try {
308
- for await (const frame of parseSse(res)) {
309
- const d = deltaFromSnapshot(emitted, frame.content)
310
- if (d.delta) { emitted = d.full; const out = cleanDelta(d.delta); if (out) yield out }
311
- if (frame.status === "complete" || frame.status === "finish") complete = true
312
- }
313
- } catch { /* transient frame error; keep polling */ }
314
- if (complete) break
315
- if (emitted) {
316
- if (emitted === lastSeen) stable += 1
317
- else { stable = 0; lastSeen = emitted }
318
- if (stable >= 2) break
319
- }
320
- await sleep(2500)
321
- }
322
- } finally {
323
- try { start.body?.cancel() } catch { /* ignore */ }
324
- }
325
-
326
- // Backstop: the final answer lives in session/req/detail even if snap frames
327
- // never carried it.
328
- if (!emitted) {
329
- try {
330
- const res = await reqDetail({ wsg, signer, sessionId, reqId, cookieHeader, signal: AbortSignal.timeout(20_000) })
331
- const json = await res.json().catch(() => null)
332
- const answer = agentAnswerFromDetail(json)
333
- if (answer) {
334
- const d = deltaFromSnapshot(emitted, answer)
335
- if (d.delta) { emitted = d.full; const out = cleanDelta(d.delta); if (out) yield out }
336
- }
337
- } catch { /* ignore */ }
338
- }
339
- }
340
-
341
- async function handleAgent(session, { stream, model, prompt, key, existing, requestId, started }) {
342
- const reqId = requestId.replace(/^magpie-/, "agent-")
343
- const sessionId = randomKbotId()
344
- const topicId = randomKbotId()
345
- const timeout = AGENT_TIMEOUT_MS
346
- const id = `chatcmpl-${requestId}`
347
- const iterator = runAgentDeltas({ session, prompt, reqId, sessionId, topicId, timeout })
348
- // Agent runs are independent; keep a turns counter only for diagnostics.
349
- const remember = () => {
350
- if (existing) existing.turns += 1
351
- }
352
-
353
- if (!stream) {
354
- let content = ""
355
- try {
356
- const deadline = started + timeout
357
- while (Date.now() < deadline) {
358
- const { value, done } = await iterator.next()
359
- if (done) break
360
- content += value
361
- }
362
- } catch (e) {
363
- const msg = String(e?.message ?? e)
364
- return new Response(JSON.stringify(errorJson(msg)), {
365
- status: e?.signIn || /登录|login|401|403|签名/i.test(msg) ? 401 : 502,
366
- headers: { "content-type": "application/json" },
367
- })
368
- }
369
- remember()
370
- return new Response(JSON.stringify(completionJson({ id, model, content })), {
371
- headers: { "content-type": "application/json" },
372
- })
373
- }
374
-
375
- const encoder = new TextEncoder()
376
- let cancelled = false
377
- const responseStream = new ReadableStream({
378
- async start(controller) {
379
- controller.enqueue(encoder.encode(sseChunk({ id, model, role: "assistant" })))
380
- try {
381
- const deadline = started + timeout
382
- while (Date.now() < deadline && !cancelled) {
383
- const { value, done } = await iterator.next()
384
- if (done) break
385
- if (value) controller.enqueue(encoder.encode(sseChunk({ id, model, content: value })))
386
- }
387
- } catch (e) {
388
- controller.enqueue(encoder.encode(sseChunk({ id, model, content: `\n\n[Kbot Agent 错误: ${String(e?.message ?? e)}]` })))
389
- }
390
- remember()
391
- controller.enqueue(encoder.encode(sseChunk({ id, model, finishReason: "stop" })))
392
- controller.enqueue(encoder.encode(sseDone()))
393
- try { controller.close() } catch { /* already closed */ }
394
- },
395
- cancel() {
396
- cancelled = true
397
- try { iterator.return?.() } catch { /* ignore */ }
398
- },
399
- })
400
- return new Response(responseStream, {
401
- headers: {
402
- "content-type": "text/event-stream; charset=utf-8",
403
- "cache-control": "no-cache",
404
- connection: "keep-alive",
405
- },
406
- })
407
- }
408
-
409
- async function handleChat(session, init) {
410
- const body = JSON.parse(typeof init?.body === "string" ? init.body : "{}")
411
- // Magpie may hand the provider-prefixed id through; Kbot wants the bare id.
412
- const model = String(body.model || DEFAULT_MODEL).replace(/^quark\//, "")
413
- const messages = Array.isArray(body.messages) ? body.messages : []
414
- const stream = !!body.stream
415
- const headers = headersOf(init)
416
- const magpieSession = headers["x-quark-session"] || "default"
417
- const key = magpieSessionKey(session.accountId, magpieSession)
418
- const existing = chatSessions.get(key)
419
- // Agent tasks are stateless here: each task gets a fresh Kbot session and the
420
- // whole conversation is folded into the prompt, so context never depends on a
421
- // server-side session surviving between Magpie turns.
422
- const includeHistory = isAgentModel(model) ? true : !existing?.kbotSessionId
423
-
424
- const prompt = promptForMessages(messages, { includeHistory })
425
- if (!prompt.trim()) {
426
- return new Response(JSON.stringify(errorJson("消息为空")), {
427
- status: 400,
428
- headers: { "content-type": "application/json" },
429
- })
430
- }
431
-
432
- const requestId = newRequestId()
433
- const started = Date.now()
434
- const timeout = isAgentModel(model) ? AGENT_TIMEOUT_MS : CHAT_TIMEOUT_MS
435
-
436
- if (isAgentModel(model)) {
437
- return await handleAgent(session, { stream, model, prompt, key, existing, requestId, started })
438
- }
439
-
440
- const reqId = requestId.replace(/^magpie-/, "direct-")
441
- const sessionId = existing?.kbotSessionId || randomKbotId()
442
- const topicId = existing?.topicId || randomKbotId()
443
- const cookieHeader = cookieForHost(session.binding.cookies, "chat-quark2.qianwen.com")
444
- const kbotBody = chatBody({
445
- reqId,
446
- sessionId,
447
- topicId,
448
- model: isAgentModel(model) ? AGENT_API_MODEL : model,
449
- messages: [{ mime_type: "text/plain", content: prompt, meta_data: {}, status: "complete" }],
450
- enableSearch: !!body.enable_search,
451
- })
452
-
453
- let res
454
- const nativeProfile = session.binding.profileDir || findNativeProfile(session.binding.uid)
455
- try {
456
- const signer = signerFor({ accountId: session.accountId, profileDir: nativeProfile })
457
- const wsg = await signer.ensureFresh()
458
- res = await chatRequest({
459
- wsg,
460
- signer,
461
- body: kbotBody,
462
- reqId,
463
- cookieHeader,
464
- signal: AbortSignal.timeout(timeout),
465
- })
466
- if (res.status === 401 || res.status === 403) {
467
- const text = await res.text().catch(() => "")
468
- if (/EX01[0-9]|登录|sign/i.test(text)) {
469
- // The WSG values went stale mid-flight; re-harvest once and retry.
470
- const fresh = await harvestWsg({ profileDir: nativeProfile }).catch(() => null)
471
- if (fresh) {
472
- saveWsgTo(session.accountId, fresh)
473
- res = await chatRequest({
474
- wsg: fresh,
475
- signer,
476
- body: kbotBody,
477
- reqId,
478
- cookieHeader,
479
- signal: AbortSignal.timeout(timeout),
480
- })
481
- }
482
- }
483
- }
484
- } catch (e) {
485
- const msg = String(e?.message ?? e)
486
- const expired = e?.signIn || /登录|login|401|403|签名/i.test(msg)
487
- return new Response(JSON.stringify(errorJson(msg)), {
488
- status: expired ? 401 : 502,
489
- headers: { "content-type": "application/json" },
490
- })
491
- }
492
-
493
- // Track the Kbot session so later turns send only the newest message.
494
- if (existing) existing.turns += 1
495
- else chatSessions.set(key, { kbotSessionId: sessionId, topicId, turns: 1 })
496
-
497
- const id = `chatcmpl-${requestId}`
498
- let emitted = ""
499
- let lastError = null
500
-
501
- if (!stream) {
502
- let content = ""
503
- try {
504
- for await (const frame of parseSse(res)) {
505
- const d = deltaFromSnapshot(emitted, frame.content)
506
- if (d.delta) emitted = d.full
507
- if (frame.status === "complete" || frame.status === "finish") break
508
- }
509
- content = emitted
510
- } catch (e) {
511
- lastError = String(e?.message ?? e)
512
- }
513
- const cardErr = loginCardError(content)
514
- if (cardErr) lastError = cardErr
515
- if (lastError) {
516
- return new Response(JSON.stringify(errorJson(lastError)), {
517
- status: 502,
518
- headers: { "content-type": "application/json" },
519
- })
520
- }
521
- return new Response(JSON.stringify(completionJson({ id, model, content })), {
522
- headers: { "content-type": "application/json" },
523
- })
524
- }
525
-
526
- const encoder = new TextEncoder()
527
- let cancelled = false
528
- let sseIterator = null
529
- const responseStream = new ReadableStream({
530
- async start(controller) {
531
- controller.enqueue(encoder.encode(sseChunk({ id, model, role: "assistant" })))
532
- sseIterator = parseSse(res)
533
- const deadline = started + timeout
534
- try {
535
- while (Date.now() < deadline && !cancelled) {
536
- const { value: frame, done: iterDone } = await sseIterator.next()
537
- if (iterDone) break
538
- const d = deltaFromSnapshot(emitted, frame.content)
539
- if (d.delta) {
540
- emitted = d.full
541
- controller.enqueue(encoder.encode(sseChunk({ id, model, content: d.delta })))
542
- }
543
- const cardErr = loginCardError(emitted)
544
- if (cardErr) { lastError = cardErr; break }
545
- if (frame.status === "complete" || frame.status === "finish") break
546
- }
547
- } catch (e) {
548
- lastError = String(e?.message ?? e)
549
- }
550
- if (lastError && !cancelled) {
551
- controller.enqueue(encoder.encode(sseChunk({ id, model, content: `\n\n[Kbot 错误: ${lastError}]`, finishReason: "stop" })))
552
- } else {
553
- controller.enqueue(encoder.encode(sseChunk({ id, model, finishReason: "stop" })))
554
- }
555
- controller.enqueue(encoder.encode(sseDone()))
556
- try { controller.close() } catch { /* already closed */ }
557
- },
558
- cancel() {
559
- cancelled = true
560
- try { res.body?.cancel() } catch { /* ignore */ }
561
- },
562
- })
563
-
564
- return new Response(responseStream, {
565
- headers: {
566
- "content-type": "text/event-stream; charset=utf-8",
567
- "cache-control": "no-cache",
568
- connection: "keep-alive",
569
- },
570
- })
571
- }
572
-
573
- async function usageFor(auth) {
574
- try {
575
- const binding = bindingOf(auth)
576
- const nativeProfile = binding.profileDir || findNativeProfile(binding.uid)
577
- if (!nativeProfile) {
578
- return {
579
- plan: "夸克 Kbot",
580
- user: binding.name || binding.accountId,
581
- windows: [{ name: "剩余额度", balance: 0, unit: "", display: "缺少原生登录目录,请重新登录" }],
582
- }
583
- }
584
-
585
- // Real quota comes from Quark Settings → 个人中心 → 额度管理
586
- // (chrome://quark-settings), read through a short-lived headless Quark and
587
- // cached to avoid repeated browser launches while the card is open.
588
- let entry = quotaCache.get(binding.accountId)
589
- if (!entry || Date.now() - entry.at > QUOTA_TTL_MS) {
590
- const signer = signerFor({ accountId: binding.accountId, profileDir: nativeProfile })
591
- const st = await signer.readQuota().catch(() => null)
592
- entry = { at: Date.now(), st }
593
- quotaCache.set(binding.accountId, entry)
594
- }
595
-
596
- const quota = entry.st?.quota
597
- const plan = quota?.plan || "夸克 Kbot"
598
- const balance = typeof quota?.balance === "number" ? quota.balance : null
599
- const windows = []
600
- if (balance != null) {
601
- windows.push({ name: "可用额度", balance, unit: "", display: `${balance.toLocaleString("en-US")} 可用` })
602
- } else {
603
- windows.push({
604
- name: "可用额度",
605
- balance: 0,
606
- unit: "",
607
- display: entry.st ? "额度页未解析到余额" : "已登录(额度信息暂不可用)",
608
- })
609
- }
610
- for (const w of quota?.windows ?? []) {
611
- const pct = typeof w.remainingPct === "number" ? w.remainingPct : null
612
- windows.push({
613
- name: w.name,
614
- balance: pct ?? 0,
615
- unit: "%",
616
- display: pct == null ? (w.note || "—") : `剩余 ${pct}%${w.note ? ` · ${w.note}` : ""}`,
617
- })
618
- }
619
-
620
- return { plan, user: binding.name || binding.accountId, windows }
621
- } catch (e) {
622
- return { error: String(e?.message ?? e).slice(0, 300), windows: [] }
623
- }
624
- }
625
-
626
- export default async function quarkKbotPlugin() {
627
- return {
628
- // ------------------------------------------------------------ provider
629
- config: async (cfg) => {
630
- cfg.provider ??= {}
631
- cfg.provider[PROVIDER_ID] ??= {
632
- name: PROVIDER_NAME,
633
- npm: "@ai-sdk/openai-compatible",
634
- api: KBOT_AGENT_API,
635
- models: FALLBACK_MODELS,
636
- }
637
- cfg.provider[PROVIDER_ID].models ??= FALLBACK_MODELS
638
- },
639
-
640
- // ------------------------------------------------------------ login
641
- auth: {
642
- provider: PROVIDER_ID,
643
- maxConcurrency: 2,
644
- methods: [
645
- {
646
- type: "api",
647
- keyless: true,
648
- label: "打开夸克浏览器登录(自动抓取)",
649
- placeholder: "插件会打开夸克窗口,扫码登录后自动完成",
650
- authorize: browserLogin,
651
- },
652
- {
653
- type: "api",
654
- keyless: true,
655
- label: "复用本机夸克浏览器登录(需先退出夸克)",
656
- placeholder: "读取本机已登录的夸克账号",
657
- async authorize() {
658
- return await reuseInstalledBrowser()
659
- },
660
- },
661
- {
662
- type: "api",
663
- label: "粘贴夸克 Cookie",
664
- placeholder: "__kuus=...; __uus=...; b-user-id=...",
665
- prompts: [{
666
- type: "password",
667
- key: "cookie",
668
- message: "粘贴夸克 Cookie(登录 kbot.quark.cn 后从开发者工具复制,需包含 __kuus 或 __uus)",
669
- placeholder: "__kuus=...; __uus=...; b-user-id=...",
670
- validate: (v) => (v && /(__kuus|__uus)=/.test(v)) ? undefined : "Cookie 里必须有 __kuus 或 __uus。",
671
- }],
672
- authorize: pasteCookieLogin,
673
- },
674
- ],
675
-
676
- async loader(getAuth) {
677
- return {
678
- baseURL: "https://kbot.quark.cn",
679
- apiKey: "quark-kbot",
680
- async fetch(input, init) {
681
- const auth = await getAuth()
682
- const binding = bindingOf(auth)
683
- const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url
684
- const url = new URL(raw)
685
- if (!/\/chat\/completions$/.test(url.pathname)) {
686
- return new Response(JSON.stringify(errorJson("unsupported path")), {
687
- status: 404,
688
- headers: { "content-type": "application/json" },
689
- })
690
- }
691
- // A lightweight per-account shell for direct mode: cookies + ids.
692
- const session = { accountId: binding.accountId, binding }
693
- return await handleChat(session, init)
694
- },
695
- }
696
- },
697
-
698
- async usage(getAuth) {
699
- return await usageFor(await getAuth())
700
- },
701
- },
702
-
703
- // ------------------------------------------------------------ models
704
- provider: {
705
- id: PROVIDER_ID,
706
- async models(provider) {
707
- return provider?.models ?? FALLBACK_MODELS
708
- },
709
- },
710
-
711
- // ------------------------------------------------------------ session id
712
- "chat.headers": async (input, output) => {
713
- if (input?.model?.providerID === PROVIDER_ID && input?.sessionID) {
714
- output.headers["x-quark-session"] = input.sessionID
715
- }
716
- },
717
-
718
- commands: [
719
- {
720
- id: "quark-status",
721
- label: "夸克 Kbot 登录状态",
722
- description: "查看夸克 Kbot 的登录状态和当前模型",
723
- async run({ auth } = {}) {
724
- try {
725
- const binding = bindingOf(auth)
726
- const ok = await usageFor(auth)
727
- return { output: `夸克 Kbot:${ok.error ? "未就绪" : "已登录"}\n账号:${binding.name || binding.accountId}\n模式:直接 HTTP(按需签名)` }
728
- } catch (e) {
729
- return { output: `夸克 Kbot:未就绪\n${String(e?.message ?? e)}` }
730
- }
731
- },
732
- },
733
- {
734
- id: "quark-models",
735
- label: "夸克 Kbot 模型",
736
- description: "列出当前可用的 Kbot 模型",
737
- async run() {
738
- return { output: Object.entries(FALLBACK_MODELS).map(([id, m]) => `${id} — ${m.name}`).join("\n") }
739
- },
740
- },
741
- ],
742
- }
743
- }
744
-
745
- // Exported for tests / local debugging; not a plugin function because the
746
- // entry module's default export is used.
747
- export const _internal = {
748
- PROVIDER_ID,
749
- DEFAULT_MODEL,
750
- AGENT_MODEL,
751
- chatSessions,
752
- closeAllSigners,
753
- parseCookieHeader,
754
- }
1
+ // Magpie provider plugin: Quark Kbot.
2
+ //
3
+ // Kbot has no public API, and its requests are signed by Quark's native
4
+ // security bridge (kps_wg/sign_wg + a WSG `sign`). Instead of keeping a Quark
5
+ // window open for every call, this plugin talks to Kbot over plain HTTP: it
6
+ // borrows the native signing material by briefly starting a headless Quark
7
+ // when the cached values go stale (lib/signer.mjs), then signs and sends the
8
+ // request itself (lib/direct.mjs). The result is exposed to Magpie as an
9
+ // OpenAI compatible provider. Agent tasks are created with a signed
10
+ // /api/v2/chat POST and polled through /api/v1/chat/snap + session/req/detail.
11
+ import {
12
+ PROVIDER_ID,
13
+ PROVIDER_NAME,
14
+ FALLBACK_MODELS,
15
+ DEFAULT_MODEL,
16
+ AGENT_MODEL,
17
+ AGENT_API_MODEL,
18
+ KBOT_AGENT_API,
19
+ } from "./lib/config.mjs"
20
+ import { connect, sleep } from "./lib/cdp.mjs"
21
+ import { launchBrowser, closeBrowser, waitForLogin, defaultProfileDir } from "./lib/quark.mjs"
22
+ import { readQuarkCookies, ProfileLocked, AppBoundEncryption } from "./lib/cookies.mjs"
23
+ import {
24
+ prepareKbotPage,
25
+ makeBinding,
26
+ bindingOf,
27
+ findNativeProfile,
28
+ } from "./lib/session.mjs"
29
+ import {
30
+ waitForChatReady,
31
+ deltaFromSnapshot,
32
+ } from "./lib/bridge.mjs"
33
+ import {
34
+ promptForMessages,
35
+ sseChunk,
36
+ sseDone,
37
+ completionJson,
38
+ errorJson,
39
+ newRequestId,
40
+ } from "./lib/kbot-api.mjs"
41
+ import { chatRequest, chatBody, parseSse, agentSnapBody, reqDetail, SNAP_PATH } from "./lib/direct.mjs"
42
+ import { signerFor, harvestWsg, saveWsg as saveWsgTo, closeAllSigners } from "./lib/signer.mjs"
43
+
44
+ const CHAT_TIMEOUT_MS = 5 * 60_000
45
+ // Magpie's gateway cancels a call at 3 minutes; return our own error first so
46
+ // the user sees why instead of a bare 499.
47
+ const AGENT_TIMEOUT_MS = 150_000
48
+
49
+ // Magpie session id -> { kbotSessionId, turns }
50
+ const chatSessions = new Map()
51
+
52
+ // accountId -> { at, st } cached Kbot quota read (a headless read is not free).
53
+ const quotaCache = new Map()
54
+ const QUOTA_TTL_MS = 5 * 60_000
55
+
56
+ function magpieSessionKey(accountId, sessionId) {
57
+ return `${accountId}::${sessionId || "default"}`
58
+ }
59
+
60
+ function parseCookieHeader(header) {
61
+ const out = []
62
+ for (const part of String(header ?? "").split(";")) {
63
+ const i = part.indexOf("=")
64
+ if (i <= 0) continue
65
+ const name = part.slice(0, i).trim()
66
+ const value = part.slice(i + 1).trim()
67
+ if (!name) continue
68
+ out.push({
69
+ domain: ".quark.cn",
70
+ name,
71
+ value,
72
+ path: "/",
73
+ expires: -1,
74
+ secure: false,
75
+ httpOnly: false,
76
+ sameSite: undefined,
77
+ })
78
+ }
79
+ // b-user-id is scoped to kbot.quark.cn; keep an extra copy there.
80
+ const bid = out.find((c) => c.name === "b-user-id")
81
+ if (bid) out.push({ ...bid, domain: "kbot.quark.cn" })
82
+ return out
83
+ }
84
+
85
+ async function browserLogin(_inputs, { signal } = {}) {
86
+ let launched
87
+ try {
88
+ // Every login opens a brand-new, signed-out Quark profile. This means
89
+ // adding another account always shows the QR code instead of silently
90
+ // reopening the account that is already signed in.
91
+ try { await closeAllSigners() } catch { /* stop background signers */ }
92
+ const profileDir = defaultProfileDir("login")
93
+ launched = await launchBrowser({ kind: "quark", url: "about:blank", profileDir })
94
+ const { cdp } = await connect(launched.port, "about:blank")
95
+ // Belt and braces: wipe any cookie/state a reused profile might hold, so
96
+ // the window cannot land on an already-signed-in Kbot page.
97
+ try { await cdp.send("Network.enable") } catch { /* ignore */ }
98
+ try { await cdp.send("Network.clearBrowserCookies") } catch { /* ignore */ }
99
+ try { await cdp.send("Network.clearBrowserCache") } catch { /* ignore */ }
100
+ for (const origin of ["https://kbot.quark.cn", "https://quark.cn", "https://passport.quark.cn", "https://chat-quark2.qianwen.com"]) {
101
+ try { await cdp.send("Storage.clearDataForOrigin", { origin, storageTypes: "all" }) } catch { /* ignore */ }
102
+ }
103
+ await prepareKbotPage(cdp)
104
+ const { state, cookies } = await waitForLogin(launched.port, {
105
+ cdp,
106
+ signal,
107
+ timeoutMs: 8 * 60_000,
108
+ })
109
+ await waitForChatReady(cdp, { timeoutMs: 30_000 })
110
+ const binding = makeBinding(cookies, state)
111
+ binding.profileDir = launched.profileDir
112
+ binding.source = "browser-login"
113
+ // The sign-in window was only needed for the QR code; the profile keeps
114
+ // the native login. Direct mode needs nothing else — WSG values are
115
+ // harvested on demand.
116
+ try { cdp.close() } catch { /* ignore */ }
117
+ await closeBrowser(launched, { removeProfile: false })
118
+ return {
119
+ type: "success",
120
+ key: JSON.stringify(binding),
121
+ accountId: binding.accountId,
122
+ metadata: {
123
+ email: binding.name,
124
+ uid: binding.uid,
125
+ source: "browser-login",
126
+ },
127
+ }
128
+ } catch (e) {
129
+ if (launched) await closeBrowser(launched, { removeProfile: true })
130
+ return { type: "failed", error: String(e?.message ?? e).slice(0, 500) }
131
+ }
132
+ }
133
+
134
+ async function reuseInstalledBrowser() {
135
+ let cookies
136
+ try {
137
+ cookies = readQuarkCookies()
138
+ } catch (e) {
139
+ if (e instanceof ProfileLocked) {
140
+ return {
141
+ type: "failed",
142
+ error: "夸克浏览器正在运行,无法读取它的登录数据。请先完全退出夸克浏览器后重试,或改用「打开夸克浏览器登录」。",
143
+ }
144
+ }
145
+ if (e instanceof AppBoundEncryption) {
146
+ return {
147
+ type: "failed",
148
+ error: "本机夸克使用了应用绑定加密,不能直接读取 Cookie。请改用「打开夸克浏览器登录」。",
149
+ }
150
+ }
151
+ return { type: "failed", error: String(e?.message ?? e).slice(0, 500) }
152
+ }
153
+ if (!cookies.length) {
154
+ return { type: "failed", error: "没有在本机夸克浏览器里找到登录 Cookie,请先在夸克中登录 Kbot。" }
155
+ }
156
+ // Direct mode signs through Quark's native bridge, so the account needs the
157
+ // installed browser's profile (its native login). Verify that it can sign
158
+ // before accepting the account.
159
+ const base = makeBinding(cookies, {})
160
+ base.profileDir = findNativeProfile(base.uid) || ""
161
+ if (!base.profileDir) {
162
+ return {
163
+ type: "failed",
164
+ error: "直接模式需要本机夸克的原生登录(用于请求签名)。请改用「打开夸克浏览器登录」。",
165
+ }
166
+ }
167
+ try {
168
+ await harvestWsg({ profileDir: base.profileDir })
169
+ return {
170
+ type: "success",
171
+ key: JSON.stringify(base),
172
+ accountId: base.accountId,
173
+ metadata: { email: base.name, uid: base.uid, source: "installed-browser" },
174
+ }
175
+ } catch (e) {
176
+ return { type: "failed", error: `夸克登录态不可用:${String(e?.message ?? e).slice(0, 460)}` }
177
+ }
178
+ }
179
+
180
+ async function pasteCookieLogin(inputs) {
181
+ const cookies = parseCookieHeader(inputs?.cookie)
182
+ if (!cookies.length) return { type: "failed", error: "Cookie 为空,请粘贴包含 __kuus 或 __uus 的 Cookie。" }
183
+ const base = makeBinding(cookies, {})
184
+ base.profileDir = findNativeProfile(base.uid) || ""
185
+ if (!base.profileDir) {
186
+ return {
187
+ type: "failed",
188
+ error: "直接模式需要本机夸克的原生登录(用于请求签名)。请改用「打开夸克浏览器登录」。",
189
+ }
190
+ }
191
+ try {
192
+ await harvestWsg({ profileDir: base.profileDir })
193
+ return {
194
+ type: "success",
195
+ key: JSON.stringify(base),
196
+ accountId: base.accountId,
197
+ metadata: { email: base.name, uid: base.uid, source: "cookie" },
198
+ }
199
+ } catch (e) {
200
+ return { type: "failed", error: `Cookie 校验失败:${String(e?.message ?? e).slice(0, 460)}` }
201
+ }
202
+ }
203
+
204
+ function cookieForHost(cookies, host) {
205
+ return (cookies || []).filter((c) => {
206
+ const d = c.domain || ""
207
+ return host === d || host.endsWith(d) || (d.startsWith(".") && host.endsWith(d.slice(1)))
208
+ }).map((c) => `${c.name}=${c.value}`).join("; ")
209
+ }
210
+
211
+ function randomKbotId() {
212
+ const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
213
+ return Array.from({ length: 32 }, () => chars[Math.floor(Math.random() * chars.length)]).join("")
214
+ }
215
+
216
+ function headersOf(init) {
217
+ try {
218
+ return Object.fromEntries(new Headers(init?.headers ?? {}))
219
+ } catch {
220
+ return {}
221
+ }
222
+ }
223
+
224
+ function isAgentModel(model) {
225
+ return model === AGENT_MODEL || model === AGENT_API_MODEL
226
+ }
227
+
228
+ // Kbot answers a browser-agent request from a cookie-imported session with a
229
+ // login card instead of running the task. That session has web cookies but not
230
+ // Quark's native account, which the agent authorization needs.
231
+ const LOGIN_CARD = "[(login_card_1)]"
232
+ function loginCardError(text) {
233
+ if (!String(text ?? "").includes(LOGIN_CARD)) return null
234
+ return "Kbot Agent 需要完整的夸克浏览器登录(Cookie 导入的账号不支持 Agent)。请在 Magpie 中重新用「打开夸克浏览器登录」添加账号。"
235
+ }
236
+
237
+ function agentAnswerFromDetail(json) {
238
+ const msgs = json?.data?.response_messages ?? []
239
+ const parts = []
240
+ for (const m of msgs) {
241
+ const mime = String(m?.mime_type ?? "")
242
+ if (!/^multi_load\//.test(mime) && !/^answer/.test(mime)) continue
243
+ if (typeof m.content === "string" && m.content) parts.push(m.content)
244
+ }
245
+ return parts.join("")
246
+ }
247
+
248
+ /**
249
+ * Drive an Agent task over plain HTTP. The page creates the task with one
250
+ * signed /api/v2/chat POST, then polls /api/v1/chat/snap (snap_index 1,2,...);
251
+ * each snapshot is an SSE frame whose multi_load card is the answer so far.
252
+ * Yields incremental text deltas.
253
+ */
254
+ async function* runAgentDeltas({ session, prompt, reqId, sessionId, topicId, timeout }) {
255
+ const nativeProfile = session.binding.profileDir || findNativeProfile(session.binding.uid)
256
+ const signer = signerFor({ accountId: session.accountId, profileDir: nativeProfile })
257
+ const cookieHeader = cookieForHost(session.binding.cookies, "chat-quark2.qianwen.com")
258
+ let wsg = await signer.ensureFresh()
259
+
260
+ const startBody = chatBody({
261
+ reqId, sessionId, topicId, model: AGENT_API_MODEL,
262
+ messages: [{ mime_type: "text/plain", content: prompt, meta_data: {}, status: "complete" }],
263
+ })
264
+ const doStart = () => chatRequest({ wsg, signer, body: startBody, reqId, cookieHeader, signal: AbortSignal.timeout(timeout) })
265
+ let start = await doStart()
266
+ if ((start.status === 401 || start.status === 403) && nativeProfile) {
267
+ const text = await start.text().catch(() => "")
268
+ if (/EX01[0-9]|登录|sign/i.test(text)) {
269
+ const fresh = await harvestWsg({ profileDir: nativeProfile }).catch(() => null)
270
+ if (fresh) { saveWsgTo(session.accountId, fresh); wsg = fresh; start = await doStart() }
271
+ }
272
+ }
273
+ if (!start.ok) {
274
+ const t = await start.text().catch(() => "")
275
+ throw Object.assign(new Error(`Kbot Agent 启动失败 HTTP ${start.status}: ${t.slice(0, 200)}`), { status: start.status })
276
+ }
277
+
278
+ const deadline = Date.now() + timeout
279
+ let emitted = ""
280
+ let lastSeen = ""
281
+ let stable = 0
282
+ let index = 0
283
+ let sawContent = false
284
+ const cleanDelta = (piece) => {
285
+ let out = piece
286
+ if (!sawContent) out = out.replace(/^[\r\n]+/, "")
287
+ if (out) sawContent = true
288
+ return out
289
+ }
290
+ try {
291
+ while (Date.now() < deadline) {
292
+ index += 1
293
+ const snapBody = agentSnapBody({ reqId, sessionId, topicId, model: AGENT_API_MODEL, prompt, snapIndex: index })
294
+ let res
295
+ try {
296
+ res = await chatRequest({ wsg, signer, body: snapBody, reqId, cookieHeader, path: SNAP_PATH, signal: AbortSignal.timeout(25_000) })
297
+ } catch {
298
+ await sleep(2500)
299
+ continue
300
+ }
301
+ if (!res.ok) {
302
+ await res.text().catch(() => {})
303
+ await sleep(2500)
304
+ continue
305
+ }
306
+ let complete = false
307
+ try {
308
+ for await (const frame of parseSse(res)) {
309
+ const d = deltaFromSnapshot(emitted, frame.content)
310
+ if (d.delta) { emitted = d.full; const out = cleanDelta(d.delta); if (out) yield out }
311
+ if (frame.status === "complete" || frame.status === "finish") complete = true
312
+ }
313
+ } catch { /* transient frame error; keep polling */ }
314
+ if (complete) break
315
+ if (emitted) {
316
+ if (emitted === lastSeen) stable += 1
317
+ else { stable = 0; lastSeen = emitted }
318
+ if (stable >= 2) break
319
+ }
320
+ await sleep(2500)
321
+ }
322
+ } finally {
323
+ try { start.body?.cancel() } catch { /* ignore */ }
324
+ }
325
+
326
+ // Backstop: the final answer lives in session/req/detail even if snap frames
327
+ // never carried it.
328
+ if (!emitted) {
329
+ try {
330
+ const res = await reqDetail({ wsg, signer, sessionId, reqId, cookieHeader, signal: AbortSignal.timeout(20_000) })
331
+ const json = await res.json().catch(() => null)
332
+ const answer = agentAnswerFromDetail(json)
333
+ if (answer) {
334
+ const d = deltaFromSnapshot(emitted, answer)
335
+ if (d.delta) { emitted = d.full; const out = cleanDelta(d.delta); if (out) yield out }
336
+ }
337
+ } catch { /* ignore */ }
338
+ }
339
+ }
340
+
341
+ async function handleAgent(session, { stream, model, prompt, key, existing, requestId, started }) {
342
+ const reqId = requestId.replace(/^magpie-/, "agent-")
343
+ const sessionId = randomKbotId()
344
+ const topicId = randomKbotId()
345
+ const timeout = AGENT_TIMEOUT_MS
346
+ const id = `chatcmpl-${requestId}`
347
+ const iterator = runAgentDeltas({ session, prompt, reqId, sessionId, topicId, timeout })
348
+ // Agent runs are independent; keep a turns counter only for diagnostics.
349
+ const remember = () => {
350
+ if (existing) existing.turns += 1
351
+ }
352
+
353
+ if (!stream) {
354
+ let content = ""
355
+ try {
356
+ const deadline = started + timeout
357
+ while (Date.now() < deadline) {
358
+ const { value, done } = await iterator.next()
359
+ if (done) break
360
+ content += value
361
+ }
362
+ } catch (e) {
363
+ const msg = String(e?.message ?? e)
364
+ return new Response(JSON.stringify(errorJson(msg)), {
365
+ status: e?.signIn || /登录|login|401|403|签名/i.test(msg) ? 401 : 502,
366
+ headers: { "content-type": "application/json" },
367
+ })
368
+ }
369
+ remember()
370
+ return new Response(JSON.stringify(completionJson({ id, model, content })), {
371
+ headers: { "content-type": "application/json" },
372
+ })
373
+ }
374
+
375
+ const encoder = new TextEncoder()
376
+ let cancelled = false
377
+ const responseStream = new ReadableStream({
378
+ async start(controller) {
379
+ controller.enqueue(encoder.encode(sseChunk({ id, model, role: "assistant" })))
380
+ try {
381
+ const deadline = started + timeout
382
+ while (Date.now() < deadline && !cancelled) {
383
+ const { value, done } = await iterator.next()
384
+ if (done) break
385
+ if (value) controller.enqueue(encoder.encode(sseChunk({ id, model, content: value })))
386
+ }
387
+ } catch (e) {
388
+ controller.enqueue(encoder.encode(sseChunk({ id, model, content: `\n\n[Kbot Agent 错误: ${String(e?.message ?? e)}]` })))
389
+ }
390
+ remember()
391
+ controller.enqueue(encoder.encode(sseChunk({ id, model, finishReason: "stop" })))
392
+ controller.enqueue(encoder.encode(sseDone()))
393
+ try { controller.close() } catch { /* already closed */ }
394
+ },
395
+ cancel() {
396
+ cancelled = true
397
+ try { iterator.return?.() } catch { /* ignore */ }
398
+ },
399
+ })
400
+ return new Response(responseStream, {
401
+ headers: {
402
+ "content-type": "text/event-stream; charset=utf-8",
403
+ "cache-control": "no-cache",
404
+ connection: "keep-alive",
405
+ },
406
+ })
407
+ }
408
+
409
+ async function handleChat(session, init) {
410
+ const body = JSON.parse(typeof init?.body === "string" ? init.body : "{}")
411
+ // Magpie may hand the provider-prefixed id through; Kbot wants the bare id.
412
+ const model = String(body.model || DEFAULT_MODEL).replace(/^quark\//, "")
413
+ const messages = Array.isArray(body.messages) ? body.messages : []
414
+ const stream = !!body.stream
415
+ const headers = headersOf(init)
416
+ const magpieSession = headers["x-quark-session"] || "default"
417
+ const key = magpieSessionKey(session.accountId, magpieSession)
418
+ const existing = chatSessions.get(key)
419
+ // Agent tasks are stateless here: each task gets a fresh Kbot session and the
420
+ // whole conversation is folded into the prompt, so context never depends on a
421
+ // server-side session surviving between Magpie turns.
422
+ const includeHistory = isAgentModel(model) ? true : !existing?.kbotSessionId
423
+
424
+ const prompt = promptForMessages(messages, { includeHistory })
425
+ if (!prompt.trim()) {
426
+ return new Response(JSON.stringify(errorJson("消息为空")), {
427
+ status: 400,
428
+ headers: { "content-type": "application/json" },
429
+ })
430
+ }
431
+
432
+ const requestId = newRequestId()
433
+ const started = Date.now()
434
+ const timeout = isAgentModel(model) ? AGENT_TIMEOUT_MS : CHAT_TIMEOUT_MS
435
+
436
+ if (isAgentModel(model)) {
437
+ return await handleAgent(session, { stream, model, prompt, key, existing, requestId, started })
438
+ }
439
+
440
+ const reqId = requestId.replace(/^magpie-/, "direct-")
441
+ const sessionId = existing?.kbotSessionId || randomKbotId()
442
+ const topicId = existing?.topicId || randomKbotId()
443
+ const cookieHeader = cookieForHost(session.binding.cookies, "chat-quark2.qianwen.com")
444
+ const kbotBody = chatBody({
445
+ reqId,
446
+ sessionId,
447
+ topicId,
448
+ model: isAgentModel(model) ? AGENT_API_MODEL : model,
449
+ messages: [{ mime_type: "text/plain", content: prompt, meta_data: {}, status: "complete" }],
450
+ enableSearch: !!body.enable_search,
451
+ })
452
+
453
+ let res
454
+ const nativeProfile = session.binding.profileDir || findNativeProfile(session.binding.uid)
455
+ try {
456
+ const signer = signerFor({ accountId: session.accountId, profileDir: nativeProfile })
457
+ const wsg = await signer.ensureFresh()
458
+ res = await chatRequest({
459
+ wsg,
460
+ signer,
461
+ body: kbotBody,
462
+ reqId,
463
+ cookieHeader,
464
+ signal: AbortSignal.timeout(timeout),
465
+ })
466
+ if (res.status === 401 || res.status === 403) {
467
+ const text = await res.text().catch(() => "")
468
+ if (/EX01[0-9]|登录|sign/i.test(text)) {
469
+ // The WSG values went stale mid-flight; re-harvest once and retry.
470
+ const fresh = await harvestWsg({ profileDir: nativeProfile }).catch(() => null)
471
+ if (fresh) {
472
+ saveWsgTo(session.accountId, fresh)
473
+ res = await chatRequest({
474
+ wsg: fresh,
475
+ signer,
476
+ body: kbotBody,
477
+ reqId,
478
+ cookieHeader,
479
+ signal: AbortSignal.timeout(timeout),
480
+ })
481
+ }
482
+ }
483
+ }
484
+ } catch (e) {
485
+ const msg = String(e?.message ?? e)
486
+ const expired = e?.signIn || /登录|login|401|403|签名/i.test(msg)
487
+ return new Response(JSON.stringify(errorJson(msg)), {
488
+ status: expired ? 401 : 502,
489
+ headers: { "content-type": "application/json" },
490
+ })
491
+ }
492
+
493
+ // Track the Kbot session so later turns send only the newest message.
494
+ if (existing) existing.turns += 1
495
+ else chatSessions.set(key, { kbotSessionId: sessionId, topicId, turns: 1 })
496
+
497
+ const id = `chatcmpl-${requestId}`
498
+ let emitted = ""
499
+ let lastError = null
500
+
501
+ if (!stream) {
502
+ let content = ""
503
+ try {
504
+ for await (const frame of parseSse(res)) {
505
+ const d = deltaFromSnapshot(emitted, frame.content)
506
+ if (d.delta) emitted = d.full
507
+ if (frame.status === "complete" || frame.status === "finish") break
508
+ }
509
+ content = emitted
510
+ } catch (e) {
511
+ lastError = String(e?.message ?? e)
512
+ }
513
+ const cardErr = loginCardError(content)
514
+ if (cardErr) lastError = cardErr
515
+ if (lastError) {
516
+ return new Response(JSON.stringify(errorJson(lastError)), {
517
+ status: 502,
518
+ headers: { "content-type": "application/json" },
519
+ })
520
+ }
521
+ return new Response(JSON.stringify(completionJson({ id, model, content })), {
522
+ headers: { "content-type": "application/json" },
523
+ })
524
+ }
525
+
526
+ const encoder = new TextEncoder()
527
+ let cancelled = false
528
+ let sseIterator = null
529
+ const responseStream = new ReadableStream({
530
+ async start(controller) {
531
+ controller.enqueue(encoder.encode(sseChunk({ id, model, role: "assistant" })))
532
+ sseIterator = parseSse(res)
533
+ const deadline = started + timeout
534
+ try {
535
+ while (Date.now() < deadline && !cancelled) {
536
+ const { value: frame, done: iterDone } = await sseIterator.next()
537
+ if (iterDone) break
538
+ const d = deltaFromSnapshot(emitted, frame.content)
539
+ if (d.delta) {
540
+ emitted = d.full
541
+ controller.enqueue(encoder.encode(sseChunk({ id, model, content: d.delta })))
542
+ }
543
+ const cardErr = loginCardError(emitted)
544
+ if (cardErr) { lastError = cardErr; break }
545
+ if (frame.status === "complete" || frame.status === "finish") break
546
+ }
547
+ } catch (e) {
548
+ lastError = String(e?.message ?? e)
549
+ }
550
+ // 流可能已被取消/关闭:入队会抛 "Invalid state",必须逐个接住,
551
+ // 否则 async start() 的拒绝同样会成为未捕获异常。
552
+ const safeEnqueue = (chunk) => {
553
+ if (cancelled) return
554
+ try { controller.enqueue(chunk) } catch { /* closed or errored */ }
555
+ }
556
+ if (lastError && !cancelled) {
557
+ safeEnqueue(encoder.encode(sseChunk({ id, model, content: `\n\n[Kbot 错误: ${lastError}]`, finishReason: "stop" })))
558
+ } else {
559
+ safeEnqueue(encoder.encode(sseChunk({ id, model, finishReason: "stop" })))
560
+ }
561
+ safeEnqueue(encoder.encode(sseDone()))
562
+ try { controller.close() } catch { /* already closed */ }
563
+ },
564
+ cancel() {
565
+ cancelled = true
566
+ // res.body.cancel() 与 sseIterator.return() 都是异步的:同步 try/catch 抓不到
567
+ // 它们被拒绝的 Promise。流已锁定时会抛 ERR_INVALID_STATE,未捕获就直接把
568
+ // Bun 宿主带崩(实测 the plugin host quit: exit status 1)。必须显式接住。
569
+ try {
570
+ const body = res.body
571
+ if (body && !body.locked) {
572
+ const p = body.cancel()
573
+ if (p && typeof p.catch === "function") p.catch(() => {})
574
+ }
575
+ } catch { /* ignore */ }
576
+ try {
577
+ const it = sseIterator
578
+ if (it && typeof it.return === "function") {
579
+ const p = it.return()
580
+ if (p && typeof p.catch === "function") p.catch(() => {})
581
+ }
582
+ } catch { /* ignore */ }
583
+ },
584
+ })
585
+
586
+ return new Response(responseStream, {
587
+ headers: {
588
+ "content-type": "text/event-stream; charset=utf-8",
589
+ "cache-control": "no-cache",
590
+ connection: "keep-alive",
591
+ },
592
+ })
593
+ }
594
+
595
+ async function usageFor(auth) {
596
+ try {
597
+ const binding = bindingOf(auth)
598
+ const nativeProfile = binding.profileDir || findNativeProfile(binding.uid)
599
+ if (!nativeProfile) {
600
+ return {
601
+ plan: "夸克 Kbot",
602
+ user: binding.name || binding.accountId,
603
+ windows: [{ name: "剩余额度", balance: 0, unit: "", display: "缺少原生登录目录,请重新登录" }],
604
+ }
605
+ }
606
+
607
+ // Real quota comes from Quark Settings → 个人中心 → 额度管理
608
+ // (chrome://quark-settings), read through a short-lived headless Quark and
609
+ // cached to avoid repeated browser launches while the card is open.
610
+ let entry = quotaCache.get(binding.accountId)
611
+ if (!entry || Date.now() - entry.at > QUOTA_TTL_MS) {
612
+ const signer = signerFor({ accountId: binding.accountId, profileDir: nativeProfile })
613
+ const st = await signer.readQuota().catch(() => null)
614
+ entry = { at: Date.now(), st }
615
+ quotaCache.set(binding.accountId, entry)
616
+ }
617
+
618
+ const quota = entry.st?.quota
619
+ const plan = quota?.plan || "夸克 Kbot"
620
+ const balance = typeof quota?.balance === "number" ? quota.balance : null
621
+ const windows = []
622
+ if (balance != null) {
623
+ windows.push({ name: "可用额度", balance, unit: "", display: `${balance.toLocaleString("en-US")} 可用` })
624
+ } else {
625
+ windows.push({
626
+ name: "可用额度",
627
+ balance: 0,
628
+ unit: "",
629
+ display: entry.st ? "额度页未解析到余额" : "已登录(额度信息暂不可用)",
630
+ })
631
+ }
632
+ for (const w of quota?.windows ?? []) {
633
+ const pct = typeof w.remainingPct === "number" ? w.remainingPct : null
634
+ windows.push({
635
+ name: w.name,
636
+ balance: pct ?? 0,
637
+ unit: "%",
638
+ display: pct == null ? (w.note || "—") : `剩余 ${pct}%${w.note ? ` · ${w.note}` : ""}`,
639
+ })
640
+ }
641
+
642
+ return { plan, user: binding.name || binding.accountId, windows }
643
+ } catch (e) {
644
+ return { error: String(e?.message ?? e).slice(0, 300), windows: [] }
645
+ }
646
+ }
647
+
648
+ export default async function quarkKbotPlugin() {
649
+ return {
650
+ // ------------------------------------------------------------ provider
651
+ config: async (cfg) => {
652
+ cfg.provider ??= {}
653
+ cfg.provider[PROVIDER_ID] ??= {
654
+ name: PROVIDER_NAME,
655
+ npm: "@ai-sdk/openai-compatible",
656
+ api: KBOT_AGENT_API,
657
+ models: FALLBACK_MODELS,
658
+ }
659
+ cfg.provider[PROVIDER_ID].models ??= FALLBACK_MODELS
660
+ },
661
+
662
+ // ------------------------------------------------------------ login
663
+ auth: {
664
+ provider: PROVIDER_ID,
665
+ maxConcurrency: 2,
666
+ methods: [
667
+ {
668
+ type: "api",
669
+ keyless: true,
670
+ label: "打开夸克浏览器登录(自动抓取)",
671
+ placeholder: "插件会打开夸克窗口,扫码登录后自动完成",
672
+ authorize: browserLogin,
673
+ },
674
+ {
675
+ type: "api",
676
+ keyless: true,
677
+ label: "复用本机夸克浏览器登录(需先退出夸克)",
678
+ placeholder: "读取本机已登录的夸克账号",
679
+ async authorize() {
680
+ return await reuseInstalledBrowser()
681
+ },
682
+ },
683
+ {
684
+ type: "api",
685
+ label: "粘贴夸克 Cookie",
686
+ placeholder: "__kuus=...; __uus=...; b-user-id=...",
687
+ prompts: [{
688
+ type: "password",
689
+ key: "cookie",
690
+ message: "粘贴夸克 Cookie(登录 kbot.quark.cn 后从开发者工具复制,需包含 __kuus 或 __uus)",
691
+ placeholder: "__kuus=...; __uus=...; b-user-id=...",
692
+ validate: (v) => (v && /(__kuus|__uus)=/.test(v)) ? undefined : "Cookie 里必须有 __kuus 或 __uus。",
693
+ }],
694
+ authorize: pasteCookieLogin,
695
+ },
696
+ ],
697
+
698
+ async loader(getAuth) {
699
+ return {
700
+ baseURL: "https://kbot.quark.cn",
701
+ apiKey: "quark-kbot",
702
+ async fetch(input, init) {
703
+ const auth = await getAuth()
704
+ const binding = bindingOf(auth)
705
+ const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input?.url
706
+ const url = new URL(raw)
707
+ if (!/\/chat\/completions$/.test(url.pathname)) {
708
+ return new Response(JSON.stringify(errorJson("unsupported path")), {
709
+ status: 404,
710
+ headers: { "content-type": "application/json" },
711
+ })
712
+ }
713
+ // A lightweight per-account shell for direct mode: cookies + ids.
714
+ const session = { accountId: binding.accountId, binding }
715
+ return await handleChat(session, init)
716
+ },
717
+ }
718
+ },
719
+
720
+ async usage(getAuth) {
721
+ return await usageFor(await getAuth())
722
+ },
723
+ },
724
+
725
+ // ------------------------------------------------------------ models
726
+ provider: {
727
+ id: PROVIDER_ID,
728
+ async models(provider) {
729
+ return provider?.models ?? FALLBACK_MODELS
730
+ },
731
+ },
732
+
733
+ // ------------------------------------------------------------ session id
734
+ "chat.headers": async (input, output) => {
735
+ if (input?.model?.providerID === PROVIDER_ID && input?.sessionID) {
736
+ output.headers["x-quark-session"] = input.sessionID
737
+ }
738
+ },
739
+
740
+ commands: [
741
+ {
742
+ id: "quark-status",
743
+ label: "夸克 Kbot 登录状态",
744
+ description: "查看夸克 Kbot 的登录状态和当前模型",
745
+ async run({ auth } = {}) {
746
+ try {
747
+ const binding = bindingOf(auth)
748
+ const ok = await usageFor(auth)
749
+ return { output: `夸克 Kbot:${ok.error ? "未就绪" : "已登录"}\n账号:${binding.name || binding.accountId}\n模式:直接 HTTP(按需签名)` }
750
+ } catch (e) {
751
+ return { output: `夸克 Kbot:未就绪\n${String(e?.message ?? e)}` }
752
+ }
753
+ },
754
+ },
755
+ {
756
+ id: "quark-models",
757
+ label: "夸克 Kbot 模型",
758
+ description: "列出当前可用的 Kbot 模型",
759
+ async run() {
760
+ return { output: Object.entries(FALLBACK_MODELS).map(([id, m]) => `${id} — ${m.name}`).join("\n") }
761
+ },
762
+ },
763
+ ],
764
+ }
765
+ }
766
+
767
+ // Exported for tests / local debugging; not a plugin function because the
768
+ // entry module's default export is used.
769
+ export const _internal = {
770
+ PROVIDER_ID,
771
+ DEFAULT_MODEL,
772
+ AGENT_MODEL,
773
+ chatSessions,
774
+ closeAllSigners,
775
+ parseCookieHeader,
776
+ }