dsh-xdpool 2.6.6 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/lib/bin.js +47 -30
- package/lib/client.js +632 -25
- package/lib/index.js +3342 -747
- package/package.json +1 -1
- package/vendor/channel-pack/pack.js +57 -4
package/lib/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
+
import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, hostname, tmpdir } from "node:os";
|
|
2
5
|
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
-
import z from "@deepseek-ai/schemastery";
|
|
4
6
|
import crypto, { createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
|
-
import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
|
|
6
7
|
import { chmod, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
7
|
-
import
|
|
8
|
-
import { execFile, execFileSync } from "node:child_process";
|
|
8
|
+
import z from "@deepseek-ai/schemastery";
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
10
|
import { createProvider } from "@earendil-works/pi-ai";
|
|
11
11
|
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
|
|
@@ -24,6 +24,2673 @@ function creditReservesWith(current, accountId, reserve) {
|
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
26
|
//#endregion
|
|
27
|
+
//#region src/doubao-auth.ts
|
|
28
|
+
/**
|
|
29
|
+
* Doubao sign-in, done the way the reference implementation does it.
|
|
30
|
+
*
|
|
31
|
+
* WHAT WAS WRONG BEFORE
|
|
32
|
+
*
|
|
33
|
+
* An earlier attempt called Doubao's `chat/completion` with a hand-built body and the user's
|
|
34
|
+
* own browser cookies, and was answered `710020202 common invalid param` for every shape it
|
|
35
|
+
* tried. That failure looked like a payload problem and was actually three missing REQUEST
|
|
36
|
+
* DETAILS, each of which silently turns a working session into a refusal:
|
|
37
|
+
*
|
|
38
|
+
* 1. `User-Agent` must end with `SamanthaDoubao/<version>` — the desktop client identifies
|
|
39
|
+
* itself that way, and the upstream checks it.
|
|
40
|
+
* 2. `Referer` must be `chrome://doubao-chat/`, NOT an https URL. A web referer marks the
|
|
41
|
+
* caller as a browser rather than the app.
|
|
42
|
+
* 3. `sec-ch-ua` must carry the client's real brand string.
|
|
43
|
+
*
|
|
44
|
+
* Get any of them wrong and the answer is `710022004 rate limited`, which reads as throttling
|
|
45
|
+
* and is not — the request was never accepted in the first place.
|
|
46
|
+
*
|
|
47
|
+
* No `a_bogus` signature is needed. Measured against the live service: a request whose
|
|
48
|
+
* signature is deliberately corrupted still answers 200, because only the cookie matters for
|
|
49
|
+
* the endpoints used here.
|
|
50
|
+
*
|
|
51
|
+
* HOW THE SESSION IS OBTAINED
|
|
52
|
+
*
|
|
53
|
+
* Doubao's own QR entrance is closed (`2035 非法请求`), so there is no scan endpoint to call.
|
|
54
|
+
* What works is a real Chromium window driven over the DevTools protocol: the user scans or
|
|
55
|
+
* enters a phone code at their own pace, and `Storage.getCookies` — which is BROWSER-scoped,
|
|
56
|
+
* so one call returns every cookie without attaching to a page that may still be redirecting
|
|
57
|
+
* — harvests the jar. The dedicated profile persists, so the second visit usually needs no
|
|
58
|
+
* scan at all.
|
|
59
|
+
*
|
|
60
|
+
* @module dsh-xdpool/doubao-auth
|
|
61
|
+
*/
|
|
62
|
+
/** The cookies a usable session needs. `sid_guard` is preferred but not required. */
|
|
63
|
+
const REQUIRED = [
|
|
64
|
+
"sessionid",
|
|
65
|
+
"sessionid_ss",
|
|
66
|
+
"sid_tt",
|
|
67
|
+
"uid_tt"
|
|
68
|
+
];
|
|
69
|
+
/** Domains whose cookies belong to Doubao; the passport jar spans several. */
|
|
70
|
+
const DOUBAO_DOMAIN = /(^|\.)(doubao|bytedance|zijieapi)\.com$/iu;
|
|
71
|
+
/** The page that mints the jar. */
|
|
72
|
+
const DOUBAO_LOGIN_URL = "https://www.doubao.com/chat/";
|
|
73
|
+
/** Where the dedicated Chromium profile lives. Persisted on purpose. */
|
|
74
|
+
function browserProfileDir() {
|
|
75
|
+
return join(homedir(), ".dsh", "doubao-browser-profile");
|
|
76
|
+
}
|
|
77
|
+
/** The port the sign-in browser listens on. Unusual enough to avoid a real session. */
|
|
78
|
+
const DEBUG_PORT = 9333;
|
|
79
|
+
/** Browsers that can be driven, in the order they are preferred. */
|
|
80
|
+
const CANDIDATES = [
|
|
81
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
82
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
|
83
|
+
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
|
84
|
+
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
|
|
85
|
+
];
|
|
86
|
+
/** The first installed browser, or undefined. */
|
|
87
|
+
function findBrowser() {
|
|
88
|
+
for (const candidate of CANDIDATES) if (existsSync(candidate)) return candidate;
|
|
89
|
+
const local = process.env["LOCALAPPDATA"];
|
|
90
|
+
if (local !== void 0) for (const name of ["Google\\Chrome\\Application\\chrome.exe", "Microsoft\\Edge\\Application\\msedge.exe"]) {
|
|
91
|
+
const path = join(local, name);
|
|
92
|
+
if (existsSync(path)) return path;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Whether a stored session has the cookie that matters. */
|
|
96
|
+
function sessionUsable(session) {
|
|
97
|
+
if (session === void 0) return false;
|
|
98
|
+
const sessionId = session.cookies["sessionid"];
|
|
99
|
+
return typeof sessionId === "string" && sessionId !== "";
|
|
100
|
+
}
|
|
101
|
+
/** The `Cookie:` header value for a session. */
|
|
102
|
+
function cookieHeader(session) {
|
|
103
|
+
return Object.entries(session.cookies).map(([name, value]) => `${name}=${value}`).join("; ");
|
|
104
|
+
}
|
|
105
|
+
/** The client version the reference implementation was measured against. */
|
|
106
|
+
const DOUBAO_VERSION$1 = "2.31.4";
|
|
107
|
+
/** Sleep for a moment without pulling in a helper. */
|
|
108
|
+
function sleep$2(ms) {
|
|
109
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
110
|
+
}
|
|
111
|
+
/** Wait until the browser's DevTools endpoint answers, and return its WebSocket URL. */
|
|
112
|
+
async function waitForDevtools(port, deadline) {
|
|
113
|
+
while (Date.now() < deadline) {
|
|
114
|
+
try {
|
|
115
|
+
const response = await fetch(`http://127.0.0.1:${String(port)}/json/version`, { signal: AbortSignal.timeout(2e3) });
|
|
116
|
+
if (response.ok) {
|
|
117
|
+
const body = await response.json();
|
|
118
|
+
if (typeof body.webSocketDebuggerUrl === "string") return body.webSocketDebuggerUrl;
|
|
119
|
+
}
|
|
120
|
+
} catch {}
|
|
121
|
+
await sleep$2(400);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* One `Storage.getCookies` round-trip.
|
|
126
|
+
*
|
|
127
|
+
* Browser-scoped on purpose: the page target may still be navigating, and attaching to it
|
|
128
|
+
* would race the sign-in redirect chain.
|
|
129
|
+
*/
|
|
130
|
+
async function readCookies(wsUrl, timeoutMs = 15e3) {
|
|
131
|
+
const Ctor = globalThis.WebSocket;
|
|
132
|
+
if (Ctor === void 0) throw new Error("this Node build has no global WebSocket");
|
|
133
|
+
const socket = new Ctor(wsUrl);
|
|
134
|
+
return await new Promise((resolve, reject) => {
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
try {
|
|
137
|
+
socket.close();
|
|
138
|
+
} catch {}
|
|
139
|
+
reject(/* @__PURE__ */ new Error("CDP timeout while reading cookies"));
|
|
140
|
+
}, timeoutMs);
|
|
141
|
+
socket.addEventListener("open", () => {
|
|
142
|
+
socket.send(JSON.stringify({
|
|
143
|
+
id: 1,
|
|
144
|
+
method: "Storage.getCookies",
|
|
145
|
+
params: {}
|
|
146
|
+
}));
|
|
147
|
+
});
|
|
148
|
+
socket.addEventListener("error", () => {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
reject(/* @__PURE__ */ new Error("CDP socket error"));
|
|
151
|
+
});
|
|
152
|
+
socket.addEventListener("message", (event) => {
|
|
153
|
+
const data = event.data;
|
|
154
|
+
if (typeof data !== "string") return;
|
|
155
|
+
let message;
|
|
156
|
+
try {
|
|
157
|
+
message = JSON.parse(data);
|
|
158
|
+
} catch {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (message.id !== 1) return;
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
try {
|
|
164
|
+
socket.close();
|
|
165
|
+
} catch {}
|
|
166
|
+
if (message.error !== void 0) {
|
|
167
|
+
reject(new Error(String(message.error.message ?? "CDP error")));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const cookies = message.result?.cookies;
|
|
171
|
+
resolve(Array.isArray(cookies) ? cookies : []);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Pick the Doubao cookies into `name → value`.
|
|
177
|
+
*
|
|
178
|
+
* First writer wins: CDP lists the more specific host first in practice, and a later
|
|
179
|
+
* `.doubao.com` duplicate must not shadow it.
|
|
180
|
+
*/
|
|
181
|
+
function pickPairs(cookies) {
|
|
182
|
+
const pairs = {};
|
|
183
|
+
for (const cookie of cookies) {
|
|
184
|
+
const name = cookie.name;
|
|
185
|
+
const value = cookie.value;
|
|
186
|
+
const domain = cookie.domain;
|
|
187
|
+
if (typeof name !== "string" || typeof value !== "string" || value === "") continue;
|
|
188
|
+
if (typeof domain !== "string" || !DOUBAO_DOMAIN.test(domain.replace(/^\./u, ""))) continue;
|
|
189
|
+
if (pairs[name] === void 0) pairs[name] = value;
|
|
190
|
+
}
|
|
191
|
+
return pairs;
|
|
192
|
+
}
|
|
193
|
+
/** Kill a spawned browser including its renderer children. */
|
|
194
|
+
function terminate(child) {
|
|
195
|
+
if (child.pid === void 0) return;
|
|
196
|
+
try {
|
|
197
|
+
spawnSync("taskkill", [
|
|
198
|
+
"/PID",
|
|
199
|
+
String(child.pid),
|
|
200
|
+
"/T",
|
|
201
|
+
"/F"
|
|
202
|
+
], { stdio: "ignore" });
|
|
203
|
+
} catch {
|
|
204
|
+
try {
|
|
205
|
+
child.kill();
|
|
206
|
+
} catch {}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Run one interactive sign-in and return the harvested session.
|
|
211
|
+
*
|
|
212
|
+
* The window stays open for the whole budget so the user can finish a scan or a phone code
|
|
213
|
+
* at their own pace; it is closed on the way out either way.
|
|
214
|
+
*/
|
|
215
|
+
async function browserLogin(options = {}) {
|
|
216
|
+
const say = options.onProgress ?? (() => {});
|
|
217
|
+
const exe = findBrowser();
|
|
218
|
+
if (exe === void 0) return {
|
|
219
|
+
ok: false,
|
|
220
|
+
reason: "没找到 Chrome 或 Edge。浏览器扫码登录需要一个 Chromium 内核的浏览器。"
|
|
221
|
+
};
|
|
222
|
+
const timeoutMs = options.timeoutMs ?? 3e5;
|
|
223
|
+
const deadline = Date.now() + timeoutMs;
|
|
224
|
+
const profile = browserProfileDir();
|
|
225
|
+
mkdirSync(profile, { recursive: true });
|
|
226
|
+
const child = spawn(exe, [
|
|
227
|
+
`--remote-debugging-port=${String(DEBUG_PORT)}`,
|
|
228
|
+
`--user-data-dir=${profile}`,
|
|
229
|
+
"--no-first-run",
|
|
230
|
+
"--no-default-browser-check",
|
|
231
|
+
"--disable-features=Translate",
|
|
232
|
+
DOUBAO_LOGIN_URL
|
|
233
|
+
], {
|
|
234
|
+
stdio: "ignore",
|
|
235
|
+
detached: false
|
|
236
|
+
});
|
|
237
|
+
try {
|
|
238
|
+
say("已打开浏览器,请在弹出的窗口里扫码或短信登录…");
|
|
239
|
+
const wsUrl = await waitForDevtools(DEBUG_PORT, Math.min(deadline, Date.now() + 2e4));
|
|
240
|
+
if (wsUrl === void 0) return {
|
|
241
|
+
ok: false,
|
|
242
|
+
reason: `浏览器调试端口 ${String(DEBUG_PORT)} 没起来(可能被占用)。`
|
|
243
|
+
};
|
|
244
|
+
let lastNote = 0;
|
|
245
|
+
while (Date.now() < deadline) {
|
|
246
|
+
let cookies = [];
|
|
247
|
+
try {
|
|
248
|
+
cookies = await readCookies(wsUrl);
|
|
249
|
+
} catch (error) {
|
|
250
|
+
say(`读取登录态失败,重试中:${error instanceof Error ? error.message : String(error)}`);
|
|
251
|
+
await sleep$2(1500);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const pairs = pickPairs(cookies);
|
|
255
|
+
if (pairs["sessionid"] !== void 0) {
|
|
256
|
+
const missing = REQUIRED.filter((name) => pairs[name] === void 0);
|
|
257
|
+
if (missing.length > 0) {
|
|
258
|
+
say(`登录已开始,等待 cookie 补齐(缺 ${missing.join(", ")})…`);
|
|
259
|
+
await sleep$2(1500);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const userAgent = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubao/${DOUBAO_VERSION$1}`;
|
|
263
|
+
say(`已取到登录态(${String(Object.keys(pairs).length)} 条 cookie)`);
|
|
264
|
+
return {
|
|
265
|
+
ok: true,
|
|
266
|
+
session: {
|
|
267
|
+
cookies: pairs,
|
|
268
|
+
userAgent,
|
|
269
|
+
savedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
if (Date.now() - lastNote > 1e4) {
|
|
274
|
+
lastNote = Date.now();
|
|
275
|
+
say(`… 等待扫码(已看到 ${String(cookies.length)} 条浏览器 cookie)`);
|
|
276
|
+
}
|
|
277
|
+
await sleep$2(2e3);
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
ok: false,
|
|
281
|
+
reason: "等待登录超时。扫码完成后请重试。"
|
|
282
|
+
};
|
|
283
|
+
} finally {
|
|
284
|
+
terminate(child);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Read the session out of the sign-in browser WITHOUT opening it.
|
|
289
|
+
*
|
|
290
|
+
* Used by the background poll: the window is already open (the user started a sign-in), and
|
|
291
|
+
* the card asks every couple of seconds whether the jar is complete yet. Returns undefined
|
|
292
|
+
* when there is nothing usable — which is the ordinary answer while the user is still typing.
|
|
293
|
+
*/
|
|
294
|
+
async function readExistingSession() {
|
|
295
|
+
let wsUrl;
|
|
296
|
+
try {
|
|
297
|
+
const response = await fetch(`http://127.0.0.1:${String(DEBUG_PORT)}/json/version`, { signal: AbortSignal.timeout(1500) });
|
|
298
|
+
if (!response.ok) return void 0;
|
|
299
|
+
const body = await response.json();
|
|
300
|
+
if (typeof body.webSocketDebuggerUrl === "string") wsUrl = body.webSocketDebuggerUrl;
|
|
301
|
+
} catch {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (wsUrl === void 0) return void 0;
|
|
305
|
+
try {
|
|
306
|
+
const pairs = pickPairs(await readCookies(wsUrl, 4e3));
|
|
307
|
+
if (pairs["sessionid"] === void 0) return void 0;
|
|
308
|
+
return {
|
|
309
|
+
cookies: pairs,
|
|
310
|
+
userAgent: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubao/${DOUBAO_VERSION$1}`,
|
|
311
|
+
savedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
312
|
+
};
|
|
313
|
+
} catch {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/doubao-catalog.ts
|
|
319
|
+
const DOUBAO_REASONING_LEVELS = [
|
|
320
|
+
{
|
|
321
|
+
id: "low",
|
|
322
|
+
name: "低",
|
|
323
|
+
level: 3,
|
|
324
|
+
verified: true
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
id: "mid",
|
|
328
|
+
name: "中",
|
|
329
|
+
level: 4,
|
|
330
|
+
verified: true
|
|
331
|
+
},
|
|
332
|
+
{
|
|
333
|
+
id: "high",
|
|
334
|
+
name: "高",
|
|
335
|
+
level: 5,
|
|
336
|
+
verified: true
|
|
337
|
+
},
|
|
338
|
+
{
|
|
339
|
+
id: "xhigh",
|
|
340
|
+
name: "极高",
|
|
341
|
+
level: 6,
|
|
342
|
+
verified: false
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
id: "max",
|
|
346
|
+
name: "最高",
|
|
347
|
+
level: 7,
|
|
348
|
+
verified: false
|
|
349
|
+
}
|
|
350
|
+
];
|
|
351
|
+
/** The level used when a request names none. Verified on the wire. */
|
|
352
|
+
const DEFAULT_REASONING_LEVEL_ID = "high";
|
|
353
|
+
/** Reasoning level for an id, falling back to the default. */
|
|
354
|
+
function findReasoningLevel(id) {
|
|
355
|
+
const known = DOUBAO_REASONING_LEVELS.find((level) => level.id === id);
|
|
356
|
+
if (known !== void 0) return known;
|
|
357
|
+
if (id !== void 0 && /^\d{1,3}$/.test(id)) {
|
|
358
|
+
const ordinal = Number(id);
|
|
359
|
+
const named = DOUBAO_REASONING_LEVELS.find((level) => level.level === ordinal);
|
|
360
|
+
if (named !== void 0) return named;
|
|
361
|
+
return {
|
|
362
|
+
id,
|
|
363
|
+
name: String(ordinal),
|
|
364
|
+
level: ordinal,
|
|
365
|
+
verified: false
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
return DOUBAO_REASONING_LEVELS.find((level) => level.id === DEFAULT_REASONING_LEVEL_ID);
|
|
369
|
+
}
|
|
370
|
+
/** The catalog entry for a wire ordinal, or undefined for one it does not know. */
|
|
371
|
+
function reasoningLevelOf(ordinal) {
|
|
372
|
+
if (ordinal === void 0) return void 0;
|
|
373
|
+
return DOUBAO_REASONING_LEVELS.find((level) => level.level === ordinal);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* The wire spelling of an ordinal.
|
|
377
|
+
*
|
|
378
|
+
* `model_extra_params.reasoning_effort` for 2.1 Lite is a STRING in the captured
|
|
379
|
+
* request, and that string is the level's name-id, not its number. An ordinal
|
|
380
|
+
* with no catalog entry falls back to its own decimal form, so a level Doubao
|
|
381
|
+
* adds later still travels instead of snapping back to 高.
|
|
382
|
+
*/
|
|
383
|
+
function levelIdOf(ordinal) {
|
|
384
|
+
return reasoningLevelOf(ordinal)?.id ?? String(ordinal);
|
|
385
|
+
}
|
|
386
|
+
/** `need_deep_think` value for the switch state. */
|
|
387
|
+
function needDeepThinkValue(deepThink) {
|
|
388
|
+
return deepThink ? 3 : 0;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Doubao's skill table, transcribed verbatim from the client bundle
|
|
392
|
+
* (`{FreeChat:0, SkillWrite:2, SkillImageGen:3, …}`), not inferred.
|
|
393
|
+
*
|
|
394
|
+
* `skill_id` is the decimal string of `skill_type`; the two are ALWAYS the same
|
|
395
|
+
* number, which is why a plain turn carries `{"skill_id":"0","skill_type":0}`.
|
|
396
|
+
* On the wire it is a JSON STRING inside `ext.input_skill`.
|
|
397
|
+
*
|
|
398
|
+
* There is no separate HTTP endpoint for text-to-image in the client — the only
|
|
399
|
+
* generation URL is `/creativity/canvas/exec`, which is the image EDITOR
|
|
400
|
+
* (cutout / outpaint / layer split). So a skill turn must go through
|
|
401
|
+
* `/chat/completion`, and it does: verified 2026-11-02, `skill_type: 3` returns
|
|
402
|
+
* real `rc_gen_image/*.jpeg` artefacts from Seedream 5.0.
|
|
403
|
+
*/
|
|
404
|
+
const DOUBAO_SKILLS = {
|
|
405
|
+
freeChat: 0,
|
|
406
|
+
write: 2,
|
|
407
|
+
imageGen: 3,
|
|
408
|
+
search: 4,
|
|
409
|
+
translate: 5,
|
|
410
|
+
read: 6,
|
|
411
|
+
webpage: 7,
|
|
412
|
+
deepSearch: 8,
|
|
413
|
+
musicGen: 9,
|
|
414
|
+
edu: 11,
|
|
415
|
+
codeInterpreter: 13,
|
|
416
|
+
codeAssistant: 16,
|
|
417
|
+
videoGeneration: 17,
|
|
418
|
+
aiPPT: 18
|
|
419
|
+
};
|
|
420
|
+
/** The `ext.input_skill` JSON string for a skill; undefined means plain chat. */
|
|
421
|
+
function inputSkillOf(skill) {
|
|
422
|
+
if (skill === void 0 || skill === "freeChat") return void 0;
|
|
423
|
+
const type = DOUBAO_SKILLS[skill];
|
|
424
|
+
return JSON.stringify({
|
|
425
|
+
skill_id: String(type),
|
|
426
|
+
skill_type: type,
|
|
427
|
+
variables: {}
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* DSH-side alias for "generate an image".
|
|
432
|
+
*
|
|
433
|
+
* NOT a Doubao `model_item_key` — Doubao has no model by this name. Selecting it
|
|
434
|
+
* makes the shim send an ordinary chat turn with `input_skill: imageGen`, and
|
|
435
|
+
* Doubao answers with Seedream. Keeping it in the catalog is what puts 生图 in
|
|
436
|
+
* DSH's model picker without inventing a second UI.
|
|
437
|
+
*/
|
|
438
|
+
const DOUBAO_IMAGE_MODEL_ID = "image-gen";
|
|
439
|
+
/**
|
|
440
|
+
* IMAGEGEN_LABEL_OVERLAY: 生图版本名以插件根目录的 image-models.json 为准,
|
|
441
|
+
* 该文件由 doubao_imagemodels.py --sync 从服务端 get_item_conf 生成。
|
|
442
|
+
*/
|
|
443
|
+
function imageModelLabelFromOverlay() {
|
|
444
|
+
try {
|
|
445
|
+
const url = new URL("../image-models.json", import.meta.url);
|
|
446
|
+
const parsed = JSON.parse(readFileSync(url, "utf8"));
|
|
447
|
+
return typeof parsed.label === "string" && parsed.label !== "" ? parsed.label : void 0;
|
|
448
|
+
} catch {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* The entries DSH may offer.
|
|
454
|
+
*
|
|
455
|
+
* WHY THESE ENTRIES. Doubao groups models by MODE, and the model list is per-mode:
|
|
456
|
+
*
|
|
457
|
+
* 对话 → 豆包 快速 (0), 豆包 2.1 Turbo·专家 (3)
|
|
458
|
+
* 工作任务 → 自动 (9), 2.1 Lite (seed-lite-7b), 2.1 Pro (5), Turbo (3)
|
|
459
|
+
*
|
|
460
|
+
* The 「工作任务」 group (`seed-lite-7b`, `5`, `9`) runs through `Agent-GeneralTask`
|
|
461
|
+
* (`mode_id: "3"`, `agent_mode: 1`) and is accompanied by an HTTP `tool_local`
|
|
462
|
+
* workspace responder (`msg/ack` -> `upload_command_result` -> `msg/complete`)
|
|
463
|
+
* so external turns complete without `710010702`.
|
|
464
|
+
*
|
|
465
|
+
* MEASURED, 2026-10-22: `model_item_key` is forwarded verbatim (the server stores
|
|
466
|
+
* it on the message), but in 对话 mode it does NOT change what answers —
|
|
467
|
+
* 0 / 3 / 5 / seed-lite-7b AND a deliberately bogus key all returned answers of
|
|
468
|
+
* indistinguishable length and latency (12.3–14.0 s). So this list is honest
|
|
469
|
+
* about what the PICKER can offer; it does not claim per-key routing.
|
|
470
|
+
*
|
|
471
|
+
* 「豆包 快速」 leads because it is the app's own chat-mode default, so an
|
|
472
|
+
* unconfigured install reproduces the app rather than something that merely
|
|
473
|
+
* happens to work.
|
|
474
|
+
*/
|
|
475
|
+
const DOUBAO_MODELS = [
|
|
476
|
+
{
|
|
477
|
+
id: "0",
|
|
478
|
+
name: "豆包 快速",
|
|
479
|
+
reasoning: false
|
|
480
|
+
},
|
|
481
|
+
{
|
|
482
|
+
id: "3",
|
|
483
|
+
name: "豆包 2.1 Turbo",
|
|
484
|
+
badge: "专家",
|
|
485
|
+
reasoning: true
|
|
486
|
+
},
|
|
487
|
+
{
|
|
488
|
+
id: "seed-lite-7b",
|
|
489
|
+
name: "豆包 2.1 Lite",
|
|
490
|
+
badge: "工作任务",
|
|
491
|
+
reasoning: true,
|
|
492
|
+
taskMode: true
|
|
493
|
+
},
|
|
494
|
+
{
|
|
495
|
+
id: "5",
|
|
496
|
+
name: "豆包 2.1 Pro",
|
|
497
|
+
badge: "工作任务",
|
|
498
|
+
reasoning: true,
|
|
499
|
+
taskMode: true
|
|
500
|
+
},
|
|
501
|
+
{
|
|
502
|
+
id: "9",
|
|
503
|
+
name: "自动",
|
|
504
|
+
badge: "工作任务",
|
|
505
|
+
reasoning: true,
|
|
506
|
+
taskMode: true
|
|
507
|
+
},
|
|
508
|
+
{
|
|
509
|
+
id: DOUBAO_IMAGE_MODEL_ID,
|
|
510
|
+
name: imageModelLabelFromOverlay() ?? "豆包 生图(Seedream 5.5)",
|
|
511
|
+
reasoning: true
|
|
512
|
+
}
|
|
513
|
+
];
|
|
514
|
+
/** True when `id` is a 「工作任务」-mode model (`seed-lite-7b`, `5`, `9`). */
|
|
515
|
+
function isTaskModel(id) {
|
|
516
|
+
if (id === void 0) return false;
|
|
517
|
+
return DOUBAO_MODELS.some((model) => model.id === id && model.taskMode === true);
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Catalog entry for a model id, falling back to {@link DOUBAO_DEFAULT_MODEL_ID}.
|
|
521
|
+
*
|
|
522
|
+
* An id the catalog does not know resolves to the default rather than throwing:
|
|
523
|
+
* a stale id in a saved session should degrade to a working model, not break
|
|
524
|
+
* the request. `describeRequestedModel` in the shim is what surfaces the miss.
|
|
525
|
+
*/
|
|
526
|
+
function findDoubaoModel(id) {
|
|
527
|
+
if (id === void 0) return DOUBAO_MODELS.find((model) => model.id === "0");
|
|
528
|
+
const known = DOUBAO_MODELS.find((model) => model.id === id);
|
|
529
|
+
if (known !== void 0) return known;
|
|
530
|
+
return {
|
|
531
|
+
id,
|
|
532
|
+
name: id,
|
|
533
|
+
reasoning: true
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
//#endregion
|
|
537
|
+
//#region src/doubao-upstream.ts
|
|
538
|
+
/**
|
|
539
|
+
* Doubao upstream client.
|
|
540
|
+
*
|
|
541
|
+
* Endpoint: POST https://www.doubao.com/chat/completion
|
|
542
|
+
*
|
|
543
|
+
* Three request details decide whether the call succeeds or is challenged with
|
|
544
|
+
* a slider CAPTCHA (verified in M2 — getting any of them wrong silently turns a
|
|
545
|
+
* working session into `710022004 rate limited`):
|
|
546
|
+
*
|
|
547
|
+
* 1. User-Agent must carry the `SamanthaDoubao/<version>` suffix.
|
|
548
|
+
* 2. Referer must be the `chrome://doubao-chat/` scheme, NOT an https URL.
|
|
549
|
+
* 3. sec-ch-ua must use the real client-hints brand string.
|
|
550
|
+
*
|
|
551
|
+
* No `a_bogus` signature is required; the server accepts a cookie-authenticated
|
|
552
|
+
* request without it.
|
|
553
|
+
*
|
|
554
|
+
* The response is a ByteDance-specific streaming variant, NOT standard SSE.
|
|
555
|
+
* Frames are three lines — `id:`, `event:`, `data:` — followed by a blank
|
|
556
|
+
* line, so a generic `data:`-only SSE parser silently drops everything.
|
|
557
|
+
*/
|
|
558
|
+
/**
|
|
559
|
+
* The reference implementation's credential shape, adapted onto this plugin's session.
|
|
560
|
+
*
|
|
561
|
+
* Its `credentials` carry a `pairs` map plus a ready-made header; this plugin's session
|
|
562
|
+
* carries the same map and builds the header on demand. `toCredentials` bridges them so the
|
|
563
|
+
* upstream code below stays exactly as measured — every function it calls here was verified
|
|
564
|
+
* against the live service, and rewriting them would throw that evidence away.
|
|
565
|
+
*/
|
|
566
|
+
function toCredentials(session) {
|
|
567
|
+
return {
|
|
568
|
+
pairs: new Map(Object.entries(session.cookies)),
|
|
569
|
+
header: cookieHeader(session),
|
|
570
|
+
userAgent: session.userAgent
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* How a session reaches the upstream.
|
|
575
|
+
*
|
|
576
|
+
* The reference implementation loads a sealed credential file; this plugin keeps one session
|
|
577
|
+
* in memory and in its own store, and the route injects it. A module-level holder is what lets
|
|
578
|
+
* the unchanged upstream code call `loadDoubaoCredentials()` and still be given THIS plugin's
|
|
579
|
+
* session — the alternative is threading a session parameter through a thousand lines that
|
|
580
|
+
* were verified as they stand.
|
|
581
|
+
*/
|
|
582
|
+
let activeSession;
|
|
583
|
+
/** Point the upstream at a session. Called by the routes and by startup restore. */
|
|
584
|
+
function setDoubaoSession(session) {
|
|
585
|
+
activeSession = session;
|
|
586
|
+
}
|
|
587
|
+
/** Throw when there is no session, with the sentence the card shows. */
|
|
588
|
+
function requireDoubaoCredentials() {
|
|
589
|
+
if (activeSession === void 0 || !sessionUsable(activeSession)) throw new Error("还没有浏览器登录态。请在豆包卡片里点「重新登录」扫码一次。");
|
|
590
|
+
return toCredentials(activeSession);
|
|
591
|
+
}
|
|
592
|
+
/** The reference's loader, answered from this plugin's session. */
|
|
593
|
+
function loadDoubaoCredentials() {
|
|
594
|
+
return requireDoubaoCredentials();
|
|
595
|
+
}
|
|
596
|
+
/** The reference's cookie-name list, as this plugin knows it. */
|
|
597
|
+
const REQUIRED_COOKIE_NAMES = [
|
|
598
|
+
"sessionid",
|
|
599
|
+
"sid_tt",
|
|
600
|
+
"uid_tt"
|
|
601
|
+
];
|
|
602
|
+
const CHAT_ENDPOINT = "https://www.doubao.com/chat/completion";
|
|
603
|
+
const QUOTA_ENDPOINT = "https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/";
|
|
604
|
+
const TOOL_LOCAL_ACK_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/ack";
|
|
605
|
+
const TOOL_LOCAL_UPLOAD_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/upload_command_result";
|
|
606
|
+
const TOOL_LOCAL_COMPLETE_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/complete";
|
|
607
|
+
/**
|
|
608
|
+
* Client version strings. These are the desktop app build this was last
|
|
609
|
+
* verified against (M9), and they MOVE with every Doubao release — a newer app
|
|
610
|
+
* sends different values here and a very old one will eventually stop being
|
|
611
|
+
* accepted. Re-check them whenever Doubao auto-updates; the risk-control layer
|
|
612
|
+
* compares them against the session it sees.
|
|
613
|
+
*/
|
|
614
|
+
const DOUBAO_VERSION = "2.31.4";
|
|
615
|
+
/**
|
|
616
|
+
* Frozen, non-secret client identity.
|
|
617
|
+
*
|
|
618
|
+
* These are constant across Doubao sessions and are NOT credentials. Keeping
|
|
619
|
+
* them fixed is what makes an external request look like the same install to
|
|
620
|
+
* the risk-control layer.
|
|
621
|
+
*/
|
|
622
|
+
const CLIENT_PARAMS = {
|
|
623
|
+
aid: "582478",
|
|
624
|
+
real_aid: "582478",
|
|
625
|
+
version_code: "20800",
|
|
626
|
+
pc_version: DOUBAO_VERSION,
|
|
627
|
+
device_id: "2697515174213273",
|
|
628
|
+
tea_uuid: "2697515174213273",
|
|
629
|
+
web_id: "7677868049198630415",
|
|
630
|
+
fp: "verify_2697515174213273",
|
|
631
|
+
chromium_version: "147.0.7727.149",
|
|
632
|
+
runtime_version: "3.39.0",
|
|
633
|
+
channel: "win",
|
|
634
|
+
language: "zh",
|
|
635
|
+
region: "CN",
|
|
636
|
+
sys_region: "CN",
|
|
637
|
+
tz_name: "Asia/Shanghai",
|
|
638
|
+
pkg_type: "release_version",
|
|
639
|
+
client_platform: "pc_client",
|
|
640
|
+
device_platform: "web",
|
|
641
|
+
doubao_device_platform: "desktop",
|
|
642
|
+
web_platform: "desktop",
|
|
643
|
+
samantha_web: "1",
|
|
644
|
+
"use-olympus-account": "1"
|
|
645
|
+
};
|
|
646
|
+
/** The default Doubao assistant; content routing means the model is chosen server-side. */
|
|
647
|
+
const DEFAULT_BOT_ID = "7338286299411103781";
|
|
648
|
+
/** Headers that make an external request indistinguishable from the app's. */
|
|
649
|
+
function buildHeaders(credentials, extra = {}) {
|
|
650
|
+
return {
|
|
651
|
+
"User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubao/${DOUBAO_VERSION}`,
|
|
652
|
+
Referer: "chrome://doubao-chat/",
|
|
653
|
+
accept: "*/*",
|
|
654
|
+
"accept-language": "zh-CN,zh;q=0.9",
|
|
655
|
+
"sec-ch-ua": "\"Chromium\";v=\"147\", \"Not.A/Brand\";v=\"8\"",
|
|
656
|
+
"sec-ch-ua-mobile": "?0",
|
|
657
|
+
"sec-ch-ua-platform": "\"Windows\"",
|
|
658
|
+
"sec-fetch-dest": "empty",
|
|
659
|
+
"sec-fetch-mode": "cors",
|
|
660
|
+
"sec-fetch-site": "same-origin",
|
|
661
|
+
"agw-js-conv": "str",
|
|
662
|
+
"x-flow-trace": `${randomUUID().replace(/-/g, "")}-${randomUUID().replace(/-/g, "")}-01`,
|
|
663
|
+
"last-event-id": "undefined",
|
|
664
|
+
cookie: applyRenewals(credentials.header),
|
|
665
|
+
...extra
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
function buildQueryUrl(endpoint, msToken) {
|
|
669
|
+
const params = new URLSearchParams({
|
|
670
|
+
...CLIENT_PARAMS,
|
|
671
|
+
web_tab_id: randomUUID()
|
|
672
|
+
});
|
|
673
|
+
if (msToken) params.set("msToken", msToken);
|
|
674
|
+
return `${endpoint}?${params.toString()}`;
|
|
675
|
+
}
|
|
676
|
+
var DoubaoUpstreamError = class extends Error {
|
|
677
|
+
code;
|
|
678
|
+
rateLimited;
|
|
679
|
+
httpStatus;
|
|
680
|
+
transport;
|
|
681
|
+
truncated;
|
|
682
|
+
kindHint;
|
|
683
|
+
constructor(message, code, rateLimited = false, meta = {}) {
|
|
684
|
+
super(message);
|
|
685
|
+
this.code = code;
|
|
686
|
+
this.rateLimited = rateLimited;
|
|
687
|
+
this.name = "DoubaoUpstreamError";
|
|
688
|
+
this.httpStatus = meta.httpStatus;
|
|
689
|
+
this.transport = meta.transport === true;
|
|
690
|
+
this.truncated = meta.truncated === true;
|
|
691
|
+
this.kindHint = meta.kind;
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
/**
|
|
695
|
+
* Stable-per-process id that rides along as `client_env_id`.
|
|
696
|
+
*
|
|
697
|
+
* The client generates one per app environment; ours is per host process so a
|
|
698
|
+
* restart looks like a new environment, which is exactly what it is.
|
|
699
|
+
*/
|
|
700
|
+
const CLIENT_ENV_ID = randomUUID();
|
|
701
|
+
/** Whether a request asks for local-PC task mode. Default: OFF — see below. */
|
|
702
|
+
function taskModeEnabled(options) {
|
|
703
|
+
if (options.taskMode !== void 0) return options.taskMode;
|
|
704
|
+
if (isTaskModel(options.modelKey)) return true;
|
|
705
|
+
const flag = process.env.DSH_DOUBAO_TASK;
|
|
706
|
+
return flag === void 0 ? false : /^(1|true|on|yes)$/i.test(flag.trim());
|
|
707
|
+
}
|
|
708
|
+
/** The directory this machine declares to the task runtime. */
|
|
709
|
+
function taskWorkspaceOf(options) {
|
|
710
|
+
return options.workspace ?? process.env.DSH_DOUBAO_WORKSPACE ?? process.cwd();
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Build `ext.general_task_param` — the field that makes a turn a 工作任务.
|
|
714
|
+
*
|
|
715
|
+
* Transcribed field-for-field from a real 「工作任务 · 本地电脑」 request the
|
|
716
|
+
* desktop client sent on 2026-09-15 (recovered from the app's own IndexedDB
|
|
717
|
+
* message store), then reduced to what is portable:
|
|
718
|
+
*
|
|
719
|
+
* thread_local_message_id the local message id being submitted
|
|
720
|
+
* client_option the workspace and the sandbox/authorisation policy
|
|
721
|
+
* runtime_type 2 — Local_PC; the cloud VM would be 1
|
|
722
|
+
* agent_task_param the same facts again, device-side
|
|
723
|
+
* agent_task_param_change all false: nothing is being switched mid-thread
|
|
724
|
+
*
|
|
725
|
+
* Paths are computed from THIS machine rather than copied, because the cloud
|
|
726
|
+
* plans against them: a workspace that does not exist here would make the task
|
|
727
|
+
* fail inside the runtime instead of at submit time. `local_device_id` and
|
|
728
|
+
* `local_app_id` reuse the frozen client identity already in {@link CLIENT_PARAMS}
|
|
729
|
+
* — the captured request carries the same two values, so they are the same
|
|
730
|
+
* install identity and not per-request state.
|
|
731
|
+
*/
|
|
732
|
+
function buildGeneralTaskParam(localMessageId, workspace, prompt) {
|
|
733
|
+
const agentWorkspace = join(tmpdir(), "dsh-doubao-agent-workspace");
|
|
734
|
+
return {
|
|
735
|
+
thread_local_message_id: [localMessageId],
|
|
736
|
+
client_option: {
|
|
737
|
+
shared_folder_path: [workspace, agentWorkspace],
|
|
738
|
+
enable_sandbox: true,
|
|
739
|
+
os: process.platform === "win32" ? "Windows" : process.platform,
|
|
740
|
+
client_env_id: CLIENT_ENV_ID,
|
|
741
|
+
sandbox_id: `route-${randomUUID()}`,
|
|
742
|
+
workspace,
|
|
743
|
+
agent_workspace: {
|
|
744
|
+
agent_workspace: agentWorkspace,
|
|
745
|
+
local_skill_paths: [join(homedir(), "Doubao", "skills"), join(homedir(), ".agents", "skills")]
|
|
746
|
+
},
|
|
747
|
+
sandbox_auth_type: 2
|
|
748
|
+
},
|
|
749
|
+
runtime_type: 2,
|
|
750
|
+
need_modify_conversation: false,
|
|
751
|
+
agent_task_param: {
|
|
752
|
+
runtime_type: 2,
|
|
753
|
+
device_name: hostname(),
|
|
754
|
+
workspace,
|
|
755
|
+
local_device_id: CLIENT_PARAMS.device_id,
|
|
756
|
+
local_app_id: CLIENT_PARAMS.aid,
|
|
757
|
+
sandbox_auth_type: 2
|
|
758
|
+
},
|
|
759
|
+
agent_task_param_change: {
|
|
760
|
+
runtime_changed: false,
|
|
761
|
+
device_changed: false,
|
|
762
|
+
sandbox_auth_type_changed: false
|
|
763
|
+
},
|
|
764
|
+
...prompt !== void 0 ? { task_input_json: JSON.stringify({
|
|
765
|
+
text: prompt,
|
|
766
|
+
files: [],
|
|
767
|
+
skills: []
|
|
768
|
+
}) } : {}
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Build the request body Doubao's chat endpoint expects.
|
|
773
|
+
*
|
|
774
|
+
* The model and the reasoning effort are each written at TWO locations, because
|
|
775
|
+
* that is what the app does and what upstream reads. Writing only one is
|
|
776
|
+
* silently ignored — the request succeeds and the answer comes from whatever
|
|
777
|
+
* the server last used.
|
|
778
|
+
*
|
|
779
|
+
* `general_task_param` is deliberately absent: it carries the desktop app's
|
|
780
|
+
* local sandbox and workspace paths, none of which apply to an external client,
|
|
781
|
+
* and the endpoint has been observed answering correctly without it.
|
|
782
|
+
*/
|
|
783
|
+
/**
|
|
784
|
+
* Add the 「生成图片:」 prefix that Doubao's image skill requires.
|
|
785
|
+
*
|
|
786
|
+
* The desktop app gets this for free: its `chat_ability.ability_param` carries
|
|
787
|
+
* `reply_message_format: "生成图片:%s"`, which rewrites the outgoing text before
|
|
788
|
+
* the request leaves. An external client has no such hook, so the same rewrite
|
|
789
|
+
* happens here. Without it the server treats the turn as ordinary chat and
|
|
790
|
+
* answers with prose instead of drawing.
|
|
791
|
+
*
|
|
792
|
+
* Deliberately ONLY the prefix: appending extra instructions makes Doubao read
|
|
793
|
+
* them as part of the subject and drop the picture entirely (measured).
|
|
794
|
+
*/
|
|
795
|
+
function withImagePrefix(prompt, options = {}) {
|
|
796
|
+
if (!(options.skill === "imageGen" || options.modelKey === "image-gen")) return prompt;
|
|
797
|
+
if (/^\s*(生成图片|生成一张|画一张|画个|绘制)/.test(prompt)) return prompt;
|
|
798
|
+
return `生成图片:${prompt}`;
|
|
799
|
+
}
|
|
800
|
+
function buildChatBody(prompt, options = {}) {
|
|
801
|
+
prompt = withImagePrefix(prompt, options);
|
|
802
|
+
const model = findDoubaoModel(options.modelKey);
|
|
803
|
+
const level = findReasoningLevel(options.reasoningLevel);
|
|
804
|
+
const task = taskModeEnabled(options);
|
|
805
|
+
const taskModelSelected = isTaskModel(model.id) || options.taskMode === true;
|
|
806
|
+
/**
|
|
807
|
+
* Deep-thinking toggle, for probing only.
|
|
808
|
+
*
|
|
809
|
+
* The captured ordinary turn sends `need_deep_think: 0`; the client's 深度思考
|
|
810
|
+
* switch is what turns this on, and the value it sends there has NOT been
|
|
811
|
+
* captured yet. `DSH_DOUBAO_DEEP_THINK=1` reproduces the old 10000+level shape
|
|
812
|
+
* so the resulting stream can be inspected.
|
|
813
|
+
*
|
|
814
|
+
* In 「工作任务」 mode (`seed-lite-7b`, `5`, `9`), captured requests send `10001`.
|
|
815
|
+
*/
|
|
816
|
+
const deepThink = options.deepThink === true || options.deepThink === void 0 && process.env.DSH_DOUBAO_DEEP_THINK === "1";
|
|
817
|
+
const needDeepThink = taskModelSelected && options.deepThink === void 0 ? 10001 : needDeepThinkValue(deepThink);
|
|
818
|
+
/**
|
|
819
|
+
* 2 = 普通对话, 1 = 「工作任务」.
|
|
820
|
+
*
|
|
821
|
+
* CDP-captured from the running client on 2026-10-22. This constant was the
|
|
822
|
+
* bug: the plugin sent 1 for chat, so the server answered every turn as a work
|
|
823
|
+
* task — `Agent-GeneralTask`, then `710010702` because the task runtime used
|
|
824
|
+
* to be the desktop app's own CUA process. Task turns now complete through the
|
|
825
|
+
* `tool_local` responder, which is why `TASK_AGENT_MODE` is safe to send.
|
|
826
|
+
*/
|
|
827
|
+
const agentMode = options.agentMode ?? (task ? 1 : 2);
|
|
828
|
+
const localMessageId = randomUUID();
|
|
829
|
+
/**
|
|
830
|
+
* Mode id the model picker groups by. The captured chat request carries "1" in
|
|
831
|
+
* BOTH `conversation_init_ext` and `aggregate_params`, whereas 「工作任务」
|
|
832
|
+
* models (`seed-lite-7b`, `5`, `9`) carry "3".
|
|
833
|
+
*/
|
|
834
|
+
const modeId = (process.env.DSH_DOUBAO_MODE_ID ?? "").trim() || (task ? "3" : "1");
|
|
835
|
+
const taskParam = task ? buildGeneralTaskParam(localMessageId, taskWorkspaceOf(options), taskModelSelected ? prompt : void 0) : { server_do_compare: true };
|
|
836
|
+
const modelExtraParams = taskModelSelected ? {
|
|
837
|
+
input_token_limit: "256k",
|
|
838
|
+
...model.id === "seed-lite-7b" ? { reasoning_effort: levelIdOf(level.level) } : {}
|
|
839
|
+
} : {};
|
|
840
|
+
return {
|
|
841
|
+
messages: [{
|
|
842
|
+
local_message_id: localMessageId,
|
|
843
|
+
message_status: 0,
|
|
844
|
+
content_block: [{
|
|
845
|
+
block_type: 1e4,
|
|
846
|
+
block_id: randomUUID(),
|
|
847
|
+
parent_id: "",
|
|
848
|
+
meta_info: [],
|
|
849
|
+
append_fields: [],
|
|
850
|
+
content: {
|
|
851
|
+
text_block: {
|
|
852
|
+
text: prompt,
|
|
853
|
+
icon_url: "",
|
|
854
|
+
icon_url_dark: "",
|
|
855
|
+
summary: ""
|
|
856
|
+
},
|
|
857
|
+
pc_event_block: ""
|
|
858
|
+
}
|
|
859
|
+
}]
|
|
860
|
+
}],
|
|
861
|
+
option: {
|
|
862
|
+
send_message_scene: "",
|
|
863
|
+
create_time_ms: Date.now(),
|
|
864
|
+
collect_id: "",
|
|
865
|
+
is_audio: false,
|
|
866
|
+
answer_with_suggest: false,
|
|
867
|
+
agent_mode: agentMode,
|
|
868
|
+
tts_switch: false,
|
|
869
|
+
need_deep_think: needDeepThink,
|
|
870
|
+
click_clear_context: false,
|
|
871
|
+
from_suggest: false,
|
|
872
|
+
is_regen: false,
|
|
873
|
+
is_replace: false,
|
|
874
|
+
is_from_click_option: false,
|
|
875
|
+
is_from_click_softlink: false,
|
|
876
|
+
disable_sse_cache: false,
|
|
877
|
+
select_text_action: "",
|
|
878
|
+
is_select_text: false,
|
|
879
|
+
resend_for_regen: false,
|
|
880
|
+
scene_type: 0,
|
|
881
|
+
unique_key: randomUUID(),
|
|
882
|
+
start_seq: 0,
|
|
883
|
+
need_create_conversation: options.continueConversation !== true,
|
|
884
|
+
conversation_init_option: { need_ack_conversation: true },
|
|
885
|
+
...taskModelSelected && options.continueConversation !== true ? { conversation_mode: 2 } : {},
|
|
886
|
+
conversation_init_ext: {
|
|
887
|
+
model_item_key: model.id,
|
|
888
|
+
reasoning_effort: String(level.level),
|
|
889
|
+
mode_id: modeId
|
|
890
|
+
},
|
|
891
|
+
regen_query_id: [],
|
|
892
|
+
edit_query_id: [],
|
|
893
|
+
regen_instruction: "",
|
|
894
|
+
no_replace_for_regen: false,
|
|
895
|
+
message_from: 0,
|
|
896
|
+
shared_app_name: "",
|
|
897
|
+
shared_app_id: "",
|
|
898
|
+
sse_recv_event_options: { support_chunk_delta: true },
|
|
899
|
+
support_lazy_fetch_stream: true,
|
|
900
|
+
is_ai_playground: false,
|
|
901
|
+
is_old_user: true,
|
|
902
|
+
general_task_param: taskParam,
|
|
903
|
+
recovery_option: {
|
|
904
|
+
is_recovery: false,
|
|
905
|
+
req_create_time_sec: Math.floor(Date.now() / 1e3),
|
|
906
|
+
append_sse_event_scene: 0
|
|
907
|
+
},
|
|
908
|
+
message_storage_type: 0,
|
|
909
|
+
related_deleted_message_ids: {},
|
|
910
|
+
connector_info_list: [],
|
|
911
|
+
model_config: {
|
|
912
|
+
model_item_key: model.id,
|
|
913
|
+
model_extra_params: modelExtraParams,
|
|
914
|
+
reasoning_effort: level.level
|
|
915
|
+
},
|
|
916
|
+
aggregate_params: {
|
|
917
|
+
mention_skill_list: "[]",
|
|
918
|
+
mention_plugin_list: "[]",
|
|
919
|
+
mention_ext: "[{}]",
|
|
920
|
+
conversation_mode: taskModelSelected && options.continueConversation !== true ? "2" : deepThink ? "1" : "",
|
|
921
|
+
mode_id: modeId,
|
|
922
|
+
model_item_key: model.id,
|
|
923
|
+
agent_mode: String(agentMode),
|
|
924
|
+
reasoning_effort: String(level.level),
|
|
925
|
+
provider_id: ""
|
|
926
|
+
}
|
|
927
|
+
},
|
|
928
|
+
client_meta: {
|
|
929
|
+
local_conversation_id: `local_${randomUUID()}`,
|
|
930
|
+
conversation_id: options.conversationId ?? "",
|
|
931
|
+
bot_id: DEFAULT_BOT_ID,
|
|
932
|
+
last_section_id: "",
|
|
933
|
+
last_message_index: null,
|
|
934
|
+
local_permissions: [
|
|
935
|
+
{
|
|
936
|
+
permission_name: "ACCESS_COARSE_LOCATION",
|
|
937
|
+
status: 1
|
|
938
|
+
},
|
|
939
|
+
{
|
|
940
|
+
permission_name: "ACCESS_FINE_LOCATION",
|
|
941
|
+
status: 1
|
|
942
|
+
},
|
|
943
|
+
{
|
|
944
|
+
permission_name: "ACCESS_BACKGROUND_LOCATION",
|
|
945
|
+
status: 1
|
|
946
|
+
}
|
|
947
|
+
]
|
|
948
|
+
},
|
|
949
|
+
user_context: [],
|
|
950
|
+
ext: {
|
|
951
|
+
agent_mode: String(agentMode),
|
|
952
|
+
use_deep_think: String(needDeepThink),
|
|
953
|
+
sub_conv_firstmet_type: "1",
|
|
954
|
+
general_task_param: JSON.stringify(taskParam),
|
|
955
|
+
collection_id: "",
|
|
956
|
+
is_finish: "1",
|
|
957
|
+
conversation_init_option: JSON.stringify({ need_ack_conversation: true }),
|
|
958
|
+
commerce_credit_config_enable: "0",
|
|
959
|
+
...(() => {
|
|
960
|
+
const encoded = inputSkillOf(options.skill);
|
|
961
|
+
return encoded === void 0 ? {} : { input_skill: encoded };
|
|
962
|
+
})()
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Parse ByteDance's three-line streaming frames out of a decoded text buffer.
|
|
968
|
+
*
|
|
969
|
+
* A frame is `id:` then `event:` then `data:` then a blank line. Standard SSE
|
|
970
|
+
* also permits comment lines (`:`), so those are skipped. Returns the frames
|
|
971
|
+
* plus whatever tail did not yet form a complete frame.
|
|
972
|
+
*/
|
|
973
|
+
function parseFrames(buffer) {
|
|
974
|
+
const frames = [];
|
|
975
|
+
let rest = buffer;
|
|
976
|
+
while (true) {
|
|
977
|
+
const boundary = rest.search(/\r?\n\r?\n/);
|
|
978
|
+
if (boundary < 0) break;
|
|
979
|
+
const block = rest.slice(0, boundary);
|
|
980
|
+
rest = rest.slice(boundary).replace(/^\r?\n\r?\n/, "");
|
|
981
|
+
const frame = { data: "" };
|
|
982
|
+
const dataLines = [];
|
|
983
|
+
for (const line of block.split(/\r?\n/)) {
|
|
984
|
+
if (!line || line.startsWith(":")) continue;
|
|
985
|
+
const colon = line.indexOf(":");
|
|
986
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
987
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
988
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
989
|
+
if (field === "id") frame.id = value;
|
|
990
|
+
else if (field === "event") frame.event = value;
|
|
991
|
+
else if (field === "data") dataLines.push(value);
|
|
992
|
+
}
|
|
993
|
+
if (dataLines.length > 0 || frame.event) {
|
|
994
|
+
frame.data = dataLines.join("\n");
|
|
995
|
+
frames.push(frame);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return {
|
|
999
|
+
frames,
|
|
1000
|
+
rest
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Collect answer text and thinking text, separated by block ownership.
|
|
1005
|
+
*
|
|
1006
|
+
* A deep-think reply carries a `block_type: 10040` container (the visible
|
|
1007
|
+
* 「正在思考 / 已完成思考」 shell) and then streams the reasoning as ordinary
|
|
1008
|
+
* `block_type: 10000` blocks whose `parent_id` is that container's id. The shell
|
|
1009
|
+
* and its children both point at `Deep_Think.png`, but `parent_id` is the
|
|
1010
|
+
* reliable discriminator, so it is what this uses.
|
|
1011
|
+
*
|
|
1012
|
+
* Treating every `text` as answer text — what the previous revision did — mixes
|
|
1013
|
+
* the model's private reasoning into the reply the user sees.
|
|
1014
|
+
*/
|
|
1015
|
+
const PLACEHOLDER_THINKING_TITLE_RE = /^(?:正在思考(?:中)?|思考中|已(?:完成)?(?:深度)?思考(?:\s*[((].*[))])?|深度思考(?:中)?|思考完成|正在(?:生成图片|生图)|已完成(?:图片生成|生图)|thinking|thought)(?:[.。…]+)?$/i;
|
|
1016
|
+
function nonPlaceholderTitle(raw) {
|
|
1017
|
+
if (typeof raw !== "string") return void 0;
|
|
1018
|
+
const trimmed = raw.trim();
|
|
1019
|
+
if (trimmed === "" || PLACEHOLDER_THINKING_TITLE_RE.test(trimmed)) return void 0;
|
|
1020
|
+
return trimmed;
|
|
1021
|
+
}
|
|
1022
|
+
function trailingNewlineCount(text, fallback = 0) {
|
|
1023
|
+
if (text === "") return fallback;
|
|
1024
|
+
if (/(?:\r?\n){2}$/.test(text)) return 2;
|
|
1025
|
+
if (/\r?\n$/.test(text)) return 1;
|
|
1026
|
+
return 0;
|
|
1027
|
+
}
|
|
1028
|
+
function createBlockCollectState() {
|
|
1029
|
+
return {
|
|
1030
|
+
thinkingIds: /* @__PURE__ */ new Set(),
|
|
1031
|
+
lastTitles: /* @__PURE__ */ new Map(),
|
|
1032
|
+
seenTitles: /* @__PURE__ */ new Set(),
|
|
1033
|
+
lastSummaries: /* @__PURE__ */ new Map(),
|
|
1034
|
+
hasFullThinkingText: false,
|
|
1035
|
+
sawThinkingBlock: false,
|
|
1036
|
+
hasEmittedThinking: false,
|
|
1037
|
+
trailingNewlines: 2
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
function pushThinkingPiece(state, into, piece, discrete) {
|
|
1041
|
+
if (piece === "") return;
|
|
1042
|
+
if (!discrete) {
|
|
1043
|
+
into.thinking.push(piece);
|
|
1044
|
+
state.hasEmittedThinking = true;
|
|
1045
|
+
state.trailingNewlines = trailingNewlineCount(piece, state.trailingNewlines ?? 0);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
const nl = state.trailingNewlines ?? 0;
|
|
1049
|
+
const out = `${!state.hasEmittedThinking ? "" : nl >= 2 ? "" : nl === 1 ? "\n" : "\n\n"}${piece}`;
|
|
1050
|
+
into.thinking.push(out);
|
|
1051
|
+
state.hasEmittedThinking = true;
|
|
1052
|
+
state.trailingNewlines = trailingNewlineCount(out, nl);
|
|
1053
|
+
}
|
|
1054
|
+
function collectBlocks(node, into, thinkingIdsOrState, depth = 0) {
|
|
1055
|
+
const state = thinkingIdsOrState instanceof Set ? { thinkingIds: thinkingIdsOrState } : thinkingIdsOrState;
|
|
1056
|
+
const thinkingIds = state.thinkingIds;
|
|
1057
|
+
if (Array.isArray(node)) {
|
|
1058
|
+
for (const item of node) collectBlocks(item, into, state, depth);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (node === null || typeof node !== "object") return;
|
|
1062
|
+
const record = node;
|
|
1063
|
+
const blockType = record.block_type;
|
|
1064
|
+
if (typeof blockType === "number") {
|
|
1065
|
+
const blockId = typeof record.block_id === "string" && record.block_id !== "" ? record.block_id : void 0;
|
|
1066
|
+
const parentId = typeof record.parent_id === "string" ? record.parent_id : "";
|
|
1067
|
+
const isThinking = blockType === THINKING_BLOCK_TYPE || parentId !== "" && thinkingIds.has(parentId);
|
|
1068
|
+
if (blockType === THINKING_BLOCK_TYPE) {
|
|
1069
|
+
if (blockId !== void 0) thinkingIds.add(blockId);
|
|
1070
|
+
}
|
|
1071
|
+
if (blockType === 2074) {
|
|
1072
|
+
state.activeTarget = "answer";
|
|
1073
|
+
if (into.images !== void 0) {
|
|
1074
|
+
const creations = record.content?.creation_block?.creations;
|
|
1075
|
+
if (Array.isArray(creations)) for (const raw of creations) {
|
|
1076
|
+
const image = toDoubaoImage(raw);
|
|
1077
|
+
if (image !== void 0) into.images.push(image);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
const content = record.content;
|
|
1082
|
+
const thinkingBlock = content?.thinking_block;
|
|
1083
|
+
const text = content?.text_block?.text;
|
|
1084
|
+
const summary = content?.text_block?.summary;
|
|
1085
|
+
if (isThinking) {
|
|
1086
|
+
if (thinkingBlock !== void 0 && typeof thinkingBlock === "object" && thinkingBlock !== null && thinkingBlock.empty_disable_click !== true) {
|
|
1087
|
+
const isSummaryStyle = thinkingBlock.cot_ui_style === "summary";
|
|
1088
|
+
if (!state.hasFullThinkingText || isSummaryStyle) {
|
|
1089
|
+
const title = nonPlaceholderTitle(thinkingBlock.finish_title) ?? nonPlaceholderTitle(thinkingBlock.unfold_streaming_title) ?? nonPlaceholderTitle(thinkingBlock.streaming_title);
|
|
1090
|
+
if (title !== void 0) {
|
|
1091
|
+
state.sawThinkingBlock = true;
|
|
1092
|
+
state.seenTitles ??= /* @__PURE__ */ new Set();
|
|
1093
|
+
state.lastTitles ??= /* @__PURE__ */ new Map();
|
|
1094
|
+
const titleKey = blockId ?? "__thinking_title__";
|
|
1095
|
+
if (!state.seenTitles.has(title) && state.lastTitles.get(titleKey) !== title) {
|
|
1096
|
+
state.seenTitles.add(title);
|
|
1097
|
+
state.lastTitles.set(titleKey, title);
|
|
1098
|
+
pushThinkingPiece(state, into, `${title}\n\n`, true);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
if (typeof text === "string" && text !== "") {
|
|
1104
|
+
state.hasFullThinkingText = true;
|
|
1105
|
+
state.sawThinkingBlock = true;
|
|
1106
|
+
pushThinkingPiece(state, into, text, false);
|
|
1107
|
+
} else if (typeof summary === "string" && summary.trim() !== "") {
|
|
1108
|
+
const trimmedSummary = summary.trim();
|
|
1109
|
+
if (!PLACEHOLDER_THINKING_TITLE_RE.test(trimmedSummary)) {
|
|
1110
|
+
state.sawThinkingBlock = true;
|
|
1111
|
+
state.seenTitles ??= /* @__PURE__ */ new Set();
|
|
1112
|
+
state.lastSummaries ??= /* @__PURE__ */ new Map();
|
|
1113
|
+
const summaryKey = blockId ?? (parentId !== "" ? `${parentId}:summary` : "__thinking_summary__");
|
|
1114
|
+
const prev = state.lastSummaries.get(summaryKey) ?? "";
|
|
1115
|
+
if (prev === "" && state.seenTitles.has(trimmedSummary)) state.lastSummaries.set(summaryKey, summary);
|
|
1116
|
+
else if (summary !== prev) {
|
|
1117
|
+
state.lastSummaries.set(summaryKey, summary);
|
|
1118
|
+
if (prev !== "" && summary.startsWith(prev)) pushThinkingPiece(state, into, summary.slice(prev.length), false);
|
|
1119
|
+
else {
|
|
1120
|
+
state.seenTitles.add(trimmedSummary);
|
|
1121
|
+
pushThinkingPiece(state, into, summary, true);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
if (typeof text === "string" && text !== "" && record.is_finish !== true) state.activeTarget = "thinking";
|
|
1127
|
+
else if (blockType !== THINKING_BLOCK_TYPE && record.is_finish !== true) state.activeTarget = "thinking";
|
|
1128
|
+
else if (blockType === THINKING_BLOCK_TYPE && state.activeTarget === void 0 && record.is_finish !== true) state.activeTarget = "thinking";
|
|
1129
|
+
} else {
|
|
1130
|
+
if (typeof text === "string" && text !== "") into.answer.push(text);
|
|
1131
|
+
if (content?.text_block !== void 0) state.activeTarget = "answer";
|
|
1132
|
+
}
|
|
1133
|
+
} else if (typeof record.text === "string" && record.text !== "" && !("content_block" in record) && !("message" in record) && (typeof record.id === "string" || depth === 0 && !("block_type" in record) && !("icon_url" in record))) {
|
|
1134
|
+
if (typeof record.id === "string" ? thinkingIds.has(record.id) : state.activeTarget === "thinking") {
|
|
1135
|
+
state.sawThinkingBlock = true;
|
|
1136
|
+
pushThinkingPiece(state, into, record.text, false);
|
|
1137
|
+
} else into.answer.push(record.text);
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
for (const value of Object.values(record)) collectBlocks(value, into, state, depth + 1);
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Turn one `creations[]` entry into an image, or undefined when it carries no
|
|
1144
|
+
* usable URL yet (the placeholder stage).
|
|
1145
|
+
*
|
|
1146
|
+
* URL preference is original → preview → thumb: `image_ori` is the full-
|
|
1147
|
+
* resolution artefact, the others are watermarked/derivative variants the app
|
|
1148
|
+
* uses for lists and thumbnails.
|
|
1149
|
+
*/
|
|
1150
|
+
function toDoubaoImage(raw) {
|
|
1151
|
+
if (raw === null || typeof raw !== "object") return void 0;
|
|
1152
|
+
const creation = raw;
|
|
1153
|
+
const image = creation.image;
|
|
1154
|
+
if (image === void 0) return void 0;
|
|
1155
|
+
const pick = (key) => {
|
|
1156
|
+
const value = image[key];
|
|
1157
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
1158
|
+
const url = value.url;
|
|
1159
|
+
if (typeof url !== "string" || url === "") return void 0;
|
|
1160
|
+
return value;
|
|
1161
|
+
};
|
|
1162
|
+
const best = pick("image_ori_raw") ?? pick("image_ori") ?? pick("image_preview") ?? pick("image_thumb");
|
|
1163
|
+
if (best === void 0) return void 0;
|
|
1164
|
+
const taskId = typeof creation.id === "string" ? creation.id : typeof creation.id === "number" ? String(creation.id) : void 0;
|
|
1165
|
+
const out = { url: best.url };
|
|
1166
|
+
if (taskId !== void 0) out.taskId = taskId;
|
|
1167
|
+
if (typeof image.key === "string") out.key = image.key;
|
|
1168
|
+
if (typeof best.width === "number") out.width = best.width;
|
|
1169
|
+
if (typeof best.height === "number") out.height = best.height;
|
|
1170
|
+
return out;
|
|
1171
|
+
}
|
|
1172
|
+
/** Read the model identifier the server actually used for a reply. */
|
|
1173
|
+
function extractModel(payload) {
|
|
1174
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1175
|
+
const walk = (node) => {
|
|
1176
|
+
if (node === null || typeof node !== "object") return void 0;
|
|
1177
|
+
if (Array.isArray(node)) {
|
|
1178
|
+
for (const item of node) {
|
|
1179
|
+
const found = walk(item);
|
|
1180
|
+
if (found) return found;
|
|
1181
|
+
}
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
const record = node;
|
|
1185
|
+
for (const key of [
|
|
1186
|
+
"model",
|
|
1187
|
+
"model_name",
|
|
1188
|
+
"model_id",
|
|
1189
|
+
"llm_model_type",
|
|
1190
|
+
"model_type"
|
|
1191
|
+
]) {
|
|
1192
|
+
const value = record[key];
|
|
1193
|
+
if (typeof value === "string" && value && !seen.has(value)) {
|
|
1194
|
+
seen.add(value);
|
|
1195
|
+
return value;
|
|
1196
|
+
}
|
|
1197
|
+
if (typeof value === "number" && value) {
|
|
1198
|
+
const text = String(value);
|
|
1199
|
+
if (!seen.has(text)) {
|
|
1200
|
+
seen.add(text);
|
|
1201
|
+
return text;
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
for (const value of Object.values(record)) {
|
|
1206
|
+
const found = walk(value);
|
|
1207
|
+
if (found) return found;
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
return walk(payload);
|
|
1211
|
+
}
|
|
1212
|
+
/** True when the reply came from a reasoning-capable model. */
|
|
1213
|
+
function extractThinking(payload) {
|
|
1214
|
+
const record = payload;
|
|
1215
|
+
const ext = record?.message?.ext ?? record?.ext;
|
|
1216
|
+
if (ext && typeof ext === "object") {
|
|
1217
|
+
const useDeepThink = ext.use_deep_think;
|
|
1218
|
+
if (useDeepThink === "1" || useDeepThink === 1) return true;
|
|
1219
|
+
if (typeof useDeepThink === "string" && useDeepThink !== "" && useDeepThink !== "0") return true;
|
|
1220
|
+
}
|
|
1221
|
+
return false;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Local workspace HTTP responder for 「工作任务」 (`Agent-GeneralTask`) turns.
|
|
1225
|
+
*
|
|
1226
|
+
* When a task-mode turn starts with `option.unique_key = <U>`, the server's
|
|
1227
|
+
* `Agent-GeneralTask` dispatches sequential local workspace commands with
|
|
1228
|
+
* deterministic IDs: `${uniqueKey}:${device_id}:${aid}:message:${seq}` for
|
|
1229
|
+
* `seq = 0, 1, 2, ...`.
|
|
1230
|
+
*
|
|
1231
|
+
* CRITICAL: `POST /alice/office/tool_local/msg/ack` MUST be called with a
|
|
1232
|
+
* SINGLE `msg_id` (`{ msg_ids: [msgId] }`). If `msg_ids` contains any `seq`
|
|
1233
|
+
* that has not been created on the server yet, the entire `msg/ack` batch fails
|
|
1234
|
+
* with `710010702`. Polling one `seq` at a time and replying to `cmd_call`
|
|
1235
|
+
* (`command: 6003`, e.g. `local.workspace.apply`) via `upload_command_result`
|
|
1236
|
+
* + `msg/complete` until `agent_finished` (`command: 6004`) satisfies the server
|
|
1237
|
+
* runtime without requiring the Doubao desktop CUA process.
|
|
1238
|
+
*/
|
|
1239
|
+
async function runToolLocalResponder(uniqueKey, credentials, isStreamDone, signal) {
|
|
1240
|
+
const msToken = credentials.pairs.get("msToken");
|
|
1241
|
+
const postToolJson = async (endpoint, payload) => {
|
|
1242
|
+
const url = buildQueryUrl(endpoint, msToken);
|
|
1243
|
+
const headers = buildHeaders(credentials, {
|
|
1244
|
+
"content-type": "application/json",
|
|
1245
|
+
accept: "application/json, text/plain, */*"
|
|
1246
|
+
});
|
|
1247
|
+
delete headers["last-event-id"];
|
|
1248
|
+
const res = await fetch(url, {
|
|
1249
|
+
method: "POST",
|
|
1250
|
+
headers,
|
|
1251
|
+
body: JSON.stringify(payload),
|
|
1252
|
+
...signal ? { signal } : {}
|
|
1253
|
+
});
|
|
1254
|
+
absorbSetCookies(res.headers);
|
|
1255
|
+
const text = await res.text();
|
|
1256
|
+
return JSON.parse(text);
|
|
1257
|
+
};
|
|
1258
|
+
let seq = 0;
|
|
1259
|
+
let postStreamPolls = 0;
|
|
1260
|
+
while (!signal?.aborted) {
|
|
1261
|
+
if (isStreamDone()) {
|
|
1262
|
+
if (seq === 0 || postStreamPolls >= 8) break;
|
|
1263
|
+
postStreamPolls += 1;
|
|
1264
|
+
}
|
|
1265
|
+
const msgId = `${uniqueKey}:${CLIENT_PARAMS.device_id}:${CLIENT_PARAMS.aid}:message:${seq}`;
|
|
1266
|
+
let ack;
|
|
1267
|
+
try {
|
|
1268
|
+
ack = await postToolJson(TOOL_LOCAL_ACK_ENDPOINT, { msg_ids: [msgId] });
|
|
1269
|
+
} catch {
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
const msg = ack?.code === 0 ? ack?.data?.msgs?.[0] : void 0;
|
|
1273
|
+
if (msg !== void 0) {
|
|
1274
|
+
const cmdCall = msg?.body?.cmd_call;
|
|
1275
|
+
const agentFinished = msg?.body?.agent_finished;
|
|
1276
|
+
if (cmdCall !== void 0) {
|
|
1277
|
+
let inputObj = {};
|
|
1278
|
+
try {
|
|
1279
|
+
inputObj = JSON.parse(cmdCall.input ?? "{}");
|
|
1280
|
+
} catch {
|
|
1281
|
+
inputObj = {};
|
|
1282
|
+
}
|
|
1283
|
+
const results = (Array.isArray(inputObj.operations) ? inputObj.operations : []).map((op) => ({
|
|
1284
|
+
...op.sequence !== void 0 ? { sequence: op.sequence } : {},
|
|
1285
|
+
id: op.id,
|
|
1286
|
+
type: op.type,
|
|
1287
|
+
path: op.path,
|
|
1288
|
+
status: "success"
|
|
1289
|
+
}));
|
|
1290
|
+
const outputObj = {
|
|
1291
|
+
request_id: inputObj.request_id ?? "",
|
|
1292
|
+
status: "success",
|
|
1293
|
+
results
|
|
1294
|
+
};
|
|
1295
|
+
try {
|
|
1296
|
+
await postToolJson(TOOL_LOCAL_UPLOAD_ENDPOINT, {
|
|
1297
|
+
cmd_id: cmdCall.cmd_id,
|
|
1298
|
+
session_id: msg.session_id,
|
|
1299
|
+
msg_id: msgId,
|
|
1300
|
+
output: JSON.stringify(outputObj)
|
|
1301
|
+
});
|
|
1302
|
+
await postToolJson(TOOL_LOCAL_COMPLETE_ENDPOINT, { msg_id: msgId });
|
|
1303
|
+
} catch {
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
seq += 1;
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
if (agentFinished !== void 0) return;
|
|
1310
|
+
seq += 1;
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
await new Promise((resolve) => setTimeout(resolve, 180));
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* One attempt, no fallback. Split out so {@link streamChat} can retry a
|
|
1318
|
+
* task-mode call as plain chat when the task runtime is not attached.
|
|
1319
|
+
*/
|
|
1320
|
+
async function streamOnce(prompt, options = {}) {
|
|
1321
|
+
const credentials = options.credentials ?? loadDoubaoCredentials();
|
|
1322
|
+
/**
|
|
1323
|
+
* No cookie means "sign in again", not "the network is down".
|
|
1324
|
+
*
|
|
1325
|
+
* `loadDoubaoCredentials` throws when there is no session, and the message it carries is
|
|
1326
|
+
* the sentence the card shows. The `session_dead` kind is what stops the caller from
|
|
1327
|
+
* treating it as a transport failure and retrying.
|
|
1328
|
+
*/
|
|
1329
|
+
if (credentials.pairs.size === 0) throw new DoubaoUpstreamError("还没有浏览器登录态。请在豆包卡片里点「重新登录」扫码一次。", void 0, false, { kind: "session_dead" });
|
|
1330
|
+
const missing = REQUIRED_COOKIE_NAMES.filter((name) => !credentials.pairs.get(name));
|
|
1331
|
+
if (missing.length > 0) throw new DoubaoUpstreamError(`Doubao session cookies missing: ${missing.join(", ")}`, void 0, false, { kind: "session_dead" });
|
|
1332
|
+
const msToken = credentials.pairs.get("msToken");
|
|
1333
|
+
const url = buildQueryUrl(CHAT_ENDPOINT, msToken);
|
|
1334
|
+
const headers = buildHeaders(credentials, { "content-type": "application/json" });
|
|
1335
|
+
const bodyObj = buildChatBody(prompt, options);
|
|
1336
|
+
const uniqueKey = bodyObj.option.unique_key;
|
|
1337
|
+
const body = JSON.stringify(bodyObj);
|
|
1338
|
+
const isTask = taskModeEnabled(options);
|
|
1339
|
+
let response;
|
|
1340
|
+
try {
|
|
1341
|
+
response = await fetch(url, {
|
|
1342
|
+
method: "POST",
|
|
1343
|
+
headers,
|
|
1344
|
+
body,
|
|
1345
|
+
...options.signal ? { signal: options.signal } : {}
|
|
1346
|
+
});
|
|
1347
|
+
} catch (error) {
|
|
1348
|
+
if (options.signal?.aborted) throw error;
|
|
1349
|
+
throw new DoubaoUpstreamError(`Doubao request did not reach the server: ${error.message}`, void 0, false, { transport: true });
|
|
1350
|
+
}
|
|
1351
|
+
if (!response.ok) {
|
|
1352
|
+
const detail = await response.text().catch(() => "");
|
|
1353
|
+
throw new DoubaoUpstreamError(`Doubao chat request failed with HTTP ${response.status}. ${detail.slice(0, 200)}`, void 0, false, { httpStatus: response.status });
|
|
1354
|
+
}
|
|
1355
|
+
absorbSetCookies(response.headers);
|
|
1356
|
+
let streamDone = false;
|
|
1357
|
+
const responderPromise = isTask ? runToolLocalResponder(uniqueKey, credentials, () => streamDone, options.signal).catch(() => {}) : Promise.resolve();
|
|
1358
|
+
try {
|
|
1359
|
+
return await consumeStream(response, options.callbacks, { harvestNotifyText: isTask });
|
|
1360
|
+
} finally {
|
|
1361
|
+
streamDone = true;
|
|
1362
|
+
await responderPromise;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Stream one completion and return the assembled reply.
|
|
1367
|
+
*
|
|
1368
|
+
* Rejects with `DoubaoUpstreamError` when the server answers with a business
|
|
1369
|
+
* error frame — notably `710022004 rate limited`, which is risk control asking
|
|
1370
|
+
* for a slider CAPTCHA rather than an authentication failure.
|
|
1371
|
+
*
|
|
1372
|
+
* TASK MODE FALLBACK. Since 0.4.1 a task-mode turn is served by the
|
|
1373
|
+
* `tool_local` responder above, so it normally completes. This is now a
|
|
1374
|
+
* last-resort net: if the responder cannot satisfy the runtime (upstream change,
|
|
1375
|
+
* network failure), the server answers with `710010702 system error` instead of
|
|
1376
|
+
* a reply (verified: the stream still names `Agent-GeneralTask`, so the mode
|
|
1377
|
+
* itself was accepted). Rather than hand that placeholder to the user, the call
|
|
1378
|
+
* is retried ONCE as plain chat — and only when the failed attempt emitted no
|
|
1379
|
+
* text, so a fallback can never duplicate a partially streamed answer.
|
|
1380
|
+
*/
|
|
1381
|
+
async function streamChat(prompt, options = {}) {
|
|
1382
|
+
let emittedText = false;
|
|
1383
|
+
const wrapped = {
|
|
1384
|
+
onText: (delta) => {
|
|
1385
|
+
if (delta) emittedText = true;
|
|
1386
|
+
options.callbacks?.onText?.(delta);
|
|
1387
|
+
},
|
|
1388
|
+
onThinking: (delta) => options.callbacks?.onThinking?.(delta),
|
|
1389
|
+
onEvent: (event) => options.callbacks?.onEvent?.(event)
|
|
1390
|
+
};
|
|
1391
|
+
const wanted = taskModeEnabled(options);
|
|
1392
|
+
const call = (taskMode) => streamOnce(prompt, {
|
|
1393
|
+
...options,
|
|
1394
|
+
callbacks: wrapped,
|
|
1395
|
+
taskMode
|
|
1396
|
+
});
|
|
1397
|
+
try {
|
|
1398
|
+
return await call(wanted);
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
const taskRuntimeMissing = error instanceof DoubaoUpstreamError && (error.code === CODE_TASK_RUNTIME_UNAVAILABLE || /agent_err_real_answer/.test(error.message));
|
|
1401
|
+
if (!wanted || !taskRuntimeMissing || emittedText) throw error;
|
|
1402
|
+
return call(false);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
const renewals = /* @__PURE__ */ new Map();
|
|
1406
|
+
/** Record rotated cookies (`x-ms-token`, `bd_sso_hi3jfd`) for the next request. */
|
|
1407
|
+
function absorbSetCookies(headers) {
|
|
1408
|
+
const msToken = headers.get("x-ms-token");
|
|
1409
|
+
if (msToken) renewals.set("msToken", msToken);
|
|
1410
|
+
const setCookie = headers.get("set-cookie");
|
|
1411
|
+
if (!setCookie) return;
|
|
1412
|
+
for (const part of setCookie.split(/,\s*(?=[A-Za-z0-9_-]+=)/)) {
|
|
1413
|
+
const [pair] = part.split(";");
|
|
1414
|
+
if (!pair) continue;
|
|
1415
|
+
const eq = pair.indexOf("=");
|
|
1416
|
+
if (eq <= 0) continue;
|
|
1417
|
+
const name = pair.slice(0, eq).trim();
|
|
1418
|
+
const value = pair.slice(eq + 1).trim();
|
|
1419
|
+
if (name && value) renewals.set(name, value);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
/** Cookie header with any rotated values overlaid. Values never leave memory. */
|
|
1423
|
+
function applyRenewals(header) {
|
|
1424
|
+
if (renewals.size === 0) return header;
|
|
1425
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
1426
|
+
for (const part of header.split(/;\s*/)) {
|
|
1427
|
+
const eq = part.indexOf("=");
|
|
1428
|
+
if (eq > 0) pairs.set(part.slice(0, eq).trim(), part.slice(eq + 1));
|
|
1429
|
+
}
|
|
1430
|
+
for (const [name, value] of renewals) pairs.set(name, value);
|
|
1431
|
+
return [...pairs.entries()].map(([name, value]) => `${name}=${value}`).join("; ");
|
|
1432
|
+
}
|
|
1433
|
+
async function consumeStream(response, callbacks, options = {}) {
|
|
1434
|
+
const reader = response.body?.getReader();
|
|
1435
|
+
if (!reader) throw new DoubaoUpstreamError("Doubao returned an empty response body.");
|
|
1436
|
+
const decoder = new TextDecoder();
|
|
1437
|
+
let buffer = "";
|
|
1438
|
+
const texts = [];
|
|
1439
|
+
/** Text carried by STREAM_MSG_NOTIFY instead of by chunk deltas. */
|
|
1440
|
+
const notifyTexts = [];
|
|
1441
|
+
/** Generated images, in arrival order (may repeat a task while it streams). */
|
|
1442
|
+
const images = [];
|
|
1443
|
+
/** Private reasoning (deep-think turns), kept out of the answer. */
|
|
1444
|
+
const reasoningParts = [];
|
|
1445
|
+
/** Shared per-stream state across `10040` / `10000` / `CHUNK_DELTA` frames. */
|
|
1446
|
+
const blockState = createBlockCollectState();
|
|
1447
|
+
let conversationId;
|
|
1448
|
+
let messageId;
|
|
1449
|
+
let model;
|
|
1450
|
+
let thinking = false;
|
|
1451
|
+
let lastEventId;
|
|
1452
|
+
let ended = false;
|
|
1453
|
+
/**
|
|
1454
|
+
* Every event name seen, in arrival order (deduped).
|
|
1455
|
+
*
|
|
1456
|
+
* Task mode answers with a richer event vocabulary than chat, so an empty
|
|
1457
|
+
* completion is usually "the text lives in an event we do not harvest yet"
|
|
1458
|
+
* rather than "the server said nothing". Naming the events turns an opaque
|
|
1459
|
+
* failure into a next step.
|
|
1460
|
+
*/
|
|
1461
|
+
function toFiniteNumber(value) {
|
|
1462
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
1463
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
1464
|
+
const parsed = Number(value);
|
|
1465
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
function parseJsonObject(value) {
|
|
1469
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value)) return value;
|
|
1470
|
+
if (typeof value !== "string" || value.trim() === "") return void 0;
|
|
1471
|
+
try {
|
|
1472
|
+
const parsed = JSON.parse(value);
|
|
1473
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
1474
|
+
} catch {}
|
|
1475
|
+
}
|
|
1476
|
+
function parseContextWindowUsage(raw) {
|
|
1477
|
+
const obj = parseJsonObject(raw);
|
|
1478
|
+
if (obj === void 0) return void 0;
|
|
1479
|
+
const systemPrompt = toFiniteNumber(obj.system_prompt);
|
|
1480
|
+
const messages = toFiniteNumber(obj.messages);
|
|
1481
|
+
const skills = toFiniteNumber(obj.skills);
|
|
1482
|
+
const tools = toFiniteNumber(obj.tools);
|
|
1483
|
+
const totalWindowSize = toFiniteNumber(obj.total_window_size);
|
|
1484
|
+
if (systemPrompt === void 0 && messages === void 0 && skills === void 0 && tools === void 0 && totalWindowSize === void 0) return;
|
|
1485
|
+
const s = Math.max(0, systemPrompt ?? 0);
|
|
1486
|
+
const m = Math.max(0, messages ?? 0);
|
|
1487
|
+
const k = Math.max(0, skills ?? 0);
|
|
1488
|
+
const t = Math.max(0, tools ?? 0);
|
|
1489
|
+
return {
|
|
1490
|
+
systemPrompt: s,
|
|
1491
|
+
messages: m,
|
|
1492
|
+
skills: k,
|
|
1493
|
+
tools: t,
|
|
1494
|
+
totalWindowSize: Math.max(0, totalWindowSize ?? 0),
|
|
1495
|
+
totalUsed: s + m + k + t
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
function collectTelemetryFromExt(ext, target) {
|
|
1499
|
+
const record = parseJsonObject(ext);
|
|
1500
|
+
if (record === void 0) return;
|
|
1501
|
+
const contextWindow = parseContextWindowUsage(record.context_window_usage);
|
|
1502
|
+
if (contextWindow !== void 0) target.contextWindowUsage = contextWindow;
|
|
1503
|
+
const teaCost = parseJsonObject(record.tea_tags_time_cost);
|
|
1504
|
+
if (teaCost !== void 0) {
|
|
1505
|
+
const ack = toFiniteNumber(teaCost.ack_cost_time);
|
|
1506
|
+
if (ack !== void 0 && ack >= 0) target.ackCostMs = ack;
|
|
1507
|
+
const firstPacket = toFiniteNumber(teaCost.first_packet_cost_time);
|
|
1508
|
+
if (firstPacket !== void 0 && firstPacket >= 0) target.firstPacketCostMs = firstPacket;
|
|
1509
|
+
}
|
|
1510
|
+
const finishTime = toFiniteNumber(record.finish_time_ms);
|
|
1511
|
+
if (finishTime !== void 0 && finishTime >= 0) target.finishTimeMs = finishTime;
|
|
1512
|
+
if (typeof record.finish_reason_chat === "string" && record.finish_reason_chat !== "") target.finishReasonChat = record.finish_reason_chat;
|
|
1513
|
+
}
|
|
1514
|
+
function collectTelemetry(payload, target) {
|
|
1515
|
+
if (payload === null || typeof payload !== "object") return;
|
|
1516
|
+
const record = payload;
|
|
1517
|
+
collectTelemetryFromExt(record.ext, target);
|
|
1518
|
+
collectTelemetryFromExt(record.content?.ext, target);
|
|
1519
|
+
collectTelemetryFromExt(record.message?.ext, target);
|
|
1520
|
+
if (Array.isArray(record.patch_op)) for (const op of record.patch_op) collectTelemetryFromExt(op?.patch_value?.ext, target);
|
|
1521
|
+
}
|
|
1522
|
+
const events = /* @__PURE__ */ new Set();
|
|
1523
|
+
/** The agent that served this turn, when the server names one. */
|
|
1524
|
+
let intentionAgent;
|
|
1525
|
+
/** Server-side timing & context window telemetry harvested across SSE frames. */
|
|
1526
|
+
const telemetry = {};
|
|
1527
|
+
/**
|
|
1528
|
+
* `expose_reason` of a task turn whose runtime was unreachable.
|
|
1529
|
+
*
|
|
1530
|
+
* Recorded instead of surfacing its placeholder text (「出了点问题,请稍后重试。」),
|
|
1531
|
+
* which reads like a transient glitch and hides the actual cause.
|
|
1532
|
+
*/
|
|
1533
|
+
let taskAgentError;
|
|
1534
|
+
const handle = (frame) => {
|
|
1535
|
+
const name = frame.event ?? "";
|
|
1536
|
+
if (name) events.add(name);
|
|
1537
|
+
if (process.env.DSH_DOUBAO_DEBUG_FRAMES === "1" && frame.data) process.stderr.write(`[frame ${name || "(none)"}] ${frame.data.slice(0, 1500)}\n`);
|
|
1538
|
+
if (name && callbacks?.onEvent) callbacks.onEvent(name);
|
|
1539
|
+
if (frame.id) lastEventId = frame.id;
|
|
1540
|
+
if (!frame.data) return;
|
|
1541
|
+
let payload;
|
|
1542
|
+
try {
|
|
1543
|
+
payload = JSON.parse(frame.data);
|
|
1544
|
+
} catch {
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
collectTelemetry(payload, telemetry);
|
|
1548
|
+
if (name === "STREAM_ERROR") {
|
|
1549
|
+
const record = payload;
|
|
1550
|
+
const code = record.error_code;
|
|
1551
|
+
const message = record.error_msg ?? "unknown stream error";
|
|
1552
|
+
const rateLimited = code === 710022004 || /rate limit/i.test(message);
|
|
1553
|
+
throw new DoubaoUpstreamError(rateLimited ? "Doubao risk control challenged this request (710022004). Slow down and retry later." : `Doubao stream error ${code ?? "?"}: ${message}`, code, rateLimited);
|
|
1554
|
+
}
|
|
1555
|
+
if (name === "SSE_ACK") {
|
|
1556
|
+
const ack = payload;
|
|
1557
|
+
conversationId = ack.ack_client_meta?.conversation_id ?? conversationId;
|
|
1558
|
+
messageId = ack.query_list?.[0]?.question_id ?? messageId;
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
if (name === "FULL_MSG_NOTIFY" || name === "STREAM_MSG_NOTIFY") {
|
|
1562
|
+
const record = payload;
|
|
1563
|
+
messageId = record.message?.message_id ?? messageId;
|
|
1564
|
+
model = model ?? extractModel(payload);
|
|
1565
|
+
thinking = thinking || extractThinking(payload);
|
|
1566
|
+
const ext = record.content?.ext ?? record.message?.ext ?? record.ext;
|
|
1567
|
+
if (ext !== void 0 && ext !== null && typeof ext === "object") {
|
|
1568
|
+
const agent = ext.intention_agent_name;
|
|
1569
|
+
if (typeof agent === "string" && agent !== "") intentionAgent = agent;
|
|
1570
|
+
const reason = ext.expose_reason;
|
|
1571
|
+
if (typeof reason === "string" && /agent_err_real_answer/.test(reason)) taskAgentError = reason;
|
|
1572
|
+
}
|
|
1573
|
+
if (name === "STREAM_MSG_NOTIFY") {
|
|
1574
|
+
thinking = thinking || extractThinking(payload);
|
|
1575
|
+
const acc = {
|
|
1576
|
+
answer: [],
|
|
1577
|
+
thinking: [],
|
|
1578
|
+
images
|
|
1579
|
+
};
|
|
1580
|
+
collectBlocks(record.content?.content_block, acc, blockState);
|
|
1581
|
+
const joinedAccThinking = acc.thinking.join("");
|
|
1582
|
+
const priorThinking = reasoningParts.join("");
|
|
1583
|
+
if (!(joinedAccThinking !== "" && priorThinking !== "" && joinedAccThinking === priorThinking)) for (const piece of acc.thinking) {
|
|
1584
|
+
if (!piece) continue;
|
|
1585
|
+
reasoningParts.push(piece);
|
|
1586
|
+
if (callbacks?.onThinking) callbacks.onThinking(piece);
|
|
1587
|
+
}
|
|
1588
|
+
for (const piece of acc.answer) {
|
|
1589
|
+
if (!piece) continue;
|
|
1590
|
+
notifyTexts.push(piece);
|
|
1591
|
+
if (callbacks?.onText) callbacks.onText(piece);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
if (name === "STREAM_CHUNK" || name === "CHUNK_DELTA") {
|
|
1597
|
+
model = model ?? extractModel(payload);
|
|
1598
|
+
thinking = thinking || extractThinking(payload);
|
|
1599
|
+
const acc = {
|
|
1600
|
+
answer: [],
|
|
1601
|
+
thinking: [],
|
|
1602
|
+
images
|
|
1603
|
+
};
|
|
1604
|
+
collectBlocks(payload, acc, blockState);
|
|
1605
|
+
for (const piece of acc.thinking) {
|
|
1606
|
+
if (!piece) continue;
|
|
1607
|
+
reasoningParts.push(piece);
|
|
1608
|
+
if (callbacks?.onThinking) callbacks.onThinking(piece);
|
|
1609
|
+
}
|
|
1610
|
+
for (const text of acc.answer) {
|
|
1611
|
+
if (!text) continue;
|
|
1612
|
+
if (callbacks?.onText) callbacks.onText(text);
|
|
1613
|
+
texts.push(text);
|
|
1614
|
+
}
|
|
1615
|
+
return;
|
|
1616
|
+
}
|
|
1617
|
+
if (name === "SSE_REPLY_END") ended = true;
|
|
1618
|
+
};
|
|
1619
|
+
try {
|
|
1620
|
+
while (true) {
|
|
1621
|
+
const { done, value } = await reader.read();
|
|
1622
|
+
if (done) break;
|
|
1623
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1624
|
+
const { frames, rest } = parseFrames(buffer);
|
|
1625
|
+
buffer = rest;
|
|
1626
|
+
for (const frame of frames) handle(frame);
|
|
1627
|
+
if (ended) break;
|
|
1628
|
+
}
|
|
1629
|
+
const tail = decoder.decode();
|
|
1630
|
+
if (tail) {
|
|
1631
|
+
const { frames, rest } = parseFrames(buffer + tail);
|
|
1632
|
+
buffer = rest;
|
|
1633
|
+
for (const frame of frames) handle(frame);
|
|
1634
|
+
}
|
|
1635
|
+
} finally {
|
|
1636
|
+
await reader.cancel().catch(() => {});
|
|
1637
|
+
reader.releaseLock();
|
|
1638
|
+
}
|
|
1639
|
+
const chunkText = texts.join("");
|
|
1640
|
+
const text = stripPromptEcho(assembleReplyText(notifyTexts.join(""), chunkText));
|
|
1641
|
+
if (taskAgentError !== void 0) throw new DoubaoUpstreamError(`Doubao accepted the task but its executing runtime was unreachable (${taskAgentError}). The 「工作任务」 runtime is attached by the desktop client; without it the agent has nowhere to run.`, CODE_TASK_RUNTIME_UNAVAILABLE);
|
|
1642
|
+
if (!ended) {
|
|
1643
|
+
const received = texts.join("").length + notifyTexts.join("").length;
|
|
1644
|
+
throw new DoubaoUpstreamError(`Doubao closed the stream before the reply finished${received > 0 ? ` after ${received} characters` : ""}; the answer is incomplete. Retry the turn.`, void 0, false, { truncated: true });
|
|
1645
|
+
}
|
|
1646
|
+
const uniqueImages = [...new Map(images.map((image) => [image.url, image])).values()];
|
|
1647
|
+
if (!text && uniqueImages.length === 0) {
|
|
1648
|
+
const seen = [...events];
|
|
1649
|
+
throw new DoubaoUpstreamError(`Doubao returned an empty completion${lastEventId ? ` (last event id ${lastEventId})` : ""}${seen.length > 0 ? `; events seen: ${seen.join(", ")}` : "; no events at all"}.`);
|
|
1650
|
+
}
|
|
1651
|
+
return {
|
|
1652
|
+
text,
|
|
1653
|
+
...model !== void 0 ? { model } : {},
|
|
1654
|
+
...conversationId !== void 0 ? { conversationId } : {},
|
|
1655
|
+
...messageId !== void 0 ? { messageId } : {},
|
|
1656
|
+
...reasoningParts.length > 0 ? { reasoningText: reasoningParts.join("") } : {},
|
|
1657
|
+
...intentionAgent !== void 0 ? { intentionAgent } : {},
|
|
1658
|
+
...Object.keys(telemetry).length > 0 ? { telemetry } : {},
|
|
1659
|
+
images: uniqueImages,
|
|
1660
|
+
thinking: thinking || blockState.sawThinkingBlock === true || reasoningParts.length > 0
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Join the two halves of a reply.
|
|
1665
|
+
*
|
|
1666
|
+
* The opening of every answer arrives in STREAM_MSG_NOTIFY and the remainder as
|
|
1667
|
+
* patch deltas in STREAM_CHUNK. Reading only the chunks swallowed the first
|
|
1668
|
+
* character of EVERY reply — 「1+1等于2。」 came back as 「+1等于2。」, 「我是豆包」
|
|
1669
|
+
* as 「是豆包」 — and nothing failed loudly, which is exactly why it survived.
|
|
1670
|
+
*
|
|
1671
|
+
* A cumulative chunk stream (one that re-sends what was already delivered)
|
|
1672
|
+
* already starts with the notification text; that case is detected rather than
|
|
1673
|
+
* concatenated twice. Exported so the rule can be tested without a live stream.
|
|
1674
|
+
*/
|
|
1675
|
+
function assembleReplyText(notifyText, chunkText) {
|
|
1676
|
+
if (notifyText === "") return chunkText;
|
|
1677
|
+
if (chunkText === "") return notifyText;
|
|
1678
|
+
return chunkText.startsWith(notifyText) ? chunkText : notifyText + chunkText;
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Remove the echoed user prompt from the front of the assembled text.
|
|
1682
|
+
*
|
|
1683
|
+
* Doubao's first chunk replays the inbound message; keeping it would make every
|
|
1684
|
+
* reply appear to start with the user's own words.
|
|
1685
|
+
*/
|
|
1686
|
+
function stripPromptEcho(raw) {
|
|
1687
|
+
return raw.trimStart();
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Collect a complete reply. Convenience wrapper over `streamChat` for callers
|
|
1691
|
+
* that do not need incremental deltas.
|
|
1692
|
+
*/
|
|
1693
|
+
async function chat(prompt, options = {}) {
|
|
1694
|
+
return streamChat(prompt, options);
|
|
1695
|
+
}
|
|
1696
|
+
/**
|
|
1697
|
+
* `block_type` of the deep-think container.
|
|
1698
|
+
*
|
|
1699
|
+
* A 深度思考 turn opens one `10040` block (the 「正在思考 / 已完成思考」 shell) and
|
|
1700
|
+
* then streams the reasoning as `10000` blocks whose `parent_id` is its id.
|
|
1701
|
+
* Captured 2026-10-23.
|
|
1702
|
+
*/
|
|
1703
|
+
const THINKING_BLOCK_TYPE = 10040;
|
|
1704
|
+
/**
|
|
1705
|
+
* The server's business code when a 「工作任务」 was accepted but its executing
|
|
1706
|
+
* runtime could not be reached (`expose_reason: agent_err_real_answer`).
|
|
1707
|
+
*
|
|
1708
|
+
* This is the signature of "the mode is right, the local runtime is not
|
|
1709
|
+
* attached" — the desktop client's CUA runtime registers itself; an external
|
|
1710
|
+
* client has nothing to register, so the agent has nowhere to run.
|
|
1711
|
+
*/
|
|
1712
|
+
const CODE_TASK_RUNTIME_UNAVAILABLE = 710010702;
|
|
1713
|
+
/** The listings, derived from the catalog the reference implementation measured. */
|
|
1714
|
+
function doubaoListing() {
|
|
1715
|
+
const rows = [];
|
|
1716
|
+
for (const model of DOUBAO_MODELS) {
|
|
1717
|
+
const parts = [];
|
|
1718
|
+
if (typeof model.badge === "string" && model.badge !== "") parts.push(model.badge);
|
|
1719
|
+
if (model.reasoning === true) parts.push("推理");
|
|
1720
|
+
rows.push({
|
|
1721
|
+
id: model.id,
|
|
1722
|
+
name: model.name,
|
|
1723
|
+
...parts.length === 0 ? {} : { description: parts.join(" · ") }
|
|
1724
|
+
});
|
|
1725
|
+
}
|
|
1726
|
+
return rows;
|
|
1727
|
+
}
|
|
1728
|
+
/** The text of a host content value, which may be a string or a block list. */
|
|
1729
|
+
function textOf$1(content) {
|
|
1730
|
+
if (typeof content === "string") return content;
|
|
1731
|
+
if (!Array.isArray(content)) return "";
|
|
1732
|
+
const out = [];
|
|
1733
|
+
for (const block of content) {
|
|
1734
|
+
if (typeof block === "string") {
|
|
1735
|
+
out.push(block);
|
|
1736
|
+
continue;
|
|
1737
|
+
}
|
|
1738
|
+
if (typeof block !== "object" || block === null) continue;
|
|
1739
|
+
const record = block;
|
|
1740
|
+
if (typeof record["text"] === "string") out.push(record["text"]);
|
|
1741
|
+
}
|
|
1742
|
+
return out.join("\n");
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* Flatten the host's message list into the single prompt Doubao takes.
|
|
1746
|
+
*
|
|
1747
|
+
* Doubao keeps history server-side under a conversation id, so the exchange is expressed by
|
|
1748
|
+
* the CONVERSATION. What has to travel inline is the system instruction and whatever the
|
|
1749
|
+
* caller put in front of the last user turn. A single question stays a single question.
|
|
1750
|
+
*/
|
|
1751
|
+
function promptFromMessages(messages) {
|
|
1752
|
+
const parts = [];
|
|
1753
|
+
for (const message of messages) {
|
|
1754
|
+
if (typeof message !== "object" || message === null) continue;
|
|
1755
|
+
const text = textOf$1(message["content"]);
|
|
1756
|
+
if (text !== "") parts.push(text);
|
|
1757
|
+
}
|
|
1758
|
+
return parts.join("\n\n");
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* The llm face for Doubao.
|
|
1762
|
+
*
|
|
1763
|
+
* `stream` yields text and reasoning as they arrive: `chat()` calls back per chunk, and the
|
|
1764
|
+
* chunks are queued and drained so a long answer appears progressively instead of landing
|
|
1765
|
+
* whole at the end.
|
|
1766
|
+
*/
|
|
1767
|
+
function createDoubaoLlm(options) {
|
|
1768
|
+
return {
|
|
1769
|
+
listModels: async (provider) => {
|
|
1770
|
+
if (provider !== "doubao") return [];
|
|
1771
|
+
return doubaoListing();
|
|
1772
|
+
},
|
|
1773
|
+
stream: async function* (streamOptions) {
|
|
1774
|
+
const session = options.session();
|
|
1775
|
+
if (session === void 0 || !sessionUsable(session)) throw new Error("还没有浏览器登录态。请在豆包卡片里点「重新登录」扫码一次。");
|
|
1776
|
+
const modelId = typeof streamOptions["model"] === "string" ? streamOptions["model"] : "";
|
|
1777
|
+
const model = findDoubaoModel(modelId);
|
|
1778
|
+
if (model === void 0) throw new Error(`豆包没有模型 ${modelId}:它可能已经下线`);
|
|
1779
|
+
const messages = Array.isArray(streamOptions["messages"]) ? streamOptions["messages"] : [];
|
|
1780
|
+
const system = typeof streamOptions["system"] === "string" ? streamOptions["system"] : "";
|
|
1781
|
+
const body = promptFromMessages(messages);
|
|
1782
|
+
const prompt = system === "" ? body : `${system}\n\n${body}`;
|
|
1783
|
+
if (prompt === "") throw new Error("这条请求没有可发送的文字");
|
|
1784
|
+
/**
|
|
1785
|
+
* The reasoning level.
|
|
1786
|
+
*
|
|
1787
|
+
* The picker sends an opaque branded string; Doubao's levels are named. An unknown
|
|
1788
|
+
* value falls back to the middle level, which every model in the family accepts.
|
|
1789
|
+
*/
|
|
1790
|
+
const requested = streamOptions["reasoningEffort"];
|
|
1791
|
+
const levelName = DOUBAO_REASONING_LEVELS.some((entry) => entry.id === requested) ? String(requested) : "medium";
|
|
1792
|
+
const signal = streamOptions["signal"] instanceof AbortSignal ? streamOptions["signal"] : new AbortController().signal;
|
|
1793
|
+
const textQueue = [];
|
|
1794
|
+
const reasoningQueue = [];
|
|
1795
|
+
let done = false;
|
|
1796
|
+
let failure;
|
|
1797
|
+
let images = [];
|
|
1798
|
+
const turn = chat(prompt, {
|
|
1799
|
+
modelKey: model.id,
|
|
1800
|
+
reasoningLevel: levelName,
|
|
1801
|
+
signal,
|
|
1802
|
+
callbacks: {
|
|
1803
|
+
onText: (chunk) => {
|
|
1804
|
+
if (chunk !== "") textQueue.push(chunk);
|
|
1805
|
+
},
|
|
1806
|
+
onThinking: (chunk) => {
|
|
1807
|
+
if (chunk !== "") reasoningQueue.push(chunk);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
}).then((result) => {
|
|
1811
|
+
if (typeof result.conversationId === "string" && result.conversationId !== "") options.onConversationId?.(result.conversationId);
|
|
1812
|
+
if (Array.isArray(result.images)) images = result.images;
|
|
1813
|
+
}).catch((error) => {
|
|
1814
|
+
failure = error instanceof Error ? error : new Error(String(error));
|
|
1815
|
+
}).finally(() => {
|
|
1816
|
+
done = true;
|
|
1817
|
+
});
|
|
1818
|
+
while (!done || textQueue.length > 0 || reasoningQueue.length > 0) {
|
|
1819
|
+
const reasoning = reasoningQueue.shift();
|
|
1820
|
+
if (reasoning !== void 0) {
|
|
1821
|
+
yield {
|
|
1822
|
+
type: "reasoning-delta",
|
|
1823
|
+
text: reasoning
|
|
1824
|
+
};
|
|
1825
|
+
continue;
|
|
1826
|
+
}
|
|
1827
|
+
const text = textQueue.shift();
|
|
1828
|
+
if (text !== void 0) {
|
|
1829
|
+
yield {
|
|
1830
|
+
type: "text-delta",
|
|
1831
|
+
text
|
|
1832
|
+
};
|
|
1833
|
+
continue;
|
|
1834
|
+
}
|
|
1835
|
+
if (done) break;
|
|
1836
|
+
await Promise.race([turn, new Promise((resolve) => setTimeout(resolve, 20))]);
|
|
1837
|
+
}
|
|
1838
|
+
await turn;
|
|
1839
|
+
if (failure !== void 0) throw failure;
|
|
1840
|
+
for (const image of images) if (typeof image.url === "string" && image.url !== "") yield {
|
|
1841
|
+
type: "text-delta",
|
|
1842
|
+
text: `\n\n\n`
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1847
|
+
//#endregion
|
|
1848
|
+
//#region src/status-paths.ts
|
|
1849
|
+
/**
|
|
1850
|
+
* Node-free constants and types shared by the Host and browser halves of the
|
|
1851
|
+
* XD Pool settings card.
|
|
1852
|
+
*
|
|
1853
|
+
* Pool's runtime state already lives in `src/status.ts` (`buildStatus` /
|
|
1854
|
+
* `WorkBuddyStatus`); this module only carves the cross-domain (Host→browser)
|
|
1855
|
+
* JSON document into a shape that stays token-free and matches what the
|
|
1856
|
+
* browser card renders. Route paths are plugin-owned and mounted on the Host's
|
|
1857
|
+
* same-origin web server (see `src/web-status.ts`).
|
|
1858
|
+
*
|
|
1859
|
+
* @module dsh-xdpool/status-paths
|
|
1860
|
+
*/
|
|
1861
|
+
/** Plugin-owned read-only pool status endpoint (account rows + models + shim). */
|
|
1862
|
+
const POOL_STATUS_PATH = "/plugins/dsh-xdpool/status";
|
|
1863
|
+
/** Plugin-owned local account rescan endpoint (re-read desktop snapshots). */
|
|
1864
|
+
const POOL_RESCAN_PATH = "/plugins/dsh-xdpool/accounts/rescan";
|
|
1865
|
+
/**
|
|
1866
|
+
* Re-fetch the upstream model catalog for both regions.
|
|
1867
|
+
*
|
|
1868
|
+
* Separate from {@link POOL_RESCAN_PATH} because they answer different
|
|
1869
|
+
* questions, and conflating them misled users: "detect accounts again" only
|
|
1870
|
+
* re-read the desktop snapshots, so it could NOT recover a model list that had
|
|
1871
|
+
* fallen back to the static table after a failed startup fetch. The only way
|
|
1872
|
+
* out was restarting DSH.
|
|
1873
|
+
*/
|
|
1874
|
+
const POOL_CATALOG_REFRESH_PATH = "/plugins/dsh-xdpool/models/refresh";
|
|
1875
|
+
/** Plugin-owned cooldown reset endpoint (clear all 429 cooldowns). */
|
|
1876
|
+
const POOL_RESET_COOLDOWN_PATH = "/plugins/dsh-xdpool/cooldowns/reset";
|
|
1877
|
+
/** Plugin-owned daily check-in action endpoint (claim today's reward). */
|
|
1878
|
+
const POOL_CHECKIN_PATH = "/plugins/dsh-xdpool/checkin";
|
|
1879
|
+
/** Plugin-owned model-selection save endpoint (writes the settings section). */
|
|
1880
|
+
const POOL_MODELS_SAVE_PATH = "/plugins/dsh-xdpool/models/save";
|
|
1881
|
+
/** Switch one account in or out of the pool (card toggle). */
|
|
1882
|
+
const POOL_ACCOUNT_DISABLE_PATH = "/plugins/dsh-xdpool/accounts/disabled";
|
|
1883
|
+
/**
|
|
1884
|
+
* Throw one account out of the pool for good, or take it back.
|
|
1885
|
+
*
|
|
1886
|
+
* Separate from the disable route because the semantics differ: disabling is a
|
|
1887
|
+
* rotation preference the account survives, ignoring survives the account.
|
|
1888
|
+
*/
|
|
1889
|
+
const POOL_ACCOUNT_IGNORE_PATH = "/plugins/dsh-xdpool/accounts/ignored";
|
|
1890
|
+
/** Run one automation job immediately, so the card can verify it on demand. */
|
|
1891
|
+
const POOL_AUTOMATION_RUN_PATH = "/plugins/dsh-xdpool/automation/run";
|
|
1892
|
+
/** Set or clear one account's reserved-credit floor. */
|
|
1893
|
+
const POOL_CREDIT_RESERVE_PATH = "/plugins/dsh-xdpool/accounts/credit-reserve";
|
|
1894
|
+
/**
|
|
1895
|
+
* Estimated credit spend, per channel and per model.
|
|
1896
|
+
*
|
|
1897
|
+
* Derived from the pack's own token ledger, never from a credit counter — the pack
|
|
1898
|
+
* records tokens, and the vendor's balance is only visible when it is read again. The
|
|
1899
|
+
* arithmetic (tokens ÷ 1e6 × the model's published multiplier) and the honesty about
|
|
1900
|
+
* its error live in `credits.ts`.
|
|
1901
|
+
*
|
|
1902
|
+
* `?days=N` limits the window; the ledger keeps 90 days.
|
|
1903
|
+
*/
|
|
1904
|
+
const POOL_CREDITS_SPEND_PATH = "/plugins/dsh-xdpool/credits/spend";
|
|
1905
|
+
/**
|
|
1906
|
+
* Name the account to try first, or hand the choice back to the strategy.
|
|
1907
|
+
*
|
|
1908
|
+
* A route rather than a settings write for the reason the ignore list is a file:
|
|
1909
|
+
* the CLI has no settings service, so a card-only settings key could be written
|
|
1910
|
+
* by the card and never by `dsh-xdpool prefer`. The route owns the
|
|
1911
|
+
* write, pushes it into the pool immediately so the very next request sees it,
|
|
1912
|
+
* and is the one path both halves share.
|
|
1913
|
+
*/
|
|
1914
|
+
const POOL_ACCOUNT_PREFER_PATH = "/plugins/dsh-xdpool/accounts/preferred";
|
|
1915
|
+
/**
|
|
1916
|
+
* Read the aggregate lane's state: every registry provider, its saved setting
|
|
1917
|
+
* (never its key), and whether it can serve anything right now.
|
|
1918
|
+
*
|
|
1919
|
+
* Separate from {@link POOL_STATUS_PATH} because it answers a different
|
|
1920
|
+
* question — "what can I configure" rather than "what is my pool doing" — and
|
|
1921
|
+
* because its payload is the WHOLE roster. Folding 76 provider records into the
|
|
1922
|
+
* status document would make every 30-second poll of the pool card carry a
|
|
1923
|
+
* directory nobody reads most of the time.
|
|
1924
|
+
*/
|
|
1925
|
+
const POOL_AGGREGATE_PATH = "/plugins/dsh-xdpool/aggregate";
|
|
1926
|
+
/**
|
|
1927
|
+
* Save one aggregate provider's setting: its key, its on/off switch, its base-URL
|
|
1928
|
+
* override, or the model ids a listing round discovered.
|
|
1929
|
+
*
|
|
1930
|
+
* POST only, and one provider per request — read-modify-write on the host side,
|
|
1931
|
+
* so two tabs editing two providers cannot clobber each other.
|
|
1932
|
+
*/
|
|
1933
|
+
const POOL_AGGREGATE_SAVE_PATH = "/plugins/dsh-xdpool/aggregate/save";
|
|
1934
|
+
/**
|
|
1935
|
+
* Verify one provider's key with a cheap non-generating call, and report what
|
|
1936
|
+
* its listing answered.
|
|
1937
|
+
*
|
|
1938
|
+
* Its own route because it is the only aggregate action that talks to the
|
|
1939
|
+
* network: a probe must never run as a side effect of saving a setting, or
|
|
1940
|
+
* "save" would silently spend the user's rate limit.
|
|
1941
|
+
*/
|
|
1942
|
+
const POOL_AGGREGATE_TEST_PATH = "/plugins/dsh-xdpool/aggregate/test";
|
|
1943
|
+
/**
|
|
1944
|
+
* Send one real streaming call to one model and report how it answered.
|
|
1945
|
+
*
|
|
1946
|
+
* Its own route, and POST-only, for the same reason the provider probe is: this
|
|
1947
|
+
* is the one action in the plugin that spends the user's credits, so it must
|
|
1948
|
+
* never be reachable by a prefetch, a GET, or any side effect of opening a
|
|
1949
|
+
* settings page. A GET here would let a browser — or anything else that can
|
|
1950
|
+
* reach a loopback port — fire unlimited billed calls by walking URLs.
|
|
1951
|
+
*
|
|
1952
|
+
* `provider` and `model` are resolved through the host's own adapter registry
|
|
1953
|
+
* rather than through this plugin's lanes, because that registry is the only
|
|
1954
|
+
* place that knows which credential and endpoint a given provider id serves.
|
|
1955
|
+
*/
|
|
1956
|
+
const POOL_MODEL_PROBE_PATH = "/plugins/dsh-xdpool/model/test";
|
|
1957
|
+
/**
|
|
1958
|
+
* POST-only: ask what models several login channels contribute right now.
|
|
1959
|
+
*
|
|
1960
|
+
* A route rather than more fields on {@link POOL_CHANNELS_PATH} because the
|
|
1961
|
+
* answer changes as accounts come and go while the roster does not, and the
|
|
1962
|
+
* login page polls only its own logins — folding live per-provider catalogues
|
|
1963
|
+
* into the roster document would either go stale the moment someone signed in,
|
|
1964
|
+
* or make every page refresh spend a round trip on thirteen providers.
|
|
1965
|
+
*
|
|
1966
|
+
* Read from the host rather than from the pack's own `model.list`, because the
|
|
1967
|
+
* pack keeps only `id`, `name` and two flags and throws away exactly the fields
|
|
1968
|
+
* this is for. The host's catalogue is the same one the model picker reads, so
|
|
1969
|
+
* the two agree by construction instead of by luck.
|
|
1970
|
+
*/
|
|
1971
|
+
const POOL_CHANNEL_MODELS_PATH = "/plugins/dsh-xdpool/channels/models";
|
|
1972
|
+
/**
|
|
1973
|
+
* Fetch one provider's live model list and write it back as its discovered set.
|
|
1974
|
+
*
|
|
1975
|
+
* Separate from the probe on purpose. The probe ANSWERS; this one COMMITS — it
|
|
1976
|
+
* changes what the provider contributes to the picker — so it is its own route
|
|
1977
|
+
* with its own confirmation, and a failed round keeps the previous roster.
|
|
1978
|
+
*/
|
|
1979
|
+
const POOL_AGGREGATE_DISCOVER_PATH = "/plugins/dsh-xdpool/aggregate/discover";
|
|
1980
|
+
/**
|
|
1981
|
+
* The thirteen login channels the vendored pack provides.
|
|
1982
|
+
*
|
|
1983
|
+
* Separate from the aggregate document for the same reason: the two lanes answer
|
|
1984
|
+
* different questions. The aggregate roster is "what can I point a key at", the
|
|
1985
|
+
* channel list is "what can I scan a QR code into", and mixing them in one poll
|
|
1986
|
+
* would put a third-party directory on the critical path of the pool card.
|
|
1987
|
+
*/
|
|
1988
|
+
const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
|
|
1989
|
+
/**
|
|
1990
|
+
* The Doubao lane's session.
|
|
1991
|
+
*
|
|
1992
|
+
* POST starts an interactive browser sign-in and answers once it lands;
|
|
1993
|
+
* GET reports whether a session is stored; DELETE forgets it.
|
|
1994
|
+
*/
|
|
1995
|
+
const POOL_DOUBAO_SESSION_PATH = "/plugins/dsh-xdpool/doubao/session";
|
|
1996
|
+
/** The Doubao quota: the windows the account has, with their reset countdowns. */
|
|
1997
|
+
const POOL_DOUBAO_QUOTA_PATH = "/plugins/dsh-xdpool/doubao/quota";
|
|
1998
|
+
/**
|
|
1999
|
+
* The `reason` the channel document carries when the login-channel route is
|
|
2000
|
+
* already owned by another plugin.
|
|
2001
|
+
*
|
|
2002
|
+
* The pack we vendor is byte-identical to the one the sibling login-channel
|
|
2003
|
+
* build mounts, and both claim the same fetch route; the host has no query for
|
|
2004
|
+
* what is already registered, so the loser of that race can only tell it lost.
|
|
2005
|
+
* Both halves need the same string — the host to say it, the card to choose
|
|
2006
|
+
* between "this host cannot run the channels" and "another plugin already runs
|
|
2007
|
+
* them", which are opposite sentences — so it is declared with the other wire
|
|
2008
|
+
* constants rather than in `channels.ts`, which the browser bundle may not
|
|
2009
|
+
* import for value.
|
|
2010
|
+
*/
|
|
2011
|
+
const ROUTE_OWNED_ELSEWHERE = "already-mounted-elsewhere";
|
|
2012
|
+
/**
|
|
2013
|
+
* The routing chains, and the whole model roster a member may name.
|
|
2014
|
+
*
|
|
2015
|
+
* One route for both because the editor cannot be drawn without the roster: a
|
|
2016
|
+
* member is chosen from a list, and a list of ids with no names, windows or
|
|
2017
|
+
* vendors is a list nobody can pick from. Reading two documents on one panel
|
|
2018
|
+
* open would also mean the roster could be a second older than the chains.
|
|
2019
|
+
*/
|
|
2020
|
+
const POOL_COMBOS_PATH = "/plugins/dsh-xdpool/combos";
|
|
2021
|
+
/**
|
|
2022
|
+
* Replace the whole chain list in one write.
|
|
2023
|
+
*
|
|
2024
|
+
* A single table replace rather than a per-chain patch: the editor's unit of
|
|
2025
|
+
* intent is "this is my routing table", and deleting one member is
|
|
2026
|
+
* indistinguishable from deleting that member's chain once ids are equal — so a
|
|
2027
|
+
* merge rule would have to guess, and a wrong guess silently resurrects a row the
|
|
2028
|
+
* user deleted.
|
|
2029
|
+
*/
|
|
2030
|
+
const POOL_COMBOS_SAVE_PATH = "/plugins/dsh-xdpool/combos/save";
|
|
2031
|
+
/**
|
|
2032
|
+
* The LAN relay's own state, and the only way to change it.
|
|
2033
|
+
*
|
|
2034
|
+
* One GET and one POST rather than a separate settings surface, because the relay
|
|
2035
|
+
* is a switch you have to be able to kill from the same card that turns it on —
|
|
2036
|
+
* a relay left listening on a network interface is the one failure here that
|
|
2037
|
+
* keeps mattering after the plugin is closed.
|
|
2038
|
+
*/
|
|
2039
|
+
const POOL_RELAY_PATH = "/plugins/dsh-xdpool/relay";
|
|
2040
|
+
/**
|
|
2041
|
+
* Read the usage panel's aggregate.
|
|
2042
|
+
*
|
|
2043
|
+
* GET only, and token-free by construction: the recorder holds counts and
|
|
2044
|
+
* timings, never a prompt. The document type is `UsageSummary` from
|
|
2045
|
+
* `src/stats.ts` rather than a copy declared here, because that module stays
|
|
2046
|
+
* Node-free precisely so the browser half can import the SAME declaration
|
|
2047
|
+
* instead of a second one that could quietly drift.
|
|
2048
|
+
*/
|
|
2049
|
+
const POOL_USAGE_PATH = "/plugins/dsh-xdpool/usage";
|
|
2050
|
+
/** The five strategies, as a value, so a request body can be validated against it. */
|
|
2051
|
+
const POOL_DISTRIBUTIONS = Object.freeze([
|
|
2052
|
+
"priority",
|
|
2053
|
+
"round-robin",
|
|
2054
|
+
"balanced",
|
|
2055
|
+
"sticky",
|
|
2056
|
+
"expiry"
|
|
2057
|
+
]);
|
|
2058
|
+
/** True when `value` names one of the five documented strategies. */
|
|
2059
|
+
function isDistributionStrategy(value) {
|
|
2060
|
+
return POOL_DISTRIBUTIONS.includes(value);
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* The schedule every automation job falls back to.
|
|
2064
|
+
*
|
|
2065
|
+
* Shared by both halves on purpose. The host uses it when a configured hour
|
|
2066
|
+
* list arrives empty (the settings schema materializes "never configured" into
|
|
2067
|
+
* `[]`), and the card uses it when it writes the `automation` block back, so a
|
|
2068
|
+
* document that already holds an empty list is healed instead of being saved
|
|
2069
|
+
* back as an unrunnable schedule.
|
|
2070
|
+
*
|
|
2071
|
+
* This lives here rather than in `scheduler.ts` because the browser half cannot
|
|
2072
|
+
* import the host module: `scheduler.ts` pulls in `node:crypto` and the whole
|
|
2073
|
+
* upstream client, none of which exists in the browser bundle. Two hand-written
|
|
2074
|
+
* copies would drift, and the drift is invisible — the card would write a
|
|
2075
|
+
* schedule the scheduler does not run.
|
|
2076
|
+
*/
|
|
2077
|
+
const DEFAULT_AUTOMATION_HOURS = {
|
|
2078
|
+
checkin: [9],
|
|
2079
|
+
report: [10],
|
|
2080
|
+
tasks: [11],
|
|
2081
|
+
streak: [12],
|
|
2082
|
+
travel: [9, 21],
|
|
2083
|
+
compensation: [13]
|
|
2084
|
+
};
|
|
2085
|
+
/**
|
|
2086
|
+
* Parse one of the server's amount fields.
|
|
2087
|
+
*
|
|
2088
|
+
* They arrive as formatted strings ("2,100"), and they are the only source of a
|
|
2089
|
+
* percentage for the plans that omit `used_percent`. Returns undefined rather
|
|
2090
|
+
* than NaN so callers can tell "no data" from "zero".
|
|
2091
|
+
*/
|
|
2092
|
+
function parseAmount(value) {
|
|
2093
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
2094
|
+
if (typeof value !== "string") return void 0;
|
|
2095
|
+
const digits = value.replace(/[^0-9.]/g, "");
|
|
2096
|
+
if (digits === "") return void 0;
|
|
2097
|
+
const parsed = Number(digits);
|
|
2098
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2099
|
+
}
|
|
2100
|
+
function mapWindowType(value) {
|
|
2101
|
+
if (value === 1) return "five_hour";
|
|
2102
|
+
if (value === 2) return "weekly";
|
|
2103
|
+
if (value === 3) return "incentive";
|
|
2104
|
+
}
|
|
2105
|
+
/**
|
|
2106
|
+
* Convert one server window into the shape the UI consumes.
|
|
2107
|
+
*
|
|
2108
|
+
* Three shapes are observed:
|
|
2109
|
+
*
|
|
2110
|
+
* - both timestamps present: a rolling window with a real reset instant;
|
|
2111
|
+
* - both zero: the window has not started yet (Doubao renders
|
|
2112
|
+
* 「开始使用后计时」); the reset instant is unknown and MUST NOT be invented;
|
|
2113
|
+
* - only `end_time`: a promotional grant with an expiry but no start.
|
|
2114
|
+
*
|
|
2115
|
+
* Reconstructing a missing start from the nominal window length used to make
|
|
2116
|
+
* the card count down to a moment the server never sent — off by up to a week.
|
|
2117
|
+
*/
|
|
2118
|
+
function normalizeWindow(raw, label) {
|
|
2119
|
+
const type = raw.window_type === void 0 ? void 0 : mapWindowType(raw.window_type);
|
|
2120
|
+
if (!type) return void 0;
|
|
2121
|
+
const start = raw.start_time ?? 0;
|
|
2122
|
+
const end = raw.end_time ?? 0;
|
|
2123
|
+
const usedAmount = parseAmount(raw.used_amount);
|
|
2124
|
+
const totalAmount = parseAmount(raw.total_amount);
|
|
2125
|
+
const fromAmounts = usedAmount !== void 0 && totalAmount !== void 0 && totalAmount > 0 ? Math.min(100, Math.max(0, usedAmount / totalAmount * 100)) : void 0;
|
|
2126
|
+
const used = typeof raw.used_percent === "number" ? raw.used_percent : fromAmounts ?? 0;
|
|
2127
|
+
const base = {
|
|
2128
|
+
type,
|
|
2129
|
+
windowType: raw.window_type,
|
|
2130
|
+
usedPercent: used,
|
|
2131
|
+
remainingPercent: Math.max(0, 100 - used),
|
|
2132
|
+
...label === void 0 || label === "" ? {} : { label },
|
|
2133
|
+
...usedAmount === void 0 ? {} : { usedAmount },
|
|
2134
|
+
...totalAmount === void 0 ? {} : { totalAmount }
|
|
2135
|
+
};
|
|
2136
|
+
if (end <= 0) return {
|
|
2137
|
+
...base,
|
|
2138
|
+
resetsAt: 0,
|
|
2139
|
+
startedAt: 0,
|
|
2140
|
+
windowMs: 0,
|
|
2141
|
+
resetUnknown: true,
|
|
2142
|
+
startsOnUse: true
|
|
2143
|
+
};
|
|
2144
|
+
return {
|
|
2145
|
+
...base,
|
|
2146
|
+
...start <= 0 ? { startsOnUse: true } : {},
|
|
2147
|
+
resetsAt: end,
|
|
2148
|
+
startedAt: start > 0 ? start : 0,
|
|
2149
|
+
windowMs: start > 0 && end > start ? end - start : 0
|
|
2150
|
+
};
|
|
2151
|
+
}
|
|
2152
|
+
/**
|
|
2153
|
+
* How long a FAILED reading is reused.
|
|
2154
|
+
*
|
|
2155
|
+
* The quota endpoint is consulted before every chat turn, and a failure used to
|
|
2156
|
+
* be forgotten immediately — so an outage cost every single turn another round
|
|
2157
|
+
* trip that was going to fail the same way, on the request's critical path. The
|
|
2158
|
+
* window is short enough that a recovery is invisible (a turn later) and long
|
|
2159
|
+
* enough to stop that fan-out.
|
|
2160
|
+
*/
|
|
2161
|
+
const QUOTA_FAILURE_TTL_MS = 3e4;
|
|
2162
|
+
/**
|
|
2163
|
+
* Remember a failed reading, and return it.
|
|
2164
|
+
*
|
|
2165
|
+
* One helper because all three failure exits (no credentials, HTTP error,
|
|
2166
|
+
* thrown) must go through it: a failure that skips the memo is exactly the bug
|
|
2167
|
+
* this exists to prevent.
|
|
2168
|
+
*/
|
|
2169
|
+
function rememberFailure(quota) {
|
|
2170
|
+
cachedFailure = quota;
|
|
2171
|
+
cachedFailureAt = Date.now();
|
|
2172
|
+
return quota;
|
|
2173
|
+
}
|
|
2174
|
+
/**
|
|
2175
|
+
* Only report the account as exhausted when all active quota entitlements say
|
|
2176
|
+
* so: an exhausted promotional bonus must not block turns while the main
|
|
2177
|
+
* window still has headroom.
|
|
2178
|
+
*/
|
|
2179
|
+
function evaluateQuotaExhausted(data) {
|
|
2180
|
+
const hasActiveGroups = (section) => Boolean(section?.window_limit_groups?.some((g) => (g.window_limits?.length ?? 0) > 0));
|
|
2181
|
+
const windowExhausted = data?.window_limit_section?.usage_exhausted;
|
|
2182
|
+
const enterpriseExhausted = data?.enterprise_window_limit_section?.usage_exhausted;
|
|
2183
|
+
const incentiveExhausted = data?.incentive_quota_section?.usage_exhausted;
|
|
2184
|
+
const activeFlags = [];
|
|
2185
|
+
if (typeof windowExhausted === "boolean") activeFlags.push(windowExhausted);
|
|
2186
|
+
if (typeof enterpriseExhausted === "boolean" && hasActiveGroups(data?.enterprise_window_limit_section)) activeFlags.push(enterpriseExhausted);
|
|
2187
|
+
if (typeof incentiveExhausted === "boolean" && hasActiveGroups(data?.incentive_quota_section)) activeFlags.push(incentiveExhausted);
|
|
2188
|
+
const fallbackFlags = [
|
|
2189
|
+
windowExhausted,
|
|
2190
|
+
enterpriseExhausted,
|
|
2191
|
+
incentiveExhausted
|
|
2192
|
+
].filter((flag) => typeof flag === "boolean");
|
|
2193
|
+
const flags = activeFlags.length > 0 ? activeFlags : fallbackFlags;
|
|
2194
|
+
return flags.length > 0 && flags.every(Boolean);
|
|
2195
|
+
}
|
|
2196
|
+
async function fetchQuota(options = {}) {
|
|
2197
|
+
const now = Date.now();
|
|
2198
|
+
if (!options.force && cached && now - cached.fetchedAt < 3e5) return cached;
|
|
2199
|
+
if (!options.force && cachedFailure !== void 0 && now - cachedFailureAt < QUOTA_FAILURE_TTL_MS) return cachedFailure;
|
|
2200
|
+
/**
|
|
2201
|
+
* No session is a quotable answer, not a throw.
|
|
2202
|
+
*
|
|
2203
|
+
* The quota panel sits beside the chat card, and a user who has not signed in yet still
|
|
2204
|
+
* needs to SEE it — with "not signed in" in the error field — rather than have the panel
|
|
2205
|
+
* disappear or the card throw on render.
|
|
2206
|
+
*/
|
|
2207
|
+
let credentials;
|
|
2208
|
+
try {
|
|
2209
|
+
credentials = requireDoubaoCredentials();
|
|
2210
|
+
} catch (error) {
|
|
2211
|
+
return rememberFailure({
|
|
2212
|
+
exhausted: false,
|
|
2213
|
+
windows: [],
|
|
2214
|
+
fetchedAt: now,
|
|
2215
|
+
error: error instanceof Error ? error.message : "Doubao credentials unavailable."
|
|
2216
|
+
});
|
|
2217
|
+
}
|
|
2218
|
+
try {
|
|
2219
|
+
const response = await fetch(buildQueryUrl(QUOTA_ENDPOINT, credentials.pairs.get("msToken")), {
|
|
2220
|
+
method: "POST",
|
|
2221
|
+
headers: buildHeaders(credentials, { "content-type": "application/json" }),
|
|
2222
|
+
body: JSON.stringify({ product_line: "membership" })
|
|
2223
|
+
});
|
|
2224
|
+
if (!response.ok) return rememberFailure({
|
|
2225
|
+
exhausted: false,
|
|
2226
|
+
windows: [],
|
|
2227
|
+
fetchedAt: now,
|
|
2228
|
+
error: `HTTP ${response.status}`
|
|
2229
|
+
});
|
|
2230
|
+
const payload = await response.json();
|
|
2231
|
+
const sections = [payload.data?.window_limit_section, payload.data?.incentive_quota_section];
|
|
2232
|
+
const windows = [];
|
|
2233
|
+
for (const section of sections) for (const group of section?.window_limit_groups ?? []) for (const limit of group.window_limits ?? []) {
|
|
2234
|
+
const normalized = normalizeWindow(limit, group.feature_group_name);
|
|
2235
|
+
if (normalized) windows.push(normalized);
|
|
2236
|
+
}
|
|
2237
|
+
const quota = {
|
|
2238
|
+
exhausted: evaluateQuotaExhausted(payload.data),
|
|
2239
|
+
windows,
|
|
2240
|
+
fetchedAt: now
|
|
2241
|
+
};
|
|
2242
|
+
const plan = payload.data?.current_subscription?.display?.short_name;
|
|
2243
|
+
if (plan) quota.plan = plan;
|
|
2244
|
+
if (payload.data?.member_info?.hasActiveSubscription !== void 0) quota.planActive = payload.data.member_info.hasActiveSubscription;
|
|
2245
|
+
cached = quota;
|
|
2246
|
+
cachedFailure = void 0;
|
|
2247
|
+
return quota;
|
|
2248
|
+
} catch (error) {
|
|
2249
|
+
return rememberFailure({
|
|
2250
|
+
exhausted: false,
|
|
2251
|
+
windows: [],
|
|
2252
|
+
fetchedAt: now,
|
|
2253
|
+
error: error.message
|
|
2254
|
+
});
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
let cached;
|
|
2258
|
+
/** The last FAILED reading, reused for {@link QUOTA_FAILURE_TTL_MS}. */
|
|
2259
|
+
let cachedFailure;
|
|
2260
|
+
let cachedFailureAt = 0;
|
|
2261
|
+
//#endregion
|
|
2262
|
+
//#region src/doubao-routes.ts
|
|
2263
|
+
/** Write a JSON response. */
|
|
2264
|
+
function json$1(res, status, body) {
|
|
2265
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
2266
|
+
res.end(JSON.stringify(body));
|
|
2267
|
+
}
|
|
2268
|
+
/**
|
|
2269
|
+
* Whether the request came from the host's own page.
|
|
2270
|
+
*
|
|
2271
|
+
* An ABSENT `Origin` is allowed and is the common case: only cross-origin requests carry the
|
|
2272
|
+
* header, so a same-origin request from the card sends none. Requiring it refused every call
|
|
2273
|
+
* the UI made — the paste arrived, was rejected `403` before any parsing ran, and the card
|
|
2274
|
+
* reported it as a bad cookie. A page in the user's browser driving this endpoint is
|
|
2275
|
+
* cross-origin by construction and always sends `Origin`, so the hostname check covers it.
|
|
2276
|
+
*/
|
|
2277
|
+
function loopbackOrigin$1(req) {
|
|
2278
|
+
const origin = req.headers.origin;
|
|
2279
|
+
if (typeof origin !== "string" || origin === "") return true;
|
|
2280
|
+
try {
|
|
2281
|
+
const url = new URL(origin);
|
|
2282
|
+
return url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
|
|
2283
|
+
} catch {
|
|
2284
|
+
return false;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
/**
|
|
2288
|
+
* Mount the Doubao routes.
|
|
2289
|
+
*
|
|
2290
|
+
* The sign-in route answers `signedIn: false` rather than an error when the user closes the
|
|
2291
|
+
* window: "did not finish signing in" is an ordinary state, and the card says so.
|
|
2292
|
+
*/
|
|
2293
|
+
function registerDoubaoRoutes(ctx, deps) {
|
|
2294
|
+
ctx.effect(() => {
|
|
2295
|
+
const disposeSession = ctx.webServer.register({
|
|
2296
|
+
kind: "exact",
|
|
2297
|
+
path: POOL_DOUBAO_SESSION_PATH,
|
|
2298
|
+
handler: async (req, res) => {
|
|
2299
|
+
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2300
|
+
try {
|
|
2301
|
+
if (req.method === "DELETE") {
|
|
2302
|
+
deps.clear();
|
|
2303
|
+
setDoubaoSession(void 0);
|
|
2304
|
+
return json$1(res, 200, {
|
|
2305
|
+
ok: true,
|
|
2306
|
+
signedIn: false
|
|
2307
|
+
});
|
|
2308
|
+
}
|
|
2309
|
+
if (req.method === "POST") {
|
|
2310
|
+
/**
|
|
2311
|
+
* Start an interactive sign-in, and answer when it lands or times out.
|
|
2312
|
+
*
|
|
2313
|
+
* The window stays open for the whole budget: a QR scan plus a phone confirmation
|
|
2314
|
+
* is a minute of a person's time, and cutting it short would make the lane look
|
|
2315
|
+
* broken to anyone who was simply slower than the timer.
|
|
2316
|
+
*/
|
|
2317
|
+
const result = await browserLogin();
|
|
2318
|
+
if (!result.ok || result.session === void 0) return json$1(res, 200, {
|
|
2319
|
+
ok: false,
|
|
2320
|
+
signedIn: false,
|
|
2321
|
+
message: result.reason ?? "登录失败"
|
|
2322
|
+
});
|
|
2323
|
+
deps.save(result.session);
|
|
2324
|
+
setDoubaoSession(result.session);
|
|
2325
|
+
return json$1(res, 200, {
|
|
2326
|
+
ok: true,
|
|
2327
|
+
signedIn: true,
|
|
2328
|
+
message: "登录成功,会话已保存"
|
|
2329
|
+
});
|
|
2330
|
+
}
|
|
2331
|
+
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2332
|
+
/**
|
|
2333
|
+
* A read is not passive: the sign-in browser may be open and already signed into,
|
|
2334
|
+
* and the card asks every couple of seconds while the user finishes. Harvesting on
|
|
2335
|
+
* read is what turns that window into an account without the user pressing anything
|
|
2336
|
+
* twice.
|
|
2337
|
+
*/
|
|
2338
|
+
const live = await readExistingSession();
|
|
2339
|
+
if (live !== void 0) {
|
|
2340
|
+
deps.save(live);
|
|
2341
|
+
setDoubaoSession(live);
|
|
2342
|
+
return json$1(res, 200, {
|
|
2343
|
+
ok: true,
|
|
2344
|
+
signedIn: true,
|
|
2345
|
+
savedAt: live.savedAt
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
const stored = deps.session();
|
|
2349
|
+
return json$1(res, 200, {
|
|
2350
|
+
ok: true,
|
|
2351
|
+
signedIn: sessionUsable(stored),
|
|
2352
|
+
...stored?.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
|
|
2353
|
+
});
|
|
2354
|
+
} catch (error) {
|
|
2355
|
+
return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
});
|
|
2359
|
+
const disposeQuota = ctx.webServer.register({
|
|
2360
|
+
kind: "exact",
|
|
2361
|
+
path: POOL_DOUBAO_QUOTA_PATH,
|
|
2362
|
+
handler: async (req, res) => {
|
|
2363
|
+
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2364
|
+
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2365
|
+
const session = deps.session();
|
|
2366
|
+
if (session === void 0 || !sessionUsable(session)) return json$1(res, 200, {
|
|
2367
|
+
ok: false,
|
|
2368
|
+
signedIn: false,
|
|
2369
|
+
windows: []
|
|
2370
|
+
});
|
|
2371
|
+
try {
|
|
2372
|
+
setDoubaoSession(session);
|
|
2373
|
+
const quota = await fetchQuota({ force: true });
|
|
2374
|
+
return json$1(res, 200, {
|
|
2375
|
+
ok: quota.error === void 0,
|
|
2376
|
+
signedIn: true,
|
|
2377
|
+
exhausted: quota.exhausted,
|
|
2378
|
+
...quota.error === void 0 ? {} : { error: quota.error },
|
|
2379
|
+
windows: quota.windows
|
|
2380
|
+
});
|
|
2381
|
+
} catch (error) {
|
|
2382
|
+
return json$1(res, 200, {
|
|
2383
|
+
ok: false,
|
|
2384
|
+
signedIn: true,
|
|
2385
|
+
windows: [],
|
|
2386
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2387
|
+
});
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
});
|
|
2391
|
+
return () => {
|
|
2392
|
+
disposeSession();
|
|
2393
|
+
disposeQuota();
|
|
2394
|
+
};
|
|
2395
|
+
});
|
|
2396
|
+
}
|
|
2397
|
+
//#endregion
|
|
2398
|
+
//#region src/file-perms.ts
|
|
2399
|
+
/**
|
|
2400
|
+
* Write a file that holds credentials, without leaving it world-readable.
|
|
2401
|
+
*
|
|
2402
|
+
* Every credential this plugin keeps on disk — the durable account list, the
|
|
2403
|
+
* ignore list, any mirrored balance — travelled through a plain `writeFile` with
|
|
2404
|
+
* the process umask as the only protection. On a POSIX host that typically means
|
|
2405
|
+
* `0644`: readable by every other user on the machine, and these files carry
|
|
2406
|
+
* `accessToken` / `refreshToken` verbatim.
|
|
2407
|
+
*
|
|
2408
|
+
* Two rules, and the order matters:
|
|
2409
|
+
*
|
|
2410
|
+
* 1. **Create, don't patch.** `mode` on `writeFile` only applies when the file is
|
|
2411
|
+
* created. The atomic-write pattern already writes a fresh temp file and
|
|
2412
|
+
* renames it over the target, so the temp is created with `0600` and the
|
|
2413
|
+
* rename carries that permission to the destination. Chmod'ing afterwards
|
|
2414
|
+
* would also work but leaves a window where the file exists with the old
|
|
2415
|
+
* mode.
|
|
2416
|
+
* 2. **Still chmod best-effort.** A file written by an older version already
|
|
2417
|
+
* exists with `0644`; the rename replaces the inode, so rule 1 covers it —
|
|
2418
|
+
* but a host that keeps the target in place (or a future caller that writes
|
|
2419
|
+
* directly) would not be covered, and `chmod` is cheap.
|
|
2420
|
+
*
|
|
2421
|
+
* WINDOWS: `mode` is ignored by Node on win32, and there is no ACL equivalent in
|
|
2422
|
+
* the standard library. The honest statement is what actually protects these
|
|
2423
|
+
* files there: they live under the user's own profile (%USERPROFILE%, %LOCALAPPDATA%),
|
|
2424
|
+
* whose inherited ACL excludes other standard users by default. Calling `icacls`
|
|
2425
|
+
* per write would spawn a process on every balance update to re-apply a
|
|
2426
|
+
* protection the parent directory already provides, so this module does not. A
|
|
2427
|
+
* profile relocated to a shared directory is outside what this code can detect —
|
|
2428
|
+
* the README says where the files live so the user can check.
|
|
2429
|
+
*
|
|
2430
|
+
* @module dsh-xdpool/file-perms
|
|
2431
|
+
*/
|
|
2432
|
+
/** Owner-only, for a file that holds a secret. */
|
|
2433
|
+
const SECRET_FILE_MODE = 384;
|
|
2434
|
+
/** Owner-only, for the directory that holds them. */
|
|
2435
|
+
const SECRET_DIR_MODE = 448;
|
|
2436
|
+
/**
|
|
2437
|
+
* True on a platform where POSIX modes are meaningful.
|
|
2438
|
+
*
|
|
2439
|
+
* Computed through a `typeof process` guard rather than read straight off the
|
|
2440
|
+
* global: this module is host-only in intent, but `store.ts` imports it and the
|
|
2441
|
+
* browser bundle imports `store.ts` for its row types, so the module body DOES
|
|
2442
|
+
* get bundled for the browser. A bare `process.platform` there throws
|
|
2443
|
+
* `ReferenceError: process is not defined` at first render — and it is the kind
|
|
2444
|
+
* of failure that only shows up in the packaged app.
|
|
2445
|
+
*/
|
|
2446
|
+
const POSIX = typeof process === "undefined" ? false : process.platform !== "win32";
|
|
2447
|
+
/**
|
|
2448
|
+
* Create the directory a secret lives in, owner-only.
|
|
2449
|
+
*
|
|
2450
|
+
* `recursive` so a fresh install works, and the mode applies to every directory
|
|
2451
|
+
* this call creates. An existing directory keeps its mode — `mkdir` does not
|
|
2452
|
+
* change what is already there — so `chmod` runs too, best-effort: tightening a
|
|
2453
|
+
* directory that a previous version created permissively is exactly the case
|
|
2454
|
+
* worth fixing, and a failure is not worth aborting a save over.
|
|
2455
|
+
*/
|
|
2456
|
+
async function ensureSecretDir(dir) {
|
|
2457
|
+
await mkdir(dir, {
|
|
2458
|
+
recursive: true,
|
|
2459
|
+
...POSIX ? { mode: SECRET_DIR_MODE } : {}
|
|
2460
|
+
});
|
|
2461
|
+
if (!POSIX) return;
|
|
2462
|
+
try {
|
|
2463
|
+
await chmod(dir, SECRET_DIR_MODE);
|
|
2464
|
+
} catch {}
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* Write `contents` to `path` with owner-only permissions.
|
|
2468
|
+
*
|
|
2469
|
+
* Not atomic on its own — callers that need the crash-safe temp+rename dance keep
|
|
2470
|
+
* doing it and just route the temp write through here, which is why the mode is
|
|
2471
|
+
* applied at creation: the rename then carries it to the final file.
|
|
2472
|
+
*/
|
|
2473
|
+
async function writeSecretFile(path, contents) {
|
|
2474
|
+
await writeFile(path, contents, POSIX ? {
|
|
2475
|
+
encoding: "utf8",
|
|
2476
|
+
mode: SECRET_FILE_MODE
|
|
2477
|
+
} : "utf8");
|
|
2478
|
+
if (!POSIX) return;
|
|
2479
|
+
try {
|
|
2480
|
+
await chmod(path, SECRET_FILE_MODE);
|
|
2481
|
+
} catch {}
|
|
2482
|
+
}
|
|
2483
|
+
//#endregion
|
|
2484
|
+
//#region src/ignored.ts
|
|
2485
|
+
/**
|
|
2486
|
+
* The permanent ignore list: accounts the user has thrown out of the pool.
|
|
2487
|
+
*
|
|
2488
|
+
* Distinct from `disabledAccountIds`, which is a ROTATION preference. A disabled
|
|
2489
|
+
* account stays on the card, can be switched back on, and its credential keeps
|
|
2490
|
+
* being read on every scan. Ignoring is a statement about the ACCOUNT — "this
|
|
2491
|
+
* one is not mine any more" — so an ignored account is skipped BEFORE its
|
|
2492
|
+
* credential is decrypted, never appears among the pool's accounts, and does not
|
|
2493
|
+
* come back when the desktop app writes a fresh `.info` file for it.
|
|
2494
|
+
*
|
|
2495
|
+
* It lives in a plugin-owned file rather than in the settings document for one
|
|
2496
|
+
* practical reason: the CLI has no settings service. `dsh-xdpool
|
|
2497
|
+
* ignore <id>` runs without a host, so a settings-only list could be written by
|
|
2498
|
+
* the card and never by the CLI. One file, read by both halves, keeps the two
|
|
2499
|
+
* views of "which accounts are ignored" identical by construction.
|
|
2500
|
+
*
|
|
2501
|
+
* @module dsh-xdpool/ignored
|
|
2502
|
+
*/
|
|
2503
|
+
/** Directory holding this plugin's own state (imported snapshots, ignore list). */
|
|
2504
|
+
const PLUGIN_DATA_DIR_NAME = ".xdpool";
|
|
2505
|
+
/** File holding the permanent ignore list, inside {@link pluginDataDir}. */
|
|
2506
|
+
const IGNORED_FILE_NAME = "ignored.json";
|
|
2507
|
+
/**
|
|
2508
|
+
* The DSH home directory, honouring the same override the host uses.
|
|
2509
|
+
*
|
|
2510
|
+
* Shared by the CLI and the host so both halves resolve the same file: an
|
|
2511
|
+
* `ignore` written from the terminal has to be visible to the running plugin,
|
|
2512
|
+
* which is only true if they agree on where "home" is.
|
|
2513
|
+
*/
|
|
2514
|
+
function dshHome(env = process.env) {
|
|
2515
|
+
const fromEnv = env["DSH_HOME"];
|
|
2516
|
+
if (typeof fromEnv === "string" && fromEnv.trim() !== "") return fromEnv.trim();
|
|
2517
|
+
return join(homedir(), ".dsh");
|
|
2518
|
+
}
|
|
2519
|
+
/** This plugin's own state directory. */
|
|
2520
|
+
function pluginDataDir(env = process.env) {
|
|
2521
|
+
return join(dshHome(env), PLUGIN_DATA_DIR_NAME);
|
|
2522
|
+
}
|
|
2523
|
+
/** Absolute path of the ignore list. */
|
|
2524
|
+
function ignoredIdsPath(env = process.env) {
|
|
2525
|
+
return join(pluginDataDir(env), IGNORED_FILE_NAME);
|
|
2526
|
+
}
|
|
2527
|
+
/**
|
|
2528
|
+
* Normalize whatever the file holds into a clean list.
|
|
2529
|
+
*
|
|
2530
|
+
* Tolerant on purpose: this file is hand-editable and a malformed entry must not
|
|
2531
|
+
* take the pool down. An entry without a usable id is dropped; a missing label
|
|
2532
|
+
* falls back to the id so the card always has something to print.
|
|
2533
|
+
*/
|
|
2534
|
+
function normalize$1(raw) {
|
|
2535
|
+
if (typeof raw !== "object" || raw === null) return [];
|
|
2536
|
+
const entries = raw.accounts;
|
|
2537
|
+
if (!Array.isArray(entries)) return [];
|
|
2538
|
+
const out = [];
|
|
2539
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2540
|
+
for (const entry of entries) {
|
|
2541
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
2542
|
+
const record = entry;
|
|
2543
|
+
const id = typeof record["id"] === "string" ? record["id"].trim() : "";
|
|
2544
|
+
if (id === "" || seen.has(id)) continue;
|
|
2545
|
+
seen.add(id);
|
|
2546
|
+
const label = typeof record["label"] === "string" && record["label"].trim() !== "" ? record["label"] : id;
|
|
2547
|
+
const ignoredAt = typeof record["ignoredAt"] === "string" ? record["ignoredAt"] : "";
|
|
2548
|
+
out.push({
|
|
2549
|
+
id,
|
|
2550
|
+
label,
|
|
2551
|
+
ignoredAt
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
return out;
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* Read the ignore list, tolerating every "no list yet" shape.
|
|
2558
|
+
*
|
|
2559
|
+
* A missing file, unreadable file, or invalid JSON all mean the same thing to
|
|
2560
|
+
* the caller — nothing is ignored — so none of them throws. The pool must be
|
|
2561
|
+
* able to start on a machine that has never ignored anything.
|
|
2562
|
+
*/
|
|
2563
|
+
async function readIgnoredAccounts(path = ignoredIdsPath()) {
|
|
2564
|
+
try {
|
|
2565
|
+
return normalize$1(JSON.parse(await readFile(path, "utf8")));
|
|
2566
|
+
} catch {
|
|
2567
|
+
return [];
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Synchronous read, for startup.
|
|
2572
|
+
*
|
|
2573
|
+
* The host applies the ignore list from inside `apply()`, which is synchronous,
|
|
2574
|
+
* and doing it there removes a startup race: an async load could resolve AFTER
|
|
2575
|
+
* the first account scan, which would let an ignored account slip into the pool
|
|
2576
|
+
* once per boot. The file is a few hundred bytes, so a blocking read at startup
|
|
2577
|
+
* costs nothing measurable.
|
|
2578
|
+
*/
|
|
2579
|
+
function readIgnoredAccountsSync(path = ignoredIdsPath()) {
|
|
2580
|
+
try {
|
|
2581
|
+
return normalize$1(JSON.parse(readFileSync(path, "utf8")));
|
|
2582
|
+
} catch {
|
|
2583
|
+
return [];
|
|
2584
|
+
}
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Replace the ignore list, atomically.
|
|
2588
|
+
*
|
|
2589
|
+
* Written to a sibling temp file and renamed over the target so a crash (or a
|
|
2590
|
+
* concurrent reader) can never observe a half-written document — the ignore
|
|
2591
|
+
* list is the only thing standing between a dead account and the rotation, and
|
|
2592
|
+
* a truncated file reads as "nothing is ignored", which would quietly put every
|
|
2593
|
+
* discarded account back in the pool.
|
|
2594
|
+
*/
|
|
2595
|
+
async function writeIgnoredAccounts(accounts, path = ignoredIdsPath()) {
|
|
2596
|
+
const payload = JSON.stringify({
|
|
2597
|
+
version: 1,
|
|
2598
|
+
accounts
|
|
2599
|
+
}, null, 2);
|
|
2600
|
+
await ensureSecretDir(dirname(path));
|
|
2601
|
+
const temp = `${path}.tmp`;
|
|
2602
|
+
await writeSecretFile(temp, `${payload}\n`);
|
|
2603
|
+
await rename(temp, path);
|
|
2604
|
+
}
|
|
2605
|
+
/**
|
|
2606
|
+
* Add one account to the ignore list, preserving the rest.
|
|
2607
|
+
*
|
|
2608
|
+
* A read-modify-write rather than a wholesale replace: the card and the CLI can
|
|
2609
|
+
* both be open, and each request names exactly one account, so re-writing the
|
|
2610
|
+
* whole list from a stale view would drop the other side's edits.
|
|
2611
|
+
*/
|
|
2612
|
+
async function ignoreAccount(account, path = ignoredIdsPath()) {
|
|
2613
|
+
const current = await readIgnoredAccounts(path);
|
|
2614
|
+
if (current.some((entry) => entry.id === account.id)) return current;
|
|
2615
|
+
const next = [...current, {
|
|
2616
|
+
id: account.id,
|
|
2617
|
+
label: account.label ?? account.id,
|
|
2618
|
+
ignoredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2619
|
+
}];
|
|
2620
|
+
await writeIgnoredAccounts(next, path);
|
|
2621
|
+
return next;
|
|
2622
|
+
}
|
|
2623
|
+
/** Drop one account from the ignore list. Returns the resulting list. */
|
|
2624
|
+
async function unignoreAccount(accountId, path = ignoredIdsPath()) {
|
|
2625
|
+
const current = await readIgnoredAccounts(path);
|
|
2626
|
+
const next = current.filter((entry) => entry.id !== accountId);
|
|
2627
|
+
if (next.length !== current.length) await writeIgnoredAccounts(next, path);
|
|
2628
|
+
return next;
|
|
2629
|
+
}
|
|
2630
|
+
//#endregion
|
|
2631
|
+
//#region src/doubao-store.ts
|
|
2632
|
+
/**
|
|
2633
|
+
* Where the Doubao session lives between runs.
|
|
2634
|
+
*
|
|
2635
|
+
* WHY A FILE OF ITS OWN
|
|
2636
|
+
*
|
|
2637
|
+
* Every other channel's credential is owned by the pack, which writes it wherever the host's
|
|
2638
|
+
* credential store keeps things. Doubao's session is this plugin's whole lane — one cookie
|
|
2639
|
+
* jar, no refresh token, no key — so it belongs beside the plugin's other state and not in a
|
|
2640
|
+
* store that would try to interpret it.
|
|
2641
|
+
*
|
|
2642
|
+
* The file is written atomically and is readable only by the user: it holds a live session,
|
|
2643
|
+
* and a half-written jar would present as "signed in" while every request failed.
|
|
2644
|
+
*
|
|
2645
|
+
* @module dsh-xdpool/doubao-store
|
|
2646
|
+
*/
|
|
2647
|
+
/** The file the session is kept in. */
|
|
2648
|
+
const DOUBAO_SESSION_FILE = "doubao-session.json";
|
|
2649
|
+
/** The absolute path of the session file. */
|
|
2650
|
+
function doubaoSessionPath() {
|
|
2651
|
+
return join(pluginDataDir(), DOUBAO_SESSION_FILE);
|
|
2652
|
+
}
|
|
2653
|
+
/** Read the stored session, or undefined when there is none or it is unreadable. */
|
|
2654
|
+
async function readStoredSession() {
|
|
2655
|
+
let text;
|
|
2656
|
+
try {
|
|
2657
|
+
text = await readFile(doubaoSessionPath(), "utf8");
|
|
2658
|
+
} catch {
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
try {
|
|
2662
|
+
const parsed = JSON.parse(text);
|
|
2663
|
+
if (typeof parsed.cookies !== "object" || parsed.cookies === null) return void 0;
|
|
2664
|
+
const cookies = {};
|
|
2665
|
+
for (const [name, value] of Object.entries(parsed.cookies)) if (typeof value === "string") cookies[name] = value;
|
|
2666
|
+
if (typeof cookies["sessionid"] !== "string" || cookies["sessionid"] === "") return void 0;
|
|
2667
|
+
return {
|
|
2668
|
+
cookies,
|
|
2669
|
+
userAgent: typeof parsed.userAgent === "string" && parsed.userAgent !== "" ? parsed.userAgent : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 SamanthaDoubao/2.31.4",
|
|
2670
|
+
savedAt: typeof parsed.savedAt === "string" ? parsed.savedAt : (/* @__PURE__ */ new Date(0)).toISOString()
|
|
2671
|
+
};
|
|
2672
|
+
} catch {
|
|
2673
|
+
return;
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
/** Write the session atomically, readable only by its owner. */
|
|
2677
|
+
async function writeStoredSession(session) {
|
|
2678
|
+
const target = doubaoSessionPath();
|
|
2679
|
+
await mkdir(dirname(target), { recursive: true });
|
|
2680
|
+
const temporary = `${target}.tmp`;
|
|
2681
|
+
await writeFile(temporary, JSON.stringify(session, null, 2), {
|
|
2682
|
+
encoding: "utf8",
|
|
2683
|
+
mode: 384
|
|
2684
|
+
});
|
|
2685
|
+
await rename(temporary, target);
|
|
2686
|
+
}
|
|
2687
|
+
/** Remove the stored session. */
|
|
2688
|
+
async function removeStoredSession() {
|
|
2689
|
+
try {
|
|
2690
|
+
await unlink(doubaoSessionPath());
|
|
2691
|
+
} catch {}
|
|
2692
|
+
}
|
|
2693
|
+
//#endregion
|
|
27
2694
|
//#region src/badges.ts
|
|
28
2695
|
/**
|
|
29
2696
|
* Promotion badges the upstream attaches to a model.
|
|
@@ -2303,243 +4970,10 @@ var WorkBuddyUpstreamClient = class {
|
|
|
2303
4970
|
};
|
|
2304
4971
|
return {
|
|
2305
4972
|
credit: typeof data["credit"] === "number" ? data["credit"] : 0,
|
|
2306
|
-
energy: typeof data["energy"] === "number" ? data["energy"] : 0
|
|
2307
|
-
};
|
|
2308
|
-
}
|
|
2309
|
-
};
|
|
2310
|
-
//#endregion
|
|
2311
|
-
//#region src/file-perms.ts
|
|
2312
|
-
/**
|
|
2313
|
-
* Write a file that holds credentials, without leaving it world-readable.
|
|
2314
|
-
*
|
|
2315
|
-
* Every credential this plugin keeps on disk — the durable account list, the
|
|
2316
|
-
* ignore list, any mirrored balance — travelled through a plain `writeFile` with
|
|
2317
|
-
* the process umask as the only protection. On a POSIX host that typically means
|
|
2318
|
-
* `0644`: readable by every other user on the machine, and these files carry
|
|
2319
|
-
* `accessToken` / `refreshToken` verbatim.
|
|
2320
|
-
*
|
|
2321
|
-
* Two rules, and the order matters:
|
|
2322
|
-
*
|
|
2323
|
-
* 1. **Create, don't patch.** `mode` on `writeFile` only applies when the file is
|
|
2324
|
-
* created. The atomic-write pattern already writes a fresh temp file and
|
|
2325
|
-
* renames it over the target, so the temp is created with `0600` and the
|
|
2326
|
-
* rename carries that permission to the destination. Chmod'ing afterwards
|
|
2327
|
-
* would also work but leaves a window where the file exists with the old
|
|
2328
|
-
* mode.
|
|
2329
|
-
* 2. **Still chmod best-effort.** A file written by an older version already
|
|
2330
|
-
* exists with `0644`; the rename replaces the inode, so rule 1 covers it —
|
|
2331
|
-
* but a host that keeps the target in place (or a future caller that writes
|
|
2332
|
-
* directly) would not be covered, and `chmod` is cheap.
|
|
2333
|
-
*
|
|
2334
|
-
* WINDOWS: `mode` is ignored by Node on win32, and there is no ACL equivalent in
|
|
2335
|
-
* the standard library. The honest statement is what actually protects these
|
|
2336
|
-
* files there: they live under the user's own profile (%USERPROFILE%, %LOCALAPPDATA%),
|
|
2337
|
-
* whose inherited ACL excludes other standard users by default. Calling `icacls`
|
|
2338
|
-
* per write would spawn a process on every balance update to re-apply a
|
|
2339
|
-
* protection the parent directory already provides, so this module does not. A
|
|
2340
|
-
* profile relocated to a shared directory is outside what this code can detect —
|
|
2341
|
-
* the README says where the files live so the user can check.
|
|
2342
|
-
*
|
|
2343
|
-
* @module dsh-xdpool/file-perms
|
|
2344
|
-
*/
|
|
2345
|
-
/** Owner-only, for a file that holds a secret. */
|
|
2346
|
-
const SECRET_FILE_MODE = 384;
|
|
2347
|
-
/** Owner-only, for the directory that holds them. */
|
|
2348
|
-
const SECRET_DIR_MODE = 448;
|
|
2349
|
-
/**
|
|
2350
|
-
* True on a platform where POSIX modes are meaningful.
|
|
2351
|
-
*
|
|
2352
|
-
* Computed through a `typeof process` guard rather than read straight off the
|
|
2353
|
-
* global: this module is host-only in intent, but `store.ts` imports it and the
|
|
2354
|
-
* browser bundle imports `store.ts` for its row types, so the module body DOES
|
|
2355
|
-
* get bundled for the browser. A bare `process.platform` there throws
|
|
2356
|
-
* `ReferenceError: process is not defined` at first render — and it is the kind
|
|
2357
|
-
* of failure that only shows up in the packaged app.
|
|
2358
|
-
*/
|
|
2359
|
-
const POSIX = typeof process === "undefined" ? false : process.platform !== "win32";
|
|
2360
|
-
/**
|
|
2361
|
-
* Create the directory a secret lives in, owner-only.
|
|
2362
|
-
*
|
|
2363
|
-
* `recursive` so a fresh install works, and the mode applies to every directory
|
|
2364
|
-
* this call creates. An existing directory keeps its mode — `mkdir` does not
|
|
2365
|
-
* change what is already there — so `chmod` runs too, best-effort: tightening a
|
|
2366
|
-
* directory that a previous version created permissively is exactly the case
|
|
2367
|
-
* worth fixing, and a failure is not worth aborting a save over.
|
|
2368
|
-
*/
|
|
2369
|
-
async function ensureSecretDir(dir) {
|
|
2370
|
-
await mkdir(dir, {
|
|
2371
|
-
recursive: true,
|
|
2372
|
-
...POSIX ? { mode: SECRET_DIR_MODE } : {}
|
|
2373
|
-
});
|
|
2374
|
-
if (!POSIX) return;
|
|
2375
|
-
try {
|
|
2376
|
-
await chmod(dir, SECRET_DIR_MODE);
|
|
2377
|
-
} catch {}
|
|
2378
|
-
}
|
|
2379
|
-
/**
|
|
2380
|
-
* Write `contents` to `path` with owner-only permissions.
|
|
2381
|
-
*
|
|
2382
|
-
* Not atomic on its own — callers that need the crash-safe temp+rename dance keep
|
|
2383
|
-
* doing it and just route the temp write through here, which is why the mode is
|
|
2384
|
-
* applied at creation: the rename then carries it to the final file.
|
|
2385
|
-
*/
|
|
2386
|
-
async function writeSecretFile(path, contents) {
|
|
2387
|
-
await writeFile(path, contents, POSIX ? {
|
|
2388
|
-
encoding: "utf8",
|
|
2389
|
-
mode: SECRET_FILE_MODE
|
|
2390
|
-
} : "utf8");
|
|
2391
|
-
if (!POSIX) return;
|
|
2392
|
-
try {
|
|
2393
|
-
await chmod(path, SECRET_FILE_MODE);
|
|
2394
|
-
} catch {}
|
|
2395
|
-
}
|
|
2396
|
-
//#endregion
|
|
2397
|
-
//#region src/ignored.ts
|
|
2398
|
-
/**
|
|
2399
|
-
* The permanent ignore list: accounts the user has thrown out of the pool.
|
|
2400
|
-
*
|
|
2401
|
-
* Distinct from `disabledAccountIds`, which is a ROTATION preference. A disabled
|
|
2402
|
-
* account stays on the card, can be switched back on, and its credential keeps
|
|
2403
|
-
* being read on every scan. Ignoring is a statement about the ACCOUNT — "this
|
|
2404
|
-
* one is not mine any more" — so an ignored account is skipped BEFORE its
|
|
2405
|
-
* credential is decrypted, never appears among the pool's accounts, and does not
|
|
2406
|
-
* come back when the desktop app writes a fresh `.info` file for it.
|
|
2407
|
-
*
|
|
2408
|
-
* It lives in a plugin-owned file rather than in the settings document for one
|
|
2409
|
-
* practical reason: the CLI has no settings service. `dsh-xdpool
|
|
2410
|
-
* ignore <id>` runs without a host, so a settings-only list could be written by
|
|
2411
|
-
* the card and never by the CLI. One file, read by both halves, keeps the two
|
|
2412
|
-
* views of "which accounts are ignored" identical by construction.
|
|
2413
|
-
*
|
|
2414
|
-
* @module dsh-xdpool/ignored
|
|
2415
|
-
*/
|
|
2416
|
-
/** Directory holding this plugin's own state (imported snapshots, ignore list). */
|
|
2417
|
-
const PLUGIN_DATA_DIR_NAME = ".xdpool";
|
|
2418
|
-
/** File holding the permanent ignore list, inside {@link pluginDataDir}. */
|
|
2419
|
-
const IGNORED_FILE_NAME = "ignored.json";
|
|
2420
|
-
/**
|
|
2421
|
-
* The DSH home directory, honouring the same override the host uses.
|
|
2422
|
-
*
|
|
2423
|
-
* Shared by the CLI and the host so both halves resolve the same file: an
|
|
2424
|
-
* `ignore` written from the terminal has to be visible to the running plugin,
|
|
2425
|
-
* which is only true if they agree on where "home" is.
|
|
2426
|
-
*/
|
|
2427
|
-
function dshHome(env = process.env) {
|
|
2428
|
-
const fromEnv = env["DSH_HOME"];
|
|
2429
|
-
if (typeof fromEnv === "string" && fromEnv.trim() !== "") return fromEnv.trim();
|
|
2430
|
-
return join(homedir(), ".dsh");
|
|
2431
|
-
}
|
|
2432
|
-
/** This plugin's own state directory. */
|
|
2433
|
-
function pluginDataDir(env = process.env) {
|
|
2434
|
-
return join(dshHome(env), PLUGIN_DATA_DIR_NAME);
|
|
2435
|
-
}
|
|
2436
|
-
/** Absolute path of the ignore list. */
|
|
2437
|
-
function ignoredIdsPath(env = process.env) {
|
|
2438
|
-
return join(pluginDataDir(env), IGNORED_FILE_NAME);
|
|
2439
|
-
}
|
|
2440
|
-
/**
|
|
2441
|
-
* Normalize whatever the file holds into a clean list.
|
|
2442
|
-
*
|
|
2443
|
-
* Tolerant on purpose: this file is hand-editable and a malformed entry must not
|
|
2444
|
-
* take the pool down. An entry without a usable id is dropped; a missing label
|
|
2445
|
-
* falls back to the id so the card always has something to print.
|
|
2446
|
-
*/
|
|
2447
|
-
function normalize$1(raw) {
|
|
2448
|
-
if (typeof raw !== "object" || raw === null) return [];
|
|
2449
|
-
const entries = raw.accounts;
|
|
2450
|
-
if (!Array.isArray(entries)) return [];
|
|
2451
|
-
const out = [];
|
|
2452
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2453
|
-
for (const entry of entries) {
|
|
2454
|
-
if (typeof entry !== "object" || entry === null) continue;
|
|
2455
|
-
const record = entry;
|
|
2456
|
-
const id = typeof record["id"] === "string" ? record["id"].trim() : "";
|
|
2457
|
-
if (id === "" || seen.has(id)) continue;
|
|
2458
|
-
seen.add(id);
|
|
2459
|
-
const label = typeof record["label"] === "string" && record["label"].trim() !== "" ? record["label"] : id;
|
|
2460
|
-
const ignoredAt = typeof record["ignoredAt"] === "string" ? record["ignoredAt"] : "";
|
|
2461
|
-
out.push({
|
|
2462
|
-
id,
|
|
2463
|
-
label,
|
|
2464
|
-
ignoredAt
|
|
2465
|
-
});
|
|
2466
|
-
}
|
|
2467
|
-
return out;
|
|
2468
|
-
}
|
|
2469
|
-
/**
|
|
2470
|
-
* Read the ignore list, tolerating every "no list yet" shape.
|
|
2471
|
-
*
|
|
2472
|
-
* A missing file, unreadable file, or invalid JSON all mean the same thing to
|
|
2473
|
-
* the caller — nothing is ignored — so none of them throws. The pool must be
|
|
2474
|
-
* able to start on a machine that has never ignored anything.
|
|
2475
|
-
*/
|
|
2476
|
-
async function readIgnoredAccounts(path = ignoredIdsPath()) {
|
|
2477
|
-
try {
|
|
2478
|
-
return normalize$1(JSON.parse(await readFile(path, "utf8")));
|
|
2479
|
-
} catch {
|
|
2480
|
-
return [];
|
|
2481
|
-
}
|
|
2482
|
-
}
|
|
2483
|
-
/**
|
|
2484
|
-
* Synchronous read, for startup.
|
|
2485
|
-
*
|
|
2486
|
-
* The host applies the ignore list from inside `apply()`, which is synchronous,
|
|
2487
|
-
* and doing it there removes a startup race: an async load could resolve AFTER
|
|
2488
|
-
* the first account scan, which would let an ignored account slip into the pool
|
|
2489
|
-
* once per boot. The file is a few hundred bytes, so a blocking read at startup
|
|
2490
|
-
* costs nothing measurable.
|
|
2491
|
-
*/
|
|
2492
|
-
function readIgnoredAccountsSync(path = ignoredIdsPath()) {
|
|
2493
|
-
try {
|
|
2494
|
-
return normalize$1(JSON.parse(readFileSync(path, "utf8")));
|
|
2495
|
-
} catch {
|
|
2496
|
-
return [];
|
|
2497
|
-
}
|
|
2498
|
-
}
|
|
2499
|
-
/**
|
|
2500
|
-
* Replace the ignore list, atomically.
|
|
2501
|
-
*
|
|
2502
|
-
* Written to a sibling temp file and renamed over the target so a crash (or a
|
|
2503
|
-
* concurrent reader) can never observe a half-written document — the ignore
|
|
2504
|
-
* list is the only thing standing between a dead account and the rotation, and
|
|
2505
|
-
* a truncated file reads as "nothing is ignored", which would quietly put every
|
|
2506
|
-
* discarded account back in the pool.
|
|
2507
|
-
*/
|
|
2508
|
-
async function writeIgnoredAccounts(accounts, path = ignoredIdsPath()) {
|
|
2509
|
-
const payload = JSON.stringify({
|
|
2510
|
-
version: 1,
|
|
2511
|
-
accounts
|
|
2512
|
-
}, null, 2);
|
|
2513
|
-
await ensureSecretDir(dirname(path));
|
|
2514
|
-
const temp = `${path}.tmp`;
|
|
2515
|
-
await writeSecretFile(temp, `${payload}\n`);
|
|
2516
|
-
await rename(temp, path);
|
|
2517
|
-
}
|
|
2518
|
-
/**
|
|
2519
|
-
* Add one account to the ignore list, preserving the rest.
|
|
2520
|
-
*
|
|
2521
|
-
* A read-modify-write rather than a wholesale replace: the card and the CLI can
|
|
2522
|
-
* both be open, and each request names exactly one account, so re-writing the
|
|
2523
|
-
* whole list from a stale view would drop the other side's edits.
|
|
2524
|
-
*/
|
|
2525
|
-
async function ignoreAccount(account, path = ignoredIdsPath()) {
|
|
2526
|
-
const current = await readIgnoredAccounts(path);
|
|
2527
|
-
if (current.some((entry) => entry.id === account.id)) return current;
|
|
2528
|
-
const next = [...current, {
|
|
2529
|
-
id: account.id,
|
|
2530
|
-
label: account.label ?? account.id,
|
|
2531
|
-
ignoredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2532
|
-
}];
|
|
2533
|
-
await writeIgnoredAccounts(next, path);
|
|
2534
|
-
return next;
|
|
2535
|
-
}
|
|
2536
|
-
/** Drop one account from the ignore list. Returns the resulting list. */
|
|
2537
|
-
async function unignoreAccount(accountId, path = ignoredIdsPath()) {
|
|
2538
|
-
const current = await readIgnoredAccounts(path);
|
|
2539
|
-
const next = current.filter((entry) => entry.id !== accountId);
|
|
2540
|
-
if (next.length !== current.length) await writeIgnoredAccounts(next, path);
|
|
2541
|
-
return next;
|
|
2542
|
-
}
|
|
4973
|
+
energy: typeof data["energy"] === "number" ? data["energy"] : 0
|
|
4974
|
+
};
|
|
4975
|
+
}
|
|
4976
|
+
};
|
|
2543
4977
|
//#endregion
|
|
2544
4978
|
//#region src/account-store.ts
|
|
2545
4979
|
/**
|
|
@@ -5484,282 +7918,53 @@ var WorkBuddyCatalog = class {
|
|
|
5484
7918
|
}
|
|
5485
7919
|
find(id) {
|
|
5486
7920
|
return this.models.find((model) => model.id === id);
|
|
5487
|
-
}
|
|
5488
|
-
/** Replace the catalog from the live upstream list; keeps the fallback if empty. */
|
|
5489
|
-
updateFromUpstream(models) {
|
|
5490
|
-
this.update(catalogFromUpstream(models, this.region));
|
|
5491
|
-
this.source = "live";
|
|
5492
|
-
this.lastUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
5493
|
-
this.lastError = void 0;
|
|
5494
|
-
}
|
|
5495
|
-
/**
|
|
5496
|
-
* Record that a fetch attempt failed, leaving the current list in place.
|
|
5497
|
-
*
|
|
5498
|
-
* The list is deliberately NOT reset here: a refresh that fails should keep
|
|
5499
|
-
* whatever working catalog is already loaded, rather than demoting a healthy
|
|
5500
|
-
* session to the static table because one retry ran out.
|
|
5501
|
-
*/
|
|
5502
|
-
noteFetchFailure(message) {
|
|
5503
|
-
this.lastError = message;
|
|
5504
|
-
this.notify();
|
|
5505
|
-
}
|
|
5506
|
-
notify() {
|
|
5507
|
-
for (const listener of this.listeners) listener();
|
|
5508
|
-
}
|
|
5509
|
-
};
|
|
5510
|
-
/** Convert one upstream catalog entry into the plugin's model-info shape. */
|
|
5511
|
-
function toModelInfo(model) {
|
|
5512
|
-
return {
|
|
5513
|
-
id: model.id,
|
|
5514
|
-
name: model.name,
|
|
5515
|
-
contextWindow: model.contextWindow,
|
|
5516
|
-
maxOutputTokens: model.maxTokens,
|
|
5517
|
-
supportsImages: model.supportsImages ?? false,
|
|
5518
|
-
...model.creditMultiplier === void 0 ? {} : { multiplier: model.creditMultiplier },
|
|
5519
|
-
...model.reasoning?.supportedEfforts === void 0 ? {} : { supportedEfforts: model.reasoning.supportedEfforts },
|
|
5520
|
-
...model.tags === void 0 || model.tags.length === 0 ? {} : { tags: model.tags }
|
|
5521
|
-
};
|
|
5522
|
-
}
|
|
5523
|
-
/**
|
|
5524
|
-
* Map the live upstream list, falling back to the static list when empty.
|
|
5525
|
-
*
|
|
5526
|
-
* `region` only chooses WHICH static table an empty list falls back to. A
|
|
5527
|
-
* non-empty list is the gateway's own answer for whichever gateway was asked,
|
|
5528
|
-
* so there is nothing region-specific left to apply to it.
|
|
5529
|
-
*/
|
|
5530
|
-
function catalogFromUpstream(models, region = "cn") {
|
|
5531
|
-
if (models.length === 0) return fallbackModelsFor(region);
|
|
5532
|
-
return models.map(toModelInfo);
|
|
5533
|
-
}
|
|
5534
|
-
//#endregion
|
|
5535
|
-
//#region src/status-paths.ts
|
|
5536
|
-
/**
|
|
5537
|
-
* Node-free constants and types shared by the Host and browser halves of the
|
|
5538
|
-
* XD Pool settings card.
|
|
5539
|
-
*
|
|
5540
|
-
* Pool's runtime state already lives in `src/status.ts` (`buildStatus` /
|
|
5541
|
-
* `WorkBuddyStatus`); this module only carves the cross-domain (Host→browser)
|
|
5542
|
-
* JSON document into a shape that stays token-free and matches what the
|
|
5543
|
-
* browser card renders. Route paths are plugin-owned and mounted on the Host's
|
|
5544
|
-
* same-origin web server (see `src/web-status.ts`).
|
|
5545
|
-
*
|
|
5546
|
-
* @module dsh-xdpool/status-paths
|
|
5547
|
-
*/
|
|
5548
|
-
/** Plugin-owned read-only pool status endpoint (account rows + models + shim). */
|
|
5549
|
-
const POOL_STATUS_PATH = "/plugins/dsh-xdpool/status";
|
|
5550
|
-
/** Plugin-owned local account rescan endpoint (re-read desktop snapshots). */
|
|
5551
|
-
const POOL_RESCAN_PATH = "/plugins/dsh-xdpool/accounts/rescan";
|
|
5552
|
-
/**
|
|
5553
|
-
* Re-fetch the upstream model catalog for both regions.
|
|
5554
|
-
*
|
|
5555
|
-
* Separate from {@link POOL_RESCAN_PATH} because they answer different
|
|
5556
|
-
* questions, and conflating them misled users: "detect accounts again" only
|
|
5557
|
-
* re-read the desktop snapshots, so it could NOT recover a model list that had
|
|
5558
|
-
* fallen back to the static table after a failed startup fetch. The only way
|
|
5559
|
-
* out was restarting DSH.
|
|
5560
|
-
*/
|
|
5561
|
-
const POOL_CATALOG_REFRESH_PATH = "/plugins/dsh-xdpool/models/refresh";
|
|
5562
|
-
/** Plugin-owned cooldown reset endpoint (clear all 429 cooldowns). */
|
|
5563
|
-
const POOL_RESET_COOLDOWN_PATH = "/plugins/dsh-xdpool/cooldowns/reset";
|
|
5564
|
-
/** Plugin-owned daily check-in action endpoint (claim today's reward). */
|
|
5565
|
-
const POOL_CHECKIN_PATH = "/plugins/dsh-xdpool/checkin";
|
|
5566
|
-
/** Plugin-owned model-selection save endpoint (writes the settings section). */
|
|
5567
|
-
const POOL_MODELS_SAVE_PATH = "/plugins/dsh-xdpool/models/save";
|
|
5568
|
-
/** Switch one account in or out of the pool (card toggle). */
|
|
5569
|
-
const POOL_ACCOUNT_DISABLE_PATH = "/plugins/dsh-xdpool/accounts/disabled";
|
|
5570
|
-
/**
|
|
5571
|
-
* Throw one account out of the pool for good, or take it back.
|
|
5572
|
-
*
|
|
5573
|
-
* Separate from the disable route because the semantics differ: disabling is a
|
|
5574
|
-
* rotation preference the account survives, ignoring survives the account.
|
|
5575
|
-
*/
|
|
5576
|
-
const POOL_ACCOUNT_IGNORE_PATH = "/plugins/dsh-xdpool/accounts/ignored";
|
|
5577
|
-
/** Run one automation job immediately, so the card can verify it on demand. */
|
|
5578
|
-
const POOL_AUTOMATION_RUN_PATH = "/plugins/dsh-xdpool/automation/run";
|
|
5579
|
-
/** Set or clear one account's reserved-credit floor. */
|
|
5580
|
-
const POOL_CREDIT_RESERVE_PATH = "/plugins/dsh-xdpool/accounts/credit-reserve";
|
|
5581
|
-
/**
|
|
5582
|
-
* Estimated credit spend, per channel and per model.
|
|
5583
|
-
*
|
|
5584
|
-
* Derived from the pack's own token ledger, never from a credit counter — the pack
|
|
5585
|
-
* records tokens, and the vendor's balance is only visible when it is read again. The
|
|
5586
|
-
* arithmetic (tokens ÷ 1e6 × the model's published multiplier) and the honesty about
|
|
5587
|
-
* its error live in `credits.ts`.
|
|
5588
|
-
*
|
|
5589
|
-
* `?days=N` limits the window; the ledger keeps 90 days.
|
|
5590
|
-
*/
|
|
5591
|
-
const POOL_CREDITS_SPEND_PATH = "/plugins/dsh-xdpool/credits/spend";
|
|
5592
|
-
/**
|
|
5593
|
-
* Name the account to try first, or hand the choice back to the strategy.
|
|
5594
|
-
*
|
|
5595
|
-
* A route rather than a settings write for the reason the ignore list is a file:
|
|
5596
|
-
* the CLI has no settings service, so a card-only settings key could be written
|
|
5597
|
-
* by the card and never by `dsh-xdpool prefer`. The route owns the
|
|
5598
|
-
* write, pushes it into the pool immediately so the very next request sees it,
|
|
5599
|
-
* and is the one path both halves share.
|
|
5600
|
-
*/
|
|
5601
|
-
const POOL_ACCOUNT_PREFER_PATH = "/plugins/dsh-xdpool/accounts/preferred";
|
|
5602
|
-
/**
|
|
5603
|
-
* Read the aggregate lane's state: every registry provider, its saved setting
|
|
5604
|
-
* (never its key), and whether it can serve anything right now.
|
|
5605
|
-
*
|
|
5606
|
-
* Separate from {@link POOL_STATUS_PATH} because it answers a different
|
|
5607
|
-
* question — "what can I configure" rather than "what is my pool doing" — and
|
|
5608
|
-
* because its payload is the WHOLE roster. Folding 76 provider records into the
|
|
5609
|
-
* status document would make every 30-second poll of the pool card carry a
|
|
5610
|
-
* directory nobody reads most of the time.
|
|
5611
|
-
*/
|
|
5612
|
-
const POOL_AGGREGATE_PATH = "/plugins/dsh-xdpool/aggregate";
|
|
5613
|
-
/**
|
|
5614
|
-
* Save one aggregate provider's setting: its key, its on/off switch, its base-URL
|
|
5615
|
-
* override, or the model ids a listing round discovered.
|
|
5616
|
-
*
|
|
5617
|
-
* POST only, and one provider per request — read-modify-write on the host side,
|
|
5618
|
-
* so two tabs editing two providers cannot clobber each other.
|
|
5619
|
-
*/
|
|
5620
|
-
const POOL_AGGREGATE_SAVE_PATH = "/plugins/dsh-xdpool/aggregate/save";
|
|
5621
|
-
/**
|
|
5622
|
-
* Verify one provider's key with a cheap non-generating call, and report what
|
|
5623
|
-
* its listing answered.
|
|
5624
|
-
*
|
|
5625
|
-
* Its own route because it is the only aggregate action that talks to the
|
|
5626
|
-
* network: a probe must never run as a side effect of saving a setting, or
|
|
5627
|
-
* "save" would silently spend the user's rate limit.
|
|
5628
|
-
*/
|
|
5629
|
-
const POOL_AGGREGATE_TEST_PATH = "/plugins/dsh-xdpool/aggregate/test";
|
|
5630
|
-
/**
|
|
5631
|
-
* Send one real streaming call to one model and report how it answered.
|
|
5632
|
-
*
|
|
5633
|
-
* Its own route, and POST-only, for the same reason the provider probe is: this
|
|
5634
|
-
* is the one action in the plugin that spends the user's credits, so it must
|
|
5635
|
-
* never be reachable by a prefetch, a GET, or any side effect of opening a
|
|
5636
|
-
* settings page. A GET here would let a browser — or anything else that can
|
|
5637
|
-
* reach a loopback port — fire unlimited billed calls by walking URLs.
|
|
5638
|
-
*
|
|
5639
|
-
* `provider` and `model` are resolved through the host's own adapter registry
|
|
5640
|
-
* rather than through this plugin's lanes, because that registry is the only
|
|
5641
|
-
* place that knows which credential and endpoint a given provider id serves.
|
|
5642
|
-
*/
|
|
5643
|
-
const POOL_MODEL_PROBE_PATH = "/plugins/dsh-xdpool/model/test";
|
|
5644
|
-
/**
|
|
5645
|
-
* POST-only: ask what models several login channels contribute right now.
|
|
5646
|
-
*
|
|
5647
|
-
* A route rather than more fields on {@link POOL_CHANNELS_PATH} because the
|
|
5648
|
-
* answer changes as accounts come and go while the roster does not, and the
|
|
5649
|
-
* login page polls only its own logins — folding live per-provider catalogues
|
|
5650
|
-
* into the roster document would either go stale the moment someone signed in,
|
|
5651
|
-
* or make every page refresh spend a round trip on thirteen providers.
|
|
5652
|
-
*
|
|
5653
|
-
* Read from the host rather than from the pack's own `model.list`, because the
|
|
5654
|
-
* pack keeps only `id`, `name` and two flags and throws away exactly the fields
|
|
5655
|
-
* this is for. The host's catalogue is the same one the model picker reads, so
|
|
5656
|
-
* the two agree by construction instead of by luck.
|
|
5657
|
-
*/
|
|
5658
|
-
const POOL_CHANNEL_MODELS_PATH = "/plugins/dsh-xdpool/channels/models";
|
|
5659
|
-
/**
|
|
5660
|
-
* Fetch one provider's live model list and write it back as its discovered set.
|
|
5661
|
-
*
|
|
5662
|
-
* Separate from the probe on purpose. The probe ANSWERS; this one COMMITS — it
|
|
5663
|
-
* changes what the provider contributes to the picker — so it is its own route
|
|
5664
|
-
* with its own confirmation, and a failed round keeps the previous roster.
|
|
5665
|
-
*/
|
|
5666
|
-
const POOL_AGGREGATE_DISCOVER_PATH = "/plugins/dsh-xdpool/aggregate/discover";
|
|
5667
|
-
/**
|
|
5668
|
-
* The thirteen login channels the vendored pack provides.
|
|
5669
|
-
*
|
|
5670
|
-
* Separate from the aggregate document for the same reason: the two lanes answer
|
|
5671
|
-
* different questions. The aggregate roster is "what can I point a key at", the
|
|
5672
|
-
* channel list is "what can I scan a QR code into", and mixing them in one poll
|
|
5673
|
-
* would put a third-party directory on the critical path of the pool card.
|
|
5674
|
-
*/
|
|
5675
|
-
const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
|
|
5676
|
-
/**
|
|
5677
|
-
* The `reason` the channel document carries when the login-channel route is
|
|
5678
|
-
* already owned by another plugin.
|
|
5679
|
-
*
|
|
5680
|
-
* The pack we vendor is byte-identical to the one the sibling login-channel
|
|
5681
|
-
* build mounts, and both claim the same fetch route; the host has no query for
|
|
5682
|
-
* what is already registered, so the loser of that race can only tell it lost.
|
|
5683
|
-
* Both halves need the same string — the host to say it, the card to choose
|
|
5684
|
-
* between "this host cannot run the channels" and "another plugin already runs
|
|
5685
|
-
* them", which are opposite sentences — so it is declared with the other wire
|
|
5686
|
-
* constants rather than in `channels.ts`, which the browser bundle may not
|
|
5687
|
-
* import for value.
|
|
5688
|
-
*/
|
|
5689
|
-
const ROUTE_OWNED_ELSEWHERE = "already-mounted-elsewhere";
|
|
5690
|
-
/**
|
|
5691
|
-
* The routing chains, and the whole model roster a member may name.
|
|
5692
|
-
*
|
|
5693
|
-
* One route for both because the editor cannot be drawn without the roster: a
|
|
5694
|
-
* member is chosen from a list, and a list of ids with no names, windows or
|
|
5695
|
-
* vendors is a list nobody can pick from. Reading two documents on one panel
|
|
5696
|
-
* open would also mean the roster could be a second older than the chains.
|
|
5697
|
-
*/
|
|
5698
|
-
const POOL_COMBOS_PATH = "/plugins/dsh-xdpool/combos";
|
|
5699
|
-
/**
|
|
5700
|
-
* Replace the whole chain list in one write.
|
|
5701
|
-
*
|
|
5702
|
-
* A single table replace rather than a per-chain patch: the editor's unit of
|
|
5703
|
-
* intent is "this is my routing table", and deleting one member is
|
|
5704
|
-
* indistinguishable from deleting that member's chain once ids are equal — so a
|
|
5705
|
-
* merge rule would have to guess, and a wrong guess silently resurrects a row the
|
|
5706
|
-
* user deleted.
|
|
5707
|
-
*/
|
|
5708
|
-
const POOL_COMBOS_SAVE_PATH = "/plugins/dsh-xdpool/combos/save";
|
|
5709
|
-
/**
|
|
5710
|
-
* The LAN relay's own state, and the only way to change it.
|
|
5711
|
-
*
|
|
5712
|
-
* One GET and one POST rather than a separate settings surface, because the relay
|
|
5713
|
-
* is a switch you have to be able to kill from the same card that turns it on —
|
|
5714
|
-
* a relay left listening on a network interface is the one failure here that
|
|
5715
|
-
* keeps mattering after the plugin is closed.
|
|
5716
|
-
*/
|
|
5717
|
-
const POOL_RELAY_PATH = "/plugins/dsh-xdpool/relay";
|
|
5718
|
-
/**
|
|
5719
|
-
* Read the usage panel's aggregate.
|
|
5720
|
-
*
|
|
5721
|
-
* GET only, and token-free by construction: the recorder holds counts and
|
|
5722
|
-
* timings, never a prompt. The document type is `UsageSummary` from
|
|
5723
|
-
* `src/stats.ts` rather than a copy declared here, because that module stays
|
|
5724
|
-
* Node-free precisely so the browser half can import the SAME declaration
|
|
5725
|
-
* instead of a second one that could quietly drift.
|
|
5726
|
-
*/
|
|
5727
|
-
const POOL_USAGE_PATH = "/plugins/dsh-xdpool/usage";
|
|
5728
|
-
/** The five strategies, as a value, so a request body can be validated against it. */
|
|
5729
|
-
const POOL_DISTRIBUTIONS = Object.freeze([
|
|
5730
|
-
"priority",
|
|
5731
|
-
"round-robin",
|
|
5732
|
-
"balanced",
|
|
5733
|
-
"sticky",
|
|
5734
|
-
"expiry"
|
|
5735
|
-
]);
|
|
5736
|
-
/** True when `value` names one of the five documented strategies. */
|
|
5737
|
-
function isDistributionStrategy(value) {
|
|
5738
|
-
return POOL_DISTRIBUTIONS.includes(value);
|
|
7921
|
+
}
|
|
7922
|
+
/** Replace the catalog from the live upstream list; keeps the fallback if empty. */
|
|
7923
|
+
updateFromUpstream(models) {
|
|
7924
|
+
this.update(catalogFromUpstream(models, this.region));
|
|
7925
|
+
this.source = "live";
|
|
7926
|
+
this.lastUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
7927
|
+
this.lastError = void 0;
|
|
7928
|
+
}
|
|
7929
|
+
/**
|
|
7930
|
+
* Record that a fetch attempt failed, leaving the current list in place.
|
|
7931
|
+
*
|
|
7932
|
+
* The list is deliberately NOT reset here: a refresh that fails should keep
|
|
7933
|
+
* whatever working catalog is already loaded, rather than demoting a healthy
|
|
7934
|
+
* session to the static table because one retry ran out.
|
|
7935
|
+
*/
|
|
7936
|
+
noteFetchFailure(message) {
|
|
7937
|
+
this.lastError = message;
|
|
7938
|
+
this.notify();
|
|
7939
|
+
}
|
|
7940
|
+
notify() {
|
|
7941
|
+
for (const listener of this.listeners) listener();
|
|
7942
|
+
}
|
|
7943
|
+
};
|
|
7944
|
+
/** Convert one upstream catalog entry into the plugin's model-info shape. */
|
|
7945
|
+
function toModelInfo(model) {
|
|
7946
|
+
return {
|
|
7947
|
+
id: model.id,
|
|
7948
|
+
name: model.name,
|
|
7949
|
+
contextWindow: model.contextWindow,
|
|
7950
|
+
maxOutputTokens: model.maxTokens,
|
|
7951
|
+
supportsImages: model.supportsImages ?? false,
|
|
7952
|
+
...model.creditMultiplier === void 0 ? {} : { multiplier: model.creditMultiplier },
|
|
7953
|
+
...model.reasoning?.supportedEfforts === void 0 ? {} : { supportedEfforts: model.reasoning.supportedEfforts },
|
|
7954
|
+
...model.tags === void 0 || model.tags.length === 0 ? {} : { tags: model.tags }
|
|
7955
|
+
};
|
|
5739
7956
|
}
|
|
5740
7957
|
/**
|
|
5741
|
-
*
|
|
5742
|
-
*
|
|
5743
|
-
* Shared by both halves on purpose. The host uses it when a configured hour
|
|
5744
|
-
* list arrives empty (the settings schema materializes "never configured" into
|
|
5745
|
-
* `[]`), and the card uses it when it writes the `automation` block back, so a
|
|
5746
|
-
* document that already holds an empty list is healed instead of being saved
|
|
5747
|
-
* back as an unrunnable schedule.
|
|
7958
|
+
* Map the live upstream list, falling back to the static list when empty.
|
|
5748
7959
|
*
|
|
5749
|
-
*
|
|
5750
|
-
*
|
|
5751
|
-
*
|
|
5752
|
-
* copies would drift, and the drift is invisible — the card would write a
|
|
5753
|
-
* schedule the scheduler does not run.
|
|
7960
|
+
* `region` only chooses WHICH static table an empty list falls back to. A
|
|
7961
|
+
* non-empty list is the gateway's own answer for whichever gateway was asked,
|
|
7962
|
+
* so there is nothing region-specific left to apply to it.
|
|
5754
7963
|
*/
|
|
5755
|
-
|
|
5756
|
-
|
|
5757
|
-
|
|
5758
|
-
|
|
5759
|
-
streak: [12],
|
|
5760
|
-
travel: [9, 21],
|
|
5761
|
-
compensation: [13]
|
|
5762
|
-
};
|
|
7964
|
+
function catalogFromUpstream(models, region = "cn") {
|
|
7965
|
+
if (models.length === 0) return fallbackModelsFor(region);
|
|
7966
|
+
return models.map(toModelInfo);
|
|
7967
|
+
}
|
|
5763
7968
|
//#endregion
|
|
5764
7969
|
//#region src/channels.ts
|
|
5765
7970
|
/**
|
|
@@ -5959,6 +8164,23 @@ const REGISTERED_CHANNELS = [
|
|
|
5959
8164
|
note: "个人 Google 账号的免费配额,走本地回调 OAuth",
|
|
5960
8165
|
login: "browser",
|
|
5961
8166
|
credits: { quota: true }
|
|
8167
|
+
},
|
|
8168
|
+
{
|
|
8169
|
+
id: "doubao",
|
|
8170
|
+
/**
|
|
8171
|
+
* Doubao, served by this plugin's own lane.
|
|
8172
|
+
*
|
|
8173
|
+
* Unlike every other row here, the pack has no Doubao adapter — the session, the
|
|
8174
|
+
* catalogue and the wire are all this plugin's. What makes it a channel anyway is the
|
|
8175
|
+
* login: one browser sign-in, then the models are in the picker like any other vendor's.
|
|
8176
|
+
*/
|
|
8177
|
+
name: "豆包",
|
|
8178
|
+
org: "字节跳动",
|
|
8179
|
+
domain: "www.doubao.com",
|
|
8180
|
+
accent: "#325AB4",
|
|
8181
|
+
note: "浏览器扫码登录一次;对话与「工作任务」模型、生图、活动赠送额度都在这里",
|
|
8182
|
+
login: "browser",
|
|
8183
|
+
credits: { quota: true }
|
|
5962
8184
|
}
|
|
5963
8185
|
];
|
|
5964
8186
|
/**
|
|
@@ -11177,6 +13399,20 @@ function flattenPlatforms(platforms) {
|
|
|
11177
13399
|
* owner is read from its shape (`workbuddy` for a bare id, the prefix otherwise)
|
|
11178
13400
|
* and groups come out in first-seen order — which is the order the members were
|
|
11179
13401
|
* in, so re-flattening reproduces exactly what was stored.
|
|
13402
|
+
*
|
|
13403
|
+
* ## A channel member's id is NOT `owner/model` (#141)
|
|
13404
|
+
*
|
|
13405
|
+
* A scan-login channel publishes members as `<channel>:<model>`, and the model id
|
|
13406
|
+
* may itself contain slashes (`cline:deepseek/deepseek-v4.1-flash-1017:batch`).
|
|
13407
|
+
* Splitting on the first `/` turns that into provider `cline` and model
|
|
13408
|
+
* `cline:deepseek/…`, so the editor showed a doubled prefix and the round-trip
|
|
13409
|
+
* write added one more (`trae/trae:deepseek-v4.1-flash`), at which point the
|
|
13410
|
+
* runtime could no longer match any member and the chain reported every one of
|
|
13411
|
+
* them missing.
|
|
13412
|
+
*
|
|
13413
|
+
* The colon is the discriminator: `<channel>:<model>` names a channel member as a
|
|
13414
|
+
* single token, while `<owner>/<model>` is how a third-party provider row is
|
|
13415
|
+
* written. Checked BEFORE the slash split so a channel id is never cut.
|
|
11180
13416
|
*/
|
|
11181
13417
|
function splitPlatforms(models) {
|
|
11182
13418
|
const groups = /* @__PURE__ */ new Map();
|
|
@@ -11184,9 +13420,15 @@ function splitPlatforms(models) {
|
|
|
11184
13420
|
for (const raw of models) {
|
|
11185
13421
|
const id = text$6(raw);
|
|
11186
13422
|
if (id === "") continue;
|
|
11187
|
-
|
|
11188
|
-
|
|
11189
|
-
|
|
13423
|
+
/**
|
|
13424
|
+
* `channel:model` — keep the whole thing as the model and file it under the
|
|
13425
|
+
* channel. `indexOf('/') === -1` is not required: the model half may contain
|
|
13426
|
+
* slashes, and the colon is what marks the shape.
|
|
13427
|
+
*/
|
|
13428
|
+
const channelMember = channelMemberOf(id);
|
|
13429
|
+
const parsed = channelMember === void 0 ? parseProviderModelId(id) : null;
|
|
13430
|
+
const owner = channelMember === void 0 ? parsed === null ? POOL_OWNER : parsed.providerId : channelMember.channel;
|
|
13431
|
+
const model = channelMember === void 0 ? parsed === null ? id : parsed.modelId : channelMember.model;
|
|
11190
13432
|
let bucket = groups.get(owner);
|
|
11191
13433
|
if (bucket === void 0) {
|
|
11192
13434
|
bucket = [];
|
|
@@ -11200,6 +13442,26 @@ function splitPlatforms(models) {
|
|
|
11200
13442
|
models: groups.get(owner) ?? []
|
|
11201
13443
|
}));
|
|
11202
13444
|
}
|
|
13445
|
+
/**
|
|
13446
|
+
* Read `<channel>:<model>` where the channel is a bare identifier.
|
|
13447
|
+
*
|
|
13448
|
+
* Returns undefined for anything else, so a provider-row id (`openai/gpt-4`) and a
|
|
13449
|
+
* bare pool id (`hy3`) both keep whatever handling they had. The channel half is
|
|
13450
|
+
* required to look like an identifier rather than a URL scheme: `https://…` has a
|
|
13451
|
+
* colon too, and treating that as a channel would file the row under `https`.
|
|
13452
|
+
*/
|
|
13453
|
+
function channelMemberOf(id) {
|
|
13454
|
+
const colon = id.indexOf(":");
|
|
13455
|
+
if (colon <= 0) return void 0;
|
|
13456
|
+
const channel = id.slice(0, colon);
|
|
13457
|
+
const model = id.slice(colon + 1);
|
|
13458
|
+
if (model === "") return void 0;
|
|
13459
|
+
if (!/^[A-Za-z0-9_-]+$/u.test(channel)) return void 0;
|
|
13460
|
+
return {
|
|
13461
|
+
channel,
|
|
13462
|
+
model
|
|
13463
|
+
};
|
|
13464
|
+
}
|
|
11203
13465
|
/** Windows assumed when nothing on the chain declares one. */
|
|
11204
13466
|
const COMBO_DEFAULT_CONTEXT_WINDOW = 131072;
|
|
11205
13467
|
/** Output ceiling assumed when nothing on the chain declares one. */
|
|
@@ -13629,7 +15891,35 @@ function createWorkBuddyAdapter(options) {
|
|
|
13629
15891
|
const baseUrl = `${shim.baseUrl()}/v1`;
|
|
13630
15892
|
if (extraRows !== void 0) return (extraRows() ?? []).map((row) => toExtraLaneModel(row, baseUrl, providerId));
|
|
13631
15893
|
if (aggregateCatalog) return [...catalog.providerRows().map((row) => toAggregateModel(row, baseUrl, providerId)), ...catalog.comboRows().map((row) => toComboModel(row, baseUrl, providerId))];
|
|
13632
|
-
|
|
15894
|
+
/**
|
|
15895
|
+
* EVERY model, with the user's selection applied where it is meaningful (#143).
|
|
15896
|
+
*
|
|
15897
|
+
* The card's tick-boxes narrow what the picker LISTS, and `visible()` is the right
|
|
15898
|
+
* answer for "what should be offered". It is the wrong answer for "what can this
|
|
15899
|
+
* provider serve": a user who types or picks a model by id — `kimi-k3.1-pro` in the
|
|
15900
|
+
* report — got `pi-ai provider "xdpool" has no configured model "kimi-k3.1-pro"`,
|
|
15901
|
+
* because that model was not in the four ticked boxes. The model existed, the account
|
|
15902
|
+
* could serve it, and the refusal came from a display filter.
|
|
15903
|
+
*
|
|
15904
|
+
* So the selection is applied as an ORDER and a per-model capability override, not as
|
|
15905
|
+
* a hard allow-list:
|
|
15906
|
+
*
|
|
15907
|
+
* - ticked models come first, in catalogue order (what the picker shows);
|
|
15908
|
+
* - unticked models follow, so an explicit id still resolves;
|
|
15909
|
+
* - the image flag and the context budget still come from `visible()`, because those
|
|
15910
|
+
* are the two settings where "the user said so" must win.
|
|
15911
|
+
*
|
|
15912
|
+
* `visible()` cannot express the ordering on its own — it returns a filtered list — so
|
|
15913
|
+
* the two are merged here, keyed by id, with the per-model overrides taken from the
|
|
15914
|
+
* visible row when it exists.
|
|
15915
|
+
*/
|
|
15916
|
+
const withSelection = () => {
|
|
15917
|
+
const shown = catalog.visible();
|
|
15918
|
+
const shownIds = new Set(shown.map((info) => info.id));
|
|
15919
|
+
const rest = catalog.current().filter((info) => !shownIds.has(info.id));
|
|
15920
|
+
return [...shown, ...rest].map((info) => toPiModel(info, baseUrl, providerId));
|
|
15921
|
+
};
|
|
15922
|
+
return withSelection();
|
|
13633
15923
|
};
|
|
13634
15924
|
/**
|
|
13635
15925
|
* Build a fresh provider object whose `models` array is the catalog as it
|
|
@@ -19668,8 +21958,231 @@ function bufferedFramesToCompletion(frames, modelId) {
|
|
|
19668
21958
|
return turnToCompletion(turn);
|
|
19669
21959
|
}
|
|
19670
21960
|
//#endregion
|
|
21961
|
+
//#region src/tool-schema.ts
|
|
21962
|
+
/**
|
|
21963
|
+
* Making a tool schema safe to send upstream.
|
|
21964
|
+
*
|
|
21965
|
+
* THE FAILURE
|
|
21966
|
+
*
|
|
21967
|
+
* `codearts: Invalid request: tools.function.parameters is not a valid moonshot flavored
|
|
21968
|
+
* json schema, details: <At path 'properties.show': detected infinite recursion without
|
|
21969
|
+
* termination condition>`
|
|
21970
|
+
*
|
|
21971
|
+
* A tool whose parameter schema refers to ITSELF has no finite JSON encoding. The upstream
|
|
21972
|
+
* validator walks the schema to check it can be materialised, and a self-reference sends it
|
|
21973
|
+
* into an endless descent — so the request is refused before the model ever sees it, and the
|
|
21974
|
+
* refusal names a path (`properties.show`) that the caller has no way to act on.
|
|
21975
|
+
*
|
|
21976
|
+
* HOW A CYCLE IS SPOTTED
|
|
21977
|
+
*
|
|
21978
|
+
* By PATH, and the path is tracked as the walk descends. A `$ref` is a JSON pointer into the
|
|
21979
|
+
* schema document, so `#/properties/show` names the node it sits in — and a reference whose
|
|
21980
|
+
* pointer resolves to a node that is an ANCESTOR of the reference itself is the loop.
|
|
21981
|
+
*
|
|
21982
|
+
* The ancestor test compares by IDENTITY: a cycle in one document is a reference to the same
|
|
21983
|
+
* object reached twice, not to an equal one.
|
|
21984
|
+
*
|
|
21985
|
+
* WHAT THIS DOES
|
|
21986
|
+
*
|
|
21987
|
+
* The recursion is cut where it starts: such a `$ref` is replaced with a permissive object.
|
|
21988
|
+
* The tool stays callable, and an upstream that cannot see the cycle cannot refuse the
|
|
21989
|
+
* request.
|
|
21990
|
+
*
|
|
21991
|
+
* @module dsh-xdpool/tool-schema
|
|
21992
|
+
*/
|
|
21993
|
+
/** The maximum depth a schema is walked to. Deep enough for real schemas, shallow enough to be cheap. */
|
|
21994
|
+
const MAX_DEPTH = 64;
|
|
21995
|
+
/**
|
|
21996
|
+
* Resolve a JSON pointer against the schema document.
|
|
21997
|
+
*
|
|
21998
|
+
* `#/properties/show` means "the `show` key of `properties`", and each segment is one level
|
|
21999
|
+
* down. A pointer that does not resolve is not a cycle — it is a reference to something this
|
|
22000
|
+
* document does not contain, which the upstream resolves against ITS OWN document.
|
|
22001
|
+
*/
|
|
22002
|
+
function resolvePointer(root, ref) {
|
|
22003
|
+
if (!ref.startsWith("#/")) return void 0;
|
|
22004
|
+
let current = root;
|
|
22005
|
+
for (const segment of ref.slice(2).split("/")) {
|
|
22006
|
+
if (current === null || typeof current !== "object") return void 0;
|
|
22007
|
+
const key = segment.replace(/~1/gu, "/").replace(/~0/gu, "~");
|
|
22008
|
+
current = current[key];
|
|
22009
|
+
if (current === void 0) return void 0;
|
|
22010
|
+
}
|
|
22011
|
+
return current;
|
|
22012
|
+
}
|
|
22013
|
+
/**
|
|
22014
|
+
* The node a `$ref` points at, together with the path it was found under.
|
|
22015
|
+
*
|
|
22016
|
+
* The path matters as much as the target: the loop in the reported failure is
|
|
22017
|
+
* `properties.show` referring to itself, so the reference and the node it names have to be
|
|
22018
|
+
* compared by WHERE they are, not only by what they contain.
|
|
22019
|
+
*/
|
|
22020
|
+
function referenceTarget(root, ref) {
|
|
22021
|
+
return resolvePointer(root, ref);
|
|
22022
|
+
}
|
|
22023
|
+
/**
|
|
22024
|
+
* Whether following references from one node reaches another.
|
|
22025
|
+
*
|
|
22026
|
+
* Containment is not enough: two properties that point at each other do not contain one
|
|
22027
|
+
* another — the connection IS the reference. So the walk follows references as well as
|
|
22028
|
+
* children, and stops at a node it has already visited, which is what makes a cycle
|
|
22029
|
+
* terminate instead of descending forever.
|
|
22030
|
+
*/
|
|
22031
|
+
function reachesNode(from, target, root, seen) {
|
|
22032
|
+
if (from === target) return true;
|
|
22033
|
+
if (from === null || typeof from !== "object") return false;
|
|
22034
|
+
if (seen.has(from)) return false;
|
|
22035
|
+
seen.add(from);
|
|
22036
|
+
if (Array.isArray(from)) return from.some((entry) => reachesNode(entry, target, root, seen));
|
|
22037
|
+
const record = from;
|
|
22038
|
+
const ref = record["$ref"];
|
|
22039
|
+
if (typeof ref === "string") {
|
|
22040
|
+
const resolved = resolvePointer(root, ref);
|
|
22041
|
+
if (resolved !== void 0 && reachesNode(resolved, target, root, seen)) return true;
|
|
22042
|
+
}
|
|
22043
|
+
return Object.values(record).some((value) => reachesNode(value, target, root, seen));
|
|
22044
|
+
}
|
|
22045
|
+
/**
|
|
22046
|
+
* Rewrite one schema node, cutting cycles.
|
|
22047
|
+
*
|
|
22048
|
+
* `root` is the document the pointers resolve against, and `ancestors` are the nodes on the
|
|
22049
|
+
* way here. A `$ref` that lands on one of them — or on the node itself — is the loop.
|
|
22050
|
+
*/
|
|
22051
|
+
function sanitizeNode(node, root, ancestors, depth) {
|
|
22052
|
+
if (depth > MAX_DEPTH) return {
|
|
22053
|
+
type: "object",
|
|
22054
|
+
additionalProperties: true
|
|
22055
|
+
};
|
|
22056
|
+
if (node === null || typeof node !== "object") return node;
|
|
22057
|
+
if (Array.isArray(node)) return node.map((entry) => sanitizeNode(entry, root, ancestors, depth + 1));
|
|
22058
|
+
const record = node;
|
|
22059
|
+
const ref = record["$ref"];
|
|
22060
|
+
if (typeof ref === "string") {
|
|
22061
|
+
const target = referenceTarget(root, ref);
|
|
22062
|
+
if (target !== void 0 && (target === node || reachesNode(target, node, root, /* @__PURE__ */ new Set())))
|
|
22063
|
+
/**
|
|
22064
|
+
* The cycle, cut.
|
|
22065
|
+
*
|
|
22066
|
+
* A permissive object is the honest description of "this is as deep as the schema
|
|
22067
|
+
* goes": the caller can pass anything there, and the model is told the shape is open
|
|
22068
|
+
* rather than being handed a lie about a finite one.
|
|
22069
|
+
*/
|
|
22070
|
+
return {
|
|
22071
|
+
type: "object",
|
|
22072
|
+
additionalProperties: true
|
|
22073
|
+
};
|
|
22074
|
+
/**
|
|
22075
|
+
* Every other reference is LEFT ALONE.
|
|
22076
|
+
*
|
|
22077
|
+
* Expanding it would inline the referenced schema and change its shape — and reuse is
|
|
22078
|
+
* not recursion: two properties pointing at the same definition are finite, and the
|
|
22079
|
+
* upstream accepts them. So a `$ref` is only ever replaced when it lands back on an
|
|
22080
|
+
* ancestor, and it is replaced with an open object rather than with the schema it
|
|
22081
|
+
* pointed at.
|
|
22082
|
+
*/
|
|
22083
|
+
return { ...record };
|
|
22084
|
+
}
|
|
22085
|
+
const out = {};
|
|
22086
|
+
for (const [key, value] of Object.entries(record)) out[key] = sanitizeNode(value, root, [...ancestors, node], depth + 1);
|
|
22087
|
+
return out;
|
|
22088
|
+
}
|
|
22089
|
+
/**
|
|
22090
|
+
* Make one tool definition safe to send.
|
|
22091
|
+
*
|
|
22092
|
+
* A definition without a schema is returned untouched: there is nothing to break, and a
|
|
22093
|
+
* tool the caller wrote badly in some other way is the caller's to fix.
|
|
22094
|
+
*/
|
|
22095
|
+
function sanitizeTool(tool) {
|
|
22096
|
+
if (tool === null || typeof tool !== "object") return tool;
|
|
22097
|
+
const record = tool;
|
|
22098
|
+
const fn = record["function"];
|
|
22099
|
+
if (fn !== null && typeof fn === "object") {
|
|
22100
|
+
const inner = fn;
|
|
22101
|
+
const parameters = inner["parameters"];
|
|
22102
|
+
if (parameters === null || typeof parameters !== "object") return tool;
|
|
22103
|
+
return {
|
|
22104
|
+
...record,
|
|
22105
|
+
function: {
|
|
22106
|
+
...inner,
|
|
22107
|
+
parameters: sanitizeNode(parameters, parameters, [], 0)
|
|
22108
|
+
}
|
|
22109
|
+
};
|
|
22110
|
+
}
|
|
22111
|
+
const parameters = record["parameters"];
|
|
22112
|
+
if (parameters === null || typeof parameters !== "object") return tool;
|
|
22113
|
+
return {
|
|
22114
|
+
...record,
|
|
22115
|
+
parameters: sanitizeNode(parameters, parameters, [], 0)
|
|
22116
|
+
};
|
|
22117
|
+
}
|
|
22118
|
+
/**
|
|
22119
|
+
* The tool list as it will be sent, with every recursive schema cut.
|
|
22120
|
+
*
|
|
22121
|
+
* The whole list is returned unchanged when nothing needed fixing, so a caller that sends
|
|
22122
|
+
* ordinary schemas gets exactly what it sent.
|
|
22123
|
+
*/
|
|
22124
|
+
function sanitizeToolSchemas(tools) {
|
|
22125
|
+
if (!Array.isArray(tools)) return tools;
|
|
22126
|
+
return tools.map((tool) => sanitizeTool(tool));
|
|
22127
|
+
}
|
|
22128
|
+
//#endregion
|
|
19671
22129
|
//#region src/channel-lane.ts
|
|
19672
22130
|
/**
|
|
22131
|
+
* The channel lane: 扫码登录 vendors served through the host's own LLM seam.
|
|
22132
|
+
*
|
|
22133
|
+
* ## Why this is a separate lane
|
|
22134
|
+
*
|
|
22135
|
+
* Every other lane reaches its upstream over HTTP this plugin owns: the pool
|
|
22136
|
+
* posts to WorkBuddy, the aggregate lane posts to a provider the user keyed, the
|
|
22137
|
+
* free lane posts to a pooled gateway. The login channels do not work that way.
|
|
22138
|
+
* `vendor/channel-pack` registers each one as a HOST adapter
|
|
22139
|
+
* (`llm.registerAdapter([product.id], adapter)`) — the credential, the wire
|
|
22140
|
+
* dialect and the endpoint all belong to the pack, and there is no
|
|
22141
|
+
* OpenAI-compatible port for a client to point at.
|
|
22142
|
+
*
|
|
22143
|
+
* So this lane opens no socket. It calls `ctx.llm`, which already knows how to
|
|
22144
|
+
* reach every registered provider, and translates between the two vocabularies.
|
|
22145
|
+
* The listing is built the same way, from `llm.listModels`, which is what the
|
|
22146
|
+
* card's own model list already calls: a channel that is not signed in throws,
|
|
22147
|
+
* the throw becomes "contributes nothing", and the gateway therefore cannot
|
|
22148
|
+
* advertise a channel the card would not show.
|
|
22149
|
+
*
|
|
22150
|
+
* ## What is translated
|
|
22151
|
+
*
|
|
22152
|
+
* The host stream vocabulary is `block-start | text-delta | reasoning-delta |
|
|
22153
|
+
* tool-call-delta | block-end | usage | finish` (dsh-llm `types.d.ts`), and each
|
|
22154
|
+
* of the four that carry content has an OpenAI spelling, so nothing is dropped on
|
|
22155
|
+
* the way out — including tool calls, which a gateway that silently swallowed
|
|
22156
|
+
* them would make look like a model that refuses to use tools.
|
|
22157
|
+
*
|
|
22158
|
+
* On the way in, every message becomes the host's `content: ContentBlock[]`;
|
|
22159
|
+
* a bare string is rejected by the host's own validation, which is the exact bug
|
|
22160
|
+
* fixed in `model-probe.ts`, so this lane does not repeat it.
|
|
22161
|
+
*
|
|
22162
|
+
* Images must go through the host's durable attachment store, for the same
|
|
22163
|
+
* reason: the typed `ImageBlock` (dsh-llm `types.d.ts`) has no `url` field at
|
|
22164
|
+
* all — only `attachment: ImageAttachmentRef`. A base64 `image_url` part is
|
|
22165
|
+
* therefore decoded and handed to `attachments.saveImage`, and the reference that
|
|
22166
|
+
* comes back is what goes into the block. Emitting `{ type: 'image', url }` is
|
|
22167
|
+
* the failure mode this note exists for: the host does not reject it, it simply
|
|
22168
|
+
* is not an image as far as the host is concerned, so the picture is dropped and
|
|
22169
|
+
* the model narrates the text alone — a solid red square came back described as
|
|
22170
|
+
* white, with a token count that proved nothing had arrived. A remote `http(s)`
|
|
22171
|
+
* URL is refused rather than fetched, matching the pack's own bridge, so the
|
|
22172
|
+
* gateway never becomes a fetch primitive on someone else's behalf.
|
|
22173
|
+
*
|
|
22174
|
+
* ## One deliberate difference from the pool lane
|
|
22175
|
+
*
|
|
22176
|
+
* The pool forces `stream: true` (`prepareChatBody`), so a client asking for a
|
|
22177
|
+
* non-streaming completion still receives SSE from it. This lane honours
|
|
22178
|
+
* `stream: false`. Copying the deviation would make the gateway's behaviour
|
|
22179
|
+
* depend on which lane a model happens to sit in — the kind of difference a
|
|
22180
|
+
* client cannot see coming and discovers as a parse error.
|
|
22181
|
+
*
|
|
22182
|
+
* @module dsh-xdpool/channel-lane
|
|
22183
|
+
*/
|
|
22184
|
+
/** The slice of the host's `llm` service this lane needs. */
|
|
22185
|
+
/**
|
|
19673
22186
|
* A request this lane will not serve as written, and that is the caller's to fix.
|
|
19674
22187
|
*
|
|
19675
22188
|
* Kept as its own type so the route can answer 400 for it: a refused image and a
|
|
@@ -19914,7 +22427,15 @@ async function* runTurn(input) {
|
|
|
19914
22427
|
if (system.length > 0) options.system = system[0].content;
|
|
19915
22428
|
if (typeof body.max_tokens === "number") options.maxTokens = body.max_tokens;
|
|
19916
22429
|
if (typeof body.temperature === "number") options.temperature = body.temperature;
|
|
19917
|
-
|
|
22430
|
+
/**
|
|
22431
|
+
* The tool schemas go out cut of their own cycles.
|
|
22432
|
+
*
|
|
22433
|
+
* They arrive from the calling agent, and a tool whose parameters refer to themselves have
|
|
22434
|
+
* no finite JSON encoding — the upstream validator walks them and never terminates, so the
|
|
22435
|
+
* request is refused with a path (`properties.show`) the caller cannot act on. Cutting the
|
|
22436
|
+
* cycle here keeps the tool callable and the request sendable.
|
|
22437
|
+
*/
|
|
22438
|
+
if (Array.isArray(body.tools) && body.tools.length > 0) options.tools = sanitizeToolSchemas(body.tools);
|
|
19918
22439
|
for await (const chunk of llm.stream(options)) {
|
|
19919
22440
|
const event = toChannelEvent(chunk);
|
|
19920
22441
|
if (event !== void 0) yield event;
|
|
@@ -23374,8 +25895,62 @@ function apply(ctx, config = {}) {
|
|
|
23374
25895
|
* would offer the same models twice under two routes — and `buddy:` is already
|
|
23375
25896
|
* the prefix the pool lane's own rows carry.
|
|
23376
25897
|
*/
|
|
25898
|
+
/**
|
|
25899
|
+
* The llm face the channel lane talks to, with Doubao served from here.
|
|
25900
|
+
*
|
|
25901
|
+
* `ctx.llm` owns every pack channel; Doubao has no pack adapter, so the two methods the
|
|
25902
|
+
* lane needs are answered by this plugin for `doubao` and handed straight through for
|
|
25903
|
+
* everything else. Composing rather than replacing keeps the host's registry authoritative
|
|
25904
|
+
* for the channels it owns, which is what lets a channel the pack adds later appear without
|
|
25905
|
+
* this file being touched.
|
|
25906
|
+
*/
|
|
25907
|
+
/**
|
|
25908
|
+
* The Doubao session, held in memory for the requests that read it.
|
|
25909
|
+
*
|
|
25910
|
+
* A module-scope-like holder rather than a local, because the lane and the routes are
|
|
25911
|
+
* registered once and must see the CURRENT session — which changes the moment a sign-in
|
|
25912
|
+
* lands. Restoring it from disk is what makes a restart keep the lane working.
|
|
25913
|
+
*/
|
|
25914
|
+
/**
|
|
25915
|
+
* The Doubao session.
|
|
25916
|
+
*
|
|
25917
|
+
* `undefined` until a sign-in lands or the stored one is restored. The lane reads it per
|
|
25918
|
+
* call, so a sign-in that happens after startup is visible on the next request without a
|
|
25919
|
+
* restart — and a rejection shows the "sign in again" sentence rather than an empty list.
|
|
25920
|
+
*/
|
|
25921
|
+
let doubaoSession;
|
|
25922
|
+
/** Point every reader at a session: the lane, and the upstream's own holder. */
|
|
25923
|
+
const adoptDoubaoSession = (session) => {
|
|
25924
|
+
doubaoSession = session;
|
|
25925
|
+
setDoubaoSession(session);
|
|
25926
|
+
};
|
|
25927
|
+
/**
|
|
25928
|
+
* Restore the session written by an earlier run.
|
|
25929
|
+
*
|
|
25930
|
+
* Deliberately at apply time and deliberately not awaited: the plugin must not block its
|
|
25931
|
+
* own start on a disk read, and a missing file is the ordinary "not signed in" state rather
|
|
25932
|
+
* than a failure. `adoptDoubaoSession` publishes it as soon as it arrives, which is before
|
|
25933
|
+
* any request can arrive.
|
|
25934
|
+
*/
|
|
25935
|
+
readStoredSession().then((stored) => {
|
|
25936
|
+
if (stored !== void 0) adoptDoubaoSession(stored);
|
|
25937
|
+
});
|
|
25938
|
+
const doubaoLlm = createDoubaoLlm({ session: () => doubaoSession });
|
|
25939
|
+
/** The ids Doubao's catalogue knows, so `stream` can tell its models from the host's. */
|
|
25940
|
+
const doubaoModelIds = new Set(DOUBAO_MODELS.map((model) => model.id));
|
|
25941
|
+
const hostLlm = ctx.llm;
|
|
23377
25942
|
const channelLane = createChannelLane({
|
|
23378
|
-
llm:
|
|
25943
|
+
llm: {
|
|
25944
|
+
listModels: async (provider) => provider === "doubao" ? doubaoLlm.listModels(provider) : hostLlm.listModels(provider),
|
|
25945
|
+
stream: (options) => (async function* () {
|
|
25946
|
+
const modelId = typeof options["model"] === "string" ? options["model"] : "";
|
|
25947
|
+
if (doubaoModelIds.has(modelId)) {
|
|
25948
|
+
yield* doubaoLlm.stream(options);
|
|
25949
|
+
return;
|
|
25950
|
+
}
|
|
25951
|
+
yield* hostLlm.stream(options);
|
|
25952
|
+
})()
|
|
25953
|
+
},
|
|
23379
25954
|
providers: () => REGISTERED_CHANNELS.map((channel) => channel.id).filter((id) => channelListableAsRows(id, POOL_OWNED_CHANNELS)),
|
|
23380
25955
|
toId: (channel, modelId) => `${channel}:${modelId}`,
|
|
23381
25956
|
attachments: () => ctx.get("attachments"),
|
|
@@ -23553,238 +26128,258 @@ function apply(ctx, config = {}) {
|
|
|
23553
26128
|
rateOf
|
|
23554
26129
|
});
|
|
23555
26130
|
};
|
|
23556
|
-
ctx.inject(["webServer"], (webCtx) =>
|
|
23557
|
-
pool: core.pool,
|
|
23558
|
-
catalogs: core.catalogs,
|
|
23559
|
-
client: core.client,
|
|
23560
|
-
usage: () => usageRecorder.summary(),
|
|
23561
|
-
shim: () => shimInfo("cn"),
|
|
23562
|
-
scheduler: () => core.scheduler.status(),
|
|
23563
|
-
runAutomation: (_job, _force) => core.scheduler.startRunAll(),
|
|
23564
|
-
saveSelection: async (region, selection) => {
|
|
23565
|
-
const payload = {
|
|
23566
|
-
...selection.enabledModelIds === void 0 ? {} : { enabledModelIds: [...selection.enabledModelIds] },
|
|
23567
|
-
...selection.imageModelIds === void 0 ? {} : { imageModelIds: [...selection.imageModelIds] },
|
|
23568
|
-
...selection.contextBudgets === void 0 ? {} : { contextBudgets: { ...selection.contextBudgets } }
|
|
23569
|
-
};
|
|
23570
|
-
await setSetting(modelSelectionKeyFor(region), payload, payload);
|
|
23571
|
-
},
|
|
23572
|
-
setAccountDisabled: async (accountId, disabled) => {
|
|
23573
|
-
const currentIds = current().disabledAccountIds ?? [];
|
|
23574
|
-
const next = disabled ? currentIds.includes(accountId) ? currentIds : [...currentIds, accountId] : currentIds.filter((id) => id !== accountId);
|
|
23575
|
-
await setSetting("disabledAccountIds", next, next);
|
|
23576
|
-
},
|
|
23577
|
-
setCreditReserve: async (accountId, reserve) => {
|
|
23578
|
-
const next = creditReservesWith(current().creditReserves, accountId, reserve);
|
|
23579
|
-
await setSetting("creditReserves", next, next);
|
|
23580
|
-
},
|
|
23581
|
-
setAccountIgnored: async (accountId, ignored) => {
|
|
23582
|
-
if (ignored) {
|
|
23583
|
-
const known = core.pool.list().find((account) => account.id === accountId);
|
|
23584
|
-
await ignoreAccount({
|
|
23585
|
-
id: accountId,
|
|
23586
|
-
...known === void 0 ? {} : { label: known.label }
|
|
23587
|
-
}, ignoredPath);
|
|
23588
|
-
} else await unignoreAccount(accountId, ignoredPath);
|
|
23589
|
-
refreshIgnored();
|
|
23590
|
-
if (!ignored) await core.pool.scan();
|
|
23591
|
-
},
|
|
23592
|
-
ignoredAccounts: () => ignoredAccounts,
|
|
23593
|
-
setPreferredAccount: async (accountId) => {
|
|
23594
|
-
await writePreferredId(accountId ?? void 0, preferredPath);
|
|
23595
|
-
applyPreferred(accountId ?? void 0);
|
|
23596
|
-
},
|
|
23597
|
-
refreshCatalog: async () => {
|
|
23598
|
-
const result = await seedCatalog();
|
|
23599
|
-
invalidateCatalog();
|
|
23600
|
-
return result;
|
|
23601
|
-
},
|
|
23602
|
-
aggregateDocument: () => aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel)),
|
|
23603
|
-
saveAggregate: async (patch) => {
|
|
23604
|
-
if (patch.kind === "lane") await setAggregateEnabled(patch.enabled);
|
|
23605
|
-
else if (patch.kind === "clear") await clearProviderSetting(patch.providerId);
|
|
23606
|
-
else await updateProviderSetting(patch.providerId, {
|
|
23607
|
-
...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
|
|
23608
|
-
...patch.apiKey === void 0 ? {} : { apiKey: patch.apiKey },
|
|
23609
|
-
...patch.apiKeys === void 0 ? {} : { apiKeys: patch.apiKeys },
|
|
23610
|
-
...patch.appendApiKey === void 0 ? {} : { appendApiKey: patch.appendApiKey },
|
|
23611
|
-
...patch.distribution === void 0 ? {} : { distribution: patch.distribution },
|
|
23612
|
-
...patch.baseUrl === void 0 ? {} : { baseUrl: patch.baseUrl },
|
|
23613
|
-
...patch.models === void 0 ? {} : { models: patch.models }
|
|
23614
|
-
});
|
|
23615
|
-
await aggregateCatalog.refresh();
|
|
23616
|
-
return aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel));
|
|
23617
|
-
},
|
|
23618
|
-
probeAggregate: async (providerId) => {
|
|
23619
|
-
const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
|
|
23620
|
-
return {
|
|
23621
|
-
ok: probe.ok,
|
|
23622
|
-
status: probe.status,
|
|
23623
|
-
message: probe.message,
|
|
23624
|
-
...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
|
|
23625
|
-
...probe.modelIds === void 0 ? {} : { modelIds: probe.modelIds }
|
|
23626
|
-
};
|
|
23627
|
-
},
|
|
26131
|
+
ctx.inject(["webServer"], (webCtx) => {
|
|
23628
26132
|
/**
|
|
23629
|
-
*
|
|
23630
|
-
*
|
|
23631
|
-
* Routed through `ctx.llm.stream` rather than through any of this plugin's
|
|
23632
|
-
* own lanes, and that is the whole point: `ctx.llm` is the host's adapter
|
|
23633
|
-
* registry, so it resolves the provider/model pair to whichever credential
|
|
23634
|
-
* and endpoint actually serve it — including lanes this plugin knows nothing
|
|
23635
|
-
* about. Asking our own shims instead would make the button report on the
|
|
23636
|
-
* plumbing rather than on the model the user clicked.
|
|
23637
|
-
*
|
|
23638
|
-
* Never throws (see {@link probeModelConnectivity}): the measurement is the
|
|
23639
|
-
* answer, and a rejection here would show as a bare route failure that reads
|
|
23640
|
-
* like a wrong key.
|
|
23641
|
-
*/
|
|
23642
|
-
probeModel: async (provider, model, signal) => {
|
|
23643
|
-
return probeModelConnectivity(ctx.llm, provider, model, { signal });
|
|
23644
|
-
},
|
|
23645
|
-
/**
|
|
23646
|
-
* What each login channel contributes, read from the host's own catalogue.
|
|
23647
|
-
*
|
|
23648
|
-
* Not from the pack, on purpose. The pack's `model.list` keeps the id, the
|
|
23649
|
-
* name and two flags and drops the rest, and the rest is exactly what the
|
|
23650
|
-
* login page is asked to show. The host's `listModels` is also the same
|
|
23651
|
-
* catalogue the model picker builds from, so a row's window here is the
|
|
23652
|
-
* window the picker will enforce.
|
|
23653
|
-
*
|
|
23654
|
-
* `listModels` is a LISTING, though: the host's own answer carries only the
|
|
23655
|
-
* id, the name, a description and the input modalities, and the host drops
|
|
23656
|
-
* the context window out of it on the way out (its listing mapper keeps
|
|
23657
|
-
* four fields). The window lives one call deeper, on
|
|
23658
|
-
* `resolveModelInfo(provider, model)` — which is where the model picker and
|
|
23659
|
-
* the compaction planner read it from — so a second pass over each row is
|
|
23660
|
-
* the only way to show a context size that matches what will actually be
|
|
23661
|
-
* enforced.
|
|
23662
|
-
*
|
|
23663
|
-
* That second pass is bounded and per-row isolated: adapters resolve a model
|
|
23664
|
-
* from their own cache in the common case, a row that cannot be resolved
|
|
23665
|
-
* simply prints no window, and a channel's answer is never held up by one
|
|
23666
|
-
* model it could not describe.
|
|
26133
|
+
* Doubao's three routes.
|
|
23667
26134
|
*
|
|
23668
|
-
*
|
|
23669
|
-
*
|
|
23670
|
-
*
|
|
23671
|
-
* no way to tell which one they are looking at.
|
|
26135
|
+
* Its own lane, so its own endpoints: the sign-in harvests a cookie jar from a browser
|
|
26136
|
+
* this process starts, and the quota reads the windows the account holds. Neither is
|
|
26137
|
+
* something the pack can answer for a vendor it has no adapter for.
|
|
23672
26138
|
*/
|
|
23673
|
-
|
|
23674
|
-
|
|
23675
|
-
|
|
23676
|
-
|
|
23677
|
-
|
|
23678
|
-
|
|
23679
|
-
|
|
23680
|
-
|
|
23681
|
-
|
|
23682
|
-
|
|
23683
|
-
|
|
23684
|
-
|
|
23685
|
-
|
|
23686
|
-
|
|
23687
|
-
|
|
23688
|
-
|
|
23689
|
-
|
|
23690
|
-
|
|
23691
|
-
|
|
23692
|
-
|
|
23693
|
-
|
|
23694
|
-
|
|
23695
|
-
|
|
23696
|
-
|
|
23697
|
-
|
|
23698
|
-
|
|
23699
|
-
|
|
23700
|
-
|
|
23701
|
-
|
|
23702
|
-
|
|
23703
|
-
|
|
23704
|
-
|
|
26139
|
+
registerDoubaoRoutes(webCtx, {
|
|
26140
|
+
session: () => doubaoSession,
|
|
26141
|
+
save: (session) => {
|
|
26142
|
+
adoptDoubaoSession(session);
|
|
26143
|
+
writeStoredSession(session);
|
|
26144
|
+
},
|
|
26145
|
+
clear: () => {
|
|
26146
|
+
adoptDoubaoSession(void 0);
|
|
26147
|
+
removeStoredSession();
|
|
26148
|
+
}
|
|
26149
|
+
});
|
|
26150
|
+
return registerPoolStatusRoute(webCtx, {
|
|
26151
|
+
pool: core.pool,
|
|
26152
|
+
catalogs: core.catalogs,
|
|
26153
|
+
client: core.client,
|
|
26154
|
+
usage: () => usageRecorder.summary(),
|
|
26155
|
+
shim: () => shimInfo("cn"),
|
|
26156
|
+
scheduler: () => core.scheduler.status(),
|
|
26157
|
+
runAutomation: (_job, _force) => core.scheduler.startRunAll(),
|
|
26158
|
+
saveSelection: async (region, selection) => {
|
|
26159
|
+
const payload = {
|
|
26160
|
+
...selection.enabledModelIds === void 0 ? {} : { enabledModelIds: [...selection.enabledModelIds] },
|
|
26161
|
+
...selection.imageModelIds === void 0 ? {} : { imageModelIds: [...selection.imageModelIds] },
|
|
26162
|
+
...selection.contextBudgets === void 0 ? {} : { contextBudgets: { ...selection.contextBudgets } }
|
|
26163
|
+
};
|
|
26164
|
+
await setSetting(modelSelectionKeyFor(region), payload, payload);
|
|
26165
|
+
},
|
|
26166
|
+
setAccountDisabled: async (accountId, disabled) => {
|
|
26167
|
+
const currentIds = current().disabledAccountIds ?? [];
|
|
26168
|
+
const next = disabled ? currentIds.includes(accountId) ? currentIds : [...currentIds, accountId] : currentIds.filter((id) => id !== accountId);
|
|
26169
|
+
await setSetting("disabledAccountIds", next, next);
|
|
26170
|
+
},
|
|
26171
|
+
setCreditReserve: async (accountId, reserve) => {
|
|
26172
|
+
const next = creditReservesWith(current().creditReserves, accountId, reserve);
|
|
26173
|
+
await setSetting("creditReserves", next, next);
|
|
26174
|
+
},
|
|
26175
|
+
setAccountIgnored: async (accountId, ignored) => {
|
|
26176
|
+
if (ignored) {
|
|
26177
|
+
const known = core.pool.list().find((account) => account.id === accountId);
|
|
26178
|
+
await ignoreAccount({
|
|
26179
|
+
id: accountId,
|
|
26180
|
+
...known === void 0 ? {} : { label: known.label }
|
|
26181
|
+
}, ignoredPath);
|
|
26182
|
+
} else await unignoreAccount(accountId, ignoredPath);
|
|
26183
|
+
refreshIgnored();
|
|
26184
|
+
if (!ignored) await core.pool.scan();
|
|
26185
|
+
},
|
|
26186
|
+
ignoredAccounts: () => ignoredAccounts,
|
|
26187
|
+
setPreferredAccount: async (accountId) => {
|
|
26188
|
+
await writePreferredId(accountId ?? void 0, preferredPath);
|
|
26189
|
+
applyPreferred(accountId ?? void 0);
|
|
26190
|
+
},
|
|
26191
|
+
refreshCatalog: async () => {
|
|
26192
|
+
const result = await seedCatalog();
|
|
26193
|
+
invalidateCatalog();
|
|
26194
|
+
return result;
|
|
26195
|
+
},
|
|
26196
|
+
aggregateDocument: () => aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel)),
|
|
26197
|
+
saveAggregate: async (patch) => {
|
|
26198
|
+
if (patch.kind === "lane") await setAggregateEnabled(patch.enabled);
|
|
26199
|
+
else if (patch.kind === "clear") await clearProviderSetting(patch.providerId);
|
|
26200
|
+
else await updateProviderSetting(patch.providerId, {
|
|
26201
|
+
...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
|
|
26202
|
+
...patch.apiKey === void 0 ? {} : { apiKey: patch.apiKey },
|
|
26203
|
+
...patch.apiKeys === void 0 ? {} : { apiKeys: patch.apiKeys },
|
|
26204
|
+
...patch.appendApiKey === void 0 ? {} : { appendApiKey: patch.appendApiKey },
|
|
26205
|
+
...patch.distribution === void 0 ? {} : { distribution: patch.distribution },
|
|
26206
|
+
...patch.baseUrl === void 0 ? {} : { baseUrl: patch.baseUrl },
|
|
26207
|
+
...patch.models === void 0 ? {} : { models: patch.models }
|
|
23705
26208
|
});
|
|
23706
|
-
await
|
|
23707
|
-
|
|
23708
|
-
}
|
|
23709
|
-
|
|
23710
|
-
|
|
23711
|
-
|
|
23712
|
-
|
|
23713
|
-
|
|
23714
|
-
|
|
23715
|
-
|
|
23716
|
-
|
|
23717
|
-
|
|
23718
|
-
}
|
|
23719
|
-
|
|
23720
|
-
|
|
23721
|
-
|
|
23722
|
-
|
|
23723
|
-
|
|
23724
|
-
|
|
23725
|
-
|
|
23726
|
-
|
|
23727
|
-
|
|
23728
|
-
|
|
23729
|
-
|
|
23730
|
-
|
|
23731
|
-
|
|
23732
|
-
|
|
23733
|
-
|
|
23734
|
-
|
|
23735
|
-
|
|
23736
|
-
|
|
23737
|
-
|
|
23738
|
-
|
|
23739
|
-
|
|
23740
|
-
|
|
23741
|
-
|
|
23742
|
-
|
|
23743
|
-
|
|
23744
|
-
|
|
23745
|
-
|
|
23746
|
-
|
|
23747
|
-
|
|
23748
|
-
|
|
23749
|
-
|
|
23750
|
-
|
|
23751
|
-
|
|
23752
|
-
|
|
23753
|
-
|
|
23754
|
-
|
|
23755
|
-
|
|
23756
|
-
|
|
23757
|
-
|
|
23758
|
-
|
|
23759
|
-
|
|
23760
|
-
|
|
23761
|
-
|
|
23762
|
-
|
|
23763
|
-
|
|
23764
|
-
|
|
23765
|
-
|
|
23766
|
-
|
|
23767
|
-
|
|
23768
|
-
|
|
23769
|
-
|
|
23770
|
-
|
|
23771
|
-
|
|
23772
|
-
|
|
23773
|
-
|
|
23774
|
-
|
|
23775
|
-
|
|
23776
|
-
|
|
23777
|
-
|
|
23778
|
-
|
|
23779
|
-
|
|
23780
|
-
|
|
23781
|
-
|
|
23782
|
-
|
|
23783
|
-
|
|
23784
|
-
|
|
23785
|
-
|
|
23786
|
-
|
|
23787
|
-
|
|
26209
|
+
await aggregateCatalog.refresh();
|
|
26210
|
+
return aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel));
|
|
26211
|
+
},
|
|
26212
|
+
probeAggregate: async (providerId) => {
|
|
26213
|
+
const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
|
|
26214
|
+
return {
|
|
26215
|
+
ok: probe.ok,
|
|
26216
|
+
status: probe.status,
|
|
26217
|
+
message: probe.message,
|
|
26218
|
+
...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
|
|
26219
|
+
...probe.modelIds === void 0 ? {} : { modelIds: probe.modelIds }
|
|
26220
|
+
};
|
|
26221
|
+
},
|
|
26222
|
+
/**
|
|
26223
|
+
* One real streaming call, for the card's per-model "test connection" button.
|
|
26224
|
+
*
|
|
26225
|
+
* Routed through `ctx.llm.stream` rather than through any of this plugin's
|
|
26226
|
+
* own lanes, and that is the whole point: `ctx.llm` is the host's adapter
|
|
26227
|
+
* registry, so it resolves the provider/model pair to whichever credential
|
|
26228
|
+
* and endpoint actually serve it — including lanes this plugin knows nothing
|
|
26229
|
+
* about. Asking our own shims instead would make the button report on the
|
|
26230
|
+
* plumbing rather than on the model the user clicked.
|
|
26231
|
+
*
|
|
26232
|
+
* Never throws (see {@link probeModelConnectivity}): the measurement is the
|
|
26233
|
+
* answer, and a rejection here would show as a bare route failure that reads
|
|
26234
|
+
* like a wrong key.
|
|
26235
|
+
*/
|
|
26236
|
+
probeModel: async (provider, model, signal) => {
|
|
26237
|
+
return probeModelConnectivity(ctx.llm, provider, model, { signal });
|
|
26238
|
+
},
|
|
26239
|
+
/**
|
|
26240
|
+
* What each login channel contributes, read from the host's own catalogue.
|
|
26241
|
+
*
|
|
26242
|
+
* Not from the pack, on purpose. The pack's `model.list` keeps the id, the
|
|
26243
|
+
* name and two flags and drops the rest, and the rest is exactly what the
|
|
26244
|
+
* login page is asked to show. The host's `listModels` is also the same
|
|
26245
|
+
* catalogue the model picker builds from, so a row's window here is the
|
|
26246
|
+
* window the picker will enforce.
|
|
26247
|
+
*
|
|
26248
|
+
* `listModels` is a LISTING, though: the host's own answer carries only the
|
|
26249
|
+
* id, the name, a description and the input modalities, and the host drops
|
|
26250
|
+
* the context window out of it on the way out (its listing mapper keeps
|
|
26251
|
+
* four fields). The window lives one call deeper, on
|
|
26252
|
+
* `resolveModelInfo(provider, model)` — which is where the model picker and
|
|
26253
|
+
* the compaction planner read it from — so a second pass over each row is
|
|
26254
|
+
* the only way to show a context size that matches what will actually be
|
|
26255
|
+
* enforced.
|
|
26256
|
+
*
|
|
26257
|
+
* That second pass is bounded and per-row isolated: adapters resolve a model
|
|
26258
|
+
* from their own cache in the common case, a row that cannot be resolved
|
|
26259
|
+
* simply prints no window, and a channel's answer is never held up by one
|
|
26260
|
+
* model it could not describe.
|
|
26261
|
+
*
|
|
26262
|
+
* A provider with no adapter registered under it is left out of the record
|
|
26263
|
+
* instead of being reported empty: "not signed in" and "signed in with
|
|
26264
|
+
* nothing to offer" would otherwise be drawn identically, and the user has
|
|
26265
|
+
* no way to tell which one they are looking at.
|
|
26266
|
+
*/
|
|
26267
|
+
channelModels: async (providers, hints) => {
|
|
26268
|
+
const models = {};
|
|
26269
|
+
const resolveConcurrency = 6;
|
|
26270
|
+
for (const provider of providers) try {
|
|
26271
|
+
const hinted = hints?.[provider];
|
|
26272
|
+
const rows = hinted !== void 0 && hinted.length > 0 ? hinted.map((id) => ({
|
|
26273
|
+
id,
|
|
26274
|
+
name: id
|
|
26275
|
+
})) : await ctx.llm.listModels(provider);
|
|
26276
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
26277
|
+
let next = 0;
|
|
26278
|
+
const workers = Array.from({ length: Math.min(resolveConcurrency, rows.length) }, async () => {
|
|
26279
|
+
while (next < rows.length) {
|
|
26280
|
+
const row = rows[next++];
|
|
26281
|
+
if (row === void 0) continue;
|
|
26282
|
+
let extra = {};
|
|
26283
|
+
try {
|
|
26284
|
+
const info = await ctx.llm.resolveModelInfo(provider, row.id);
|
|
26285
|
+
extra = {
|
|
26286
|
+
...info.context?.contextWindow === void 0 ? {} : { contextWindow: info.context.contextWindow },
|
|
26287
|
+
...info.defaultMaxTokens === void 0 ? {} : { maxTokens: info.defaultMaxTokens },
|
|
26288
|
+
...info.inputModalities === void 0 ? {} : { inputModalities: info.inputModalities }
|
|
26289
|
+
};
|
|
26290
|
+
} catch (cause) {}
|
|
26291
|
+
resolved.set(row.id, {
|
|
26292
|
+
id: row.id,
|
|
26293
|
+
name: row.name,
|
|
26294
|
+
...row.description === void 0 ? {} : { description: row.description },
|
|
26295
|
+
...row.inputModalities === void 0 ? {} : { inputModalities: row.inputModalities },
|
|
26296
|
+
...extra
|
|
26297
|
+
});
|
|
26298
|
+
}
|
|
26299
|
+
});
|
|
26300
|
+
await Promise.all(workers);
|
|
26301
|
+
models[provider] = rows.map((row) => resolved.get(row.id)).filter((row) => row !== void 0);
|
|
26302
|
+
} catch {}
|
|
26303
|
+
return models;
|
|
26304
|
+
},
|
|
26305
|
+
discoverAggregate: async (providerId) => {
|
|
26306
|
+
const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
|
|
26307
|
+
if (!probe.ok || probe.modelIds === void 0) return {
|
|
26308
|
+
ok: probe.ok,
|
|
26309
|
+
status: probe.status,
|
|
26310
|
+
message: probe.message,
|
|
26311
|
+
...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount }
|
|
26312
|
+
};
|
|
26313
|
+
await updateProviderSetting(providerId, { discovered: probe.modelIds });
|
|
26314
|
+
await aggregateCatalog.refresh();
|
|
26315
|
+
return {
|
|
26316
|
+
ok: true,
|
|
26317
|
+
status: probe.status,
|
|
26318
|
+
message: probe.message,
|
|
26319
|
+
...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
|
|
26320
|
+
modelIds: probe.modelIds,
|
|
26321
|
+
committed: probe.modelIds.length
|
|
26322
|
+
};
|
|
26323
|
+
},
|
|
26324
|
+
channelsDocument: () => {
|
|
26325
|
+
const state = channels.state();
|
|
26326
|
+
return {
|
|
26327
|
+
state: state.state,
|
|
26328
|
+
...state.state === "unavailable" ? { reason: state.reason } : {},
|
|
26329
|
+
channels: REGISTERED_CHANNELS.map((channel) => ({
|
|
26330
|
+
id: channel.id,
|
|
26331
|
+
name: channel.name,
|
|
26332
|
+
org: channel.org,
|
|
26333
|
+
...channel.domain === void 0 ? {} : { domain: channel.domain },
|
|
26334
|
+
accent: channel.accent,
|
|
26335
|
+
note: channel.note,
|
|
26336
|
+
loginKind: channel.login,
|
|
26337
|
+
ownedByPool: POOL_OWNED_CHANNELS.has(channel.id),
|
|
26338
|
+
...channel.smsHint === true ? { smsHint: true } : {},
|
|
26339
|
+
...channel.credits === void 0 ? {} : { credits: channel.credits }
|
|
26340
|
+
}))
|
|
26341
|
+
};
|
|
26342
|
+
},
|
|
26343
|
+
combosDocument: async () => combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster()),
|
|
26344
|
+
saveCombos: async (raw) => {
|
|
26345
|
+
await saveCombos(raw);
|
|
26346
|
+
await aggregateCatalog.refresh();
|
|
26347
|
+
return combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster());
|
|
26348
|
+
},
|
|
26349
|
+
/** Estimated credit spend per channel, for the composer strip. */
|
|
26350
|
+
creditsSpend: async (days) => await creditSpend(days),
|
|
26351
|
+
/**
|
|
26352
|
+
* Relay state plus the gateway's model picker.
|
|
26353
|
+
*
|
|
26354
|
+
* The candidates come from the shim's own roster rather than a parallel
|
|
26355
|
+
* assembly here, so the card cannot offer a model the gateway would then
|
|
26356
|
+
* refuse — the exact drift the picker exists to prevent.
|
|
26357
|
+
*/
|
|
26358
|
+
relayDocument,
|
|
26359
|
+
/**
|
|
26360
|
+
* Apply one patch from the card and answer with the fresh document.
|
|
26361
|
+
*
|
|
26362
|
+
* The write path mints a key when the card asks for a rotation and the user
|
|
26363
|
+
* has never had one: an enabled relay with no key would have to either refuse
|
|
26364
|
+
* everyone (so the switch silently does nothing) or accept everyone. Minting
|
|
26365
|
+
* one keeps "enabled" honest, and the card shows it so it can be pasted into
|
|
26366
|
+
* the other device.
|
|
26367
|
+
*/
|
|
26368
|
+
saveRelay: async (patch) => {
|
|
26369
|
+
const before = readAggregateSettingsSync().relay ?? {};
|
|
26370
|
+
const key = patch.key === "" ? newRelayKey() : patch.key;
|
|
26371
|
+
await updateRelaySetting({
|
|
26372
|
+
...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
|
|
26373
|
+
...patch.host === void 0 ? {} : { host: patch.host },
|
|
26374
|
+
...patch.port === void 0 ? {} : { port: patch.port },
|
|
26375
|
+
key: key ?? before.key ?? newRelayKey(),
|
|
26376
|
+
...patch.models === void 0 ? {} : { models: patch.models }
|
|
26377
|
+
});
|
|
26378
|
+
await relay.sync();
|
|
26379
|
+
return relayDocument();
|
|
26380
|
+
}
|
|
26381
|
+
});
|
|
26382
|
+
});
|
|
23788
26383
|
api = {
|
|
23789
26384
|
...core,
|
|
23790
26385
|
shim,
|