heybash-xdpool 1.0.8 → 1.0.9
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 +7 -0
- package/lib/bin.js +102 -51
- package/lib/client.js +133 -10
- package/lib/index.d.ts +15 -6
- package/lib/index.js +1149 -884
- package/package.json +1 -1
- package/vendor/channel-pack/pack.js +28 -1
package/lib/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import crypto, { createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { LlmAdapter, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
|
|
4
|
-
import { ToolCallId } from "@deepseek-ai/dsh-llm/brand";
|
|
4
|
+
import { ReasoningEffortId, ToolCallId } from "@deepseek-ai/dsh-llm/brand";
|
|
5
5
|
import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
7
7
|
import { homedir, hostname, tmpdir } from "node:os";
|
|
@@ -664,8 +664,6 @@ const REQUIRED_COOKIE_NAMES = [
|
|
|
664
664
|
const CHAT_ENDPOINT = "https://www.doubao.com/chat/completion";
|
|
665
665
|
const QUOTA_ENDPOINT = "https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/";
|
|
666
666
|
const TOOL_LOCAL_ACK_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/ack";
|
|
667
|
-
const TOOL_LOCAL_UPLOAD_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/upload_command_result";
|
|
668
|
-
const TOOL_LOCAL_COMPLETE_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/complete";
|
|
669
667
|
/**
|
|
670
668
|
* Client version strings. These are the desktop app build this was last
|
|
671
669
|
* verified against (M9), and they MOVE with every Doubao release — a newer app
|
|
@@ -791,8 +789,9 @@ function taskWorkspaceOf(options) {
|
|
|
791
789
|
* — the captured request carries the same two values, so they are the same
|
|
792
790
|
* install identity and not per-request state.
|
|
793
791
|
*/
|
|
794
|
-
function buildGeneralTaskParam(localMessageId, workspace, prompt) {
|
|
795
|
-
const
|
|
792
|
+
function buildGeneralTaskParam(localMessageId, workspace, prompt, isolated = false) {
|
|
793
|
+
const userData = isolated ? void 0 : void 0;
|
|
794
|
+
const agentWorkspace = isolated ? tmpdir() : userData === void 0 ? join(tmpdir(), "dsh-doubao-agent-workspace") : join(userData, "Default", ".doubao", "agent_mode", "workspace");
|
|
796
795
|
return {
|
|
797
796
|
thread_local_message_id: [localMessageId],
|
|
798
797
|
client_option: {
|
|
@@ -804,7 +803,7 @@ function buildGeneralTaskParam(localMessageId, workspace, prompt) {
|
|
|
804
803
|
workspace,
|
|
805
804
|
agent_workspace: {
|
|
806
805
|
agent_workspace: agentWorkspace,
|
|
807
|
-
local_skill_paths: [join(homedir(), "Doubao", "skills"), join(homedir(), ".agents", "skills")]
|
|
806
|
+
local_skill_paths: isolated ? [] : [join(homedir(), "Doubao", "skills"), join(homedir(), ".agents", "skills")]
|
|
808
807
|
},
|
|
809
808
|
sandbox_auth_type: 2
|
|
810
809
|
},
|
|
@@ -812,7 +811,7 @@ function buildGeneralTaskParam(localMessageId, workspace, prompt) {
|
|
|
812
811
|
need_modify_conversation: false,
|
|
813
812
|
agent_task_param: {
|
|
814
813
|
runtime_type: 2,
|
|
815
|
-
device_name: hostname(),
|
|
814
|
+
device_name: isolated ? "DSH" : hostname(),
|
|
816
815
|
workspace,
|
|
817
816
|
local_device_id: CLIENT_PARAMS.device_id,
|
|
818
817
|
local_app_id: CLIENT_PARAMS.aid,
|
|
@@ -894,7 +893,7 @@ function buildChatBody(prompt, options = {}) {
|
|
|
894
893
|
* models (`seed-lite-7b`, `5`, `9`) carry "3".
|
|
895
894
|
*/
|
|
896
895
|
const modeId = (process.env.DSH_DOUBAO_MODE_ID ?? "").trim() || (task ? "3" : "1");
|
|
897
|
-
const taskParam = task ? buildGeneralTaskParam(localMessageId, taskWorkspaceOf(options), taskModelSelected ? prompt : void 0) : { server_do_compare: true };
|
|
896
|
+
const taskParam = task ? buildGeneralTaskParam(localMessageId, options.isolatedWorkspace === true ? tmpdir() : taskWorkspaceOf(options), taskModelSelected ? prompt : void 0, options.isolatedWorkspace === true) : { server_do_compare: true };
|
|
898
897
|
const modelExtraParams = taskModelSelected ? {
|
|
899
898
|
input_token_limit: "256k",
|
|
900
899
|
...model.id === "seed-lite-7b" ? { reasoning_effort: levelIdOf(level.level) } : {}
|
|
@@ -1335,39 +1334,7 @@ async function runToolLocalResponder(uniqueKey, credentials, isStreamDone, signa
|
|
|
1335
1334
|
if (msg !== void 0) {
|
|
1336
1335
|
const cmdCall = msg?.body?.cmd_call;
|
|
1337
1336
|
const agentFinished = msg?.body?.agent_finished;
|
|
1338
|
-
if (cmdCall !== void 0)
|
|
1339
|
-
let inputObj = {};
|
|
1340
|
-
try {
|
|
1341
|
-
inputObj = JSON.parse(cmdCall.input ?? "{}");
|
|
1342
|
-
} catch {
|
|
1343
|
-
inputObj = {};
|
|
1344
|
-
}
|
|
1345
|
-
const results = (Array.isArray(inputObj.operations) ? inputObj.operations : []).map((op) => ({
|
|
1346
|
-
...op.sequence !== void 0 ? { sequence: op.sequence } : {},
|
|
1347
|
-
id: op.id,
|
|
1348
|
-
type: op.type,
|
|
1349
|
-
path: op.path,
|
|
1350
|
-
status: "success"
|
|
1351
|
-
}));
|
|
1352
|
-
const outputObj = {
|
|
1353
|
-
request_id: inputObj.request_id ?? "",
|
|
1354
|
-
status: "success",
|
|
1355
|
-
results
|
|
1356
|
-
};
|
|
1357
|
-
try {
|
|
1358
|
-
await postToolJson(TOOL_LOCAL_UPLOAD_ENDPOINT, {
|
|
1359
|
-
cmd_id: cmdCall.cmd_id,
|
|
1360
|
-
session_id: msg.session_id,
|
|
1361
|
-
msg_id: msgId,
|
|
1362
|
-
output: JSON.stringify(outputObj)
|
|
1363
|
-
});
|
|
1364
|
-
await postToolJson(TOOL_LOCAL_COMPLETE_ENDPOINT, { msg_id: msgId });
|
|
1365
|
-
} catch {
|
|
1366
|
-
return;
|
|
1367
|
-
}
|
|
1368
|
-
seq += 1;
|
|
1369
|
-
continue;
|
|
1370
|
-
}
|
|
1337
|
+
if (cmdCall !== void 0) throw new Error("豆包请求了无法由 DSH 验证的本地操作,已停止;请使用 DSH 工具重试。");
|
|
1371
1338
|
if (agentFinished !== void 0) return;
|
|
1372
1339
|
seq += 1;
|
|
1373
1340
|
continue;
|
|
@@ -1398,13 +1365,15 @@ async function streamOnce(prompt, options = {}) {
|
|
|
1398
1365
|
const uniqueKey = bodyObj.option.unique_key;
|
|
1399
1366
|
const body = JSON.stringify(bodyObj);
|
|
1400
1367
|
const isTask = taskModeEnabled(options);
|
|
1368
|
+
const responderAbort = new AbortController();
|
|
1369
|
+
const requestSignal = options.signal ? AbortSignal.any([options.signal, responderAbort.signal]) : responderAbort.signal;
|
|
1401
1370
|
let response;
|
|
1402
1371
|
try {
|
|
1403
1372
|
response = await fetch(url, {
|
|
1404
1373
|
method: "POST",
|
|
1405
1374
|
headers,
|
|
1406
1375
|
body,
|
|
1407
|
-
|
|
1376
|
+
signal: requestSignal
|
|
1408
1377
|
});
|
|
1409
1378
|
} catch (error) {
|
|
1410
1379
|
if (options.signal?.aborted) throw error;
|
|
@@ -1416,9 +1385,20 @@ async function streamOnce(prompt, options = {}) {
|
|
|
1416
1385
|
}
|
|
1417
1386
|
absorbSetCookies(response.headers);
|
|
1418
1387
|
let streamDone = false;
|
|
1419
|
-
|
|
1388
|
+
let responderFailure;
|
|
1389
|
+
const responderPromise = isTask ? runToolLocalResponder(uniqueKey, credentials, () => streamDone, requestSignal).catch((error) => {
|
|
1390
|
+
responderFailure = error;
|
|
1391
|
+
responderAbort.abort();
|
|
1392
|
+
}) : Promise.resolve();
|
|
1420
1393
|
try {
|
|
1421
|
-
|
|
1394
|
+
const result = await consumeStream(response, options.callbacks, { harvestNotifyText: isTask });
|
|
1395
|
+
streamDone = true;
|
|
1396
|
+
await responderPromise;
|
|
1397
|
+
if (responderFailure !== void 0) throw responderFailure;
|
|
1398
|
+
return result;
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
if (responderFailure !== void 0) throw responderFailure;
|
|
1401
|
+
throw error;
|
|
1422
1402
|
} finally {
|
|
1423
1403
|
streamDone = true;
|
|
1424
1404
|
await responderPromise;
|
|
@@ -1460,7 +1440,7 @@ async function streamChat(prompt, options = {}) {
|
|
|
1460
1440
|
return await call(wanted);
|
|
1461
1441
|
} catch (error) {
|
|
1462
1442
|
const taskRuntimeMissing = error instanceof DoubaoUpstreamError && (error.code === CODE_TASK_RUNTIME_UNAVAILABLE || /agent_err_real_answer/.test(error.message));
|
|
1463
|
-
if (!wanted || !taskRuntimeMissing || emittedText) throw error;
|
|
1443
|
+
if (!wanted || !taskRuntimeMissing || emittedText || options.allowTaskFallback === false) throw error;
|
|
1464
1444
|
return call(false);
|
|
1465
1445
|
}
|
|
1466
1446
|
}
|
|
@@ -1850,7 +1830,7 @@ function createDoubaoLlm(options) {
|
|
|
1850
1830
|
* value falls back to the middle level, which every model in the family accepts.
|
|
1851
1831
|
*/
|
|
1852
1832
|
const requested = streamOptions["reasoningEffort"];
|
|
1853
|
-
const levelName = DOUBAO_REASONING_LEVELS.some((entry) => entry.id === requested)
|
|
1833
|
+
const levelName = typeof requested === "string" && (DOUBAO_REASONING_LEVELS.some((entry) => entry.id === requested) || /^\d{1,3}$/u.test(requested)) ? requested : "high";
|
|
1854
1834
|
const signal = streamOptions["signal"] instanceof AbortSignal ? streamOptions["signal"] : new AbortController().signal;
|
|
1855
1835
|
const textQueue = [];
|
|
1856
1836
|
const reasoningQueue = [];
|
|
@@ -1859,6 +1839,9 @@ function createDoubaoLlm(options) {
|
|
|
1859
1839
|
let images = [];
|
|
1860
1840
|
const turn = chat(prompt, {
|
|
1861
1841
|
modelKey: model.id,
|
|
1842
|
+
taskMode: streamOptions["taskMode"] === true,
|
|
1843
|
+
allowTaskFallback: false,
|
|
1844
|
+
isolatedWorkspace: true,
|
|
1862
1845
|
reasoningLevel: levelName,
|
|
1863
1846
|
signal,
|
|
1864
1847
|
callbacks: {
|
|
@@ -1906,936 +1889,1157 @@ function createDoubaoLlm(options) {
|
|
|
1906
1889
|
}
|
|
1907
1890
|
};
|
|
1908
1891
|
}
|
|
1909
|
-
// src/
|
|
1910
|
-
const DOUBAO_PROVIDER_ID = "heybash-doubao";
|
|
1911
|
-
const DIRECT_DOUBAO_MODELS = DOUBAO_MODELS.filter((model) => model.id === "0" || model.id === "3");
|
|
1912
|
-
var DoubaoAdapter = class extends LlmAdapter {
|
|
1913
|
-
session;
|
|
1914
|
-
constructor(session) {
|
|
1915
|
-
super();
|
|
1916
|
-
this.session = session;
|
|
1917
|
-
}
|
|
1918
|
-
providerInfo() {
|
|
1919
|
-
return {
|
|
1920
|
-
id: DOUBAO_PROVIDER_ID,
|
|
1921
|
-
name: "豆包"
|
|
1922
|
-
};
|
|
1923
|
-
}
|
|
1924
|
-
async listModels() {
|
|
1925
|
-
if (!sessionUsable(this.session())) return [];
|
|
1926
|
-
return DIRECT_DOUBAO_MODELS.map((model) => ({
|
|
1927
|
-
provider: DOUBAO_PROVIDER_ID,
|
|
1928
|
-
id: model.id,
|
|
1929
|
-
name: model.name,
|
|
1930
|
-
inputModalities: ["text"]
|
|
1931
|
-
}));
|
|
1932
|
-
}
|
|
1933
|
-
async resolveModel(provider, model) {
|
|
1934
|
-
const row = (await this.listModels()).find((item) => item.id === model);
|
|
1935
|
-
if (provider !== "heybash-doubao" || row === void 0) throw new Error("豆包模型不可用,请先登录");
|
|
1936
|
-
return {
|
|
1937
|
-
...row,
|
|
1938
|
-
context: { contextWindow: DOUBAO_CONTEXT_WINDOW }
|
|
1939
|
-
};
|
|
1940
|
-
}
|
|
1941
|
-
async *stream(options) {
|
|
1942
|
-
try {
|
|
1943
|
-
if (options.provider !== "heybash-doubao" || !DIRECT_DOUBAO_MODELS.some((model) => model.id === options.model)) throw new Error("豆包模型不可用");
|
|
1944
|
-
const lane = createDoubaoLlm({ session: this.session });
|
|
1945
|
-
const hasTools = (options.tools?.length ?? 0) > 0;
|
|
1946
|
-
const messages = hasTools ? [{
|
|
1947
|
-
role: "user",
|
|
1948
|
-
content: [{
|
|
1949
|
-
type: "text",
|
|
1950
|
-
text: doubaoPrompt(options)
|
|
1951
|
-
}]
|
|
1952
|
-
}] : options.messages;
|
|
1953
|
-
let text = "";
|
|
1954
|
-
let reasoning = "";
|
|
1955
|
-
if (!hasTools) yield {
|
|
1956
|
-
type: "block-start",
|
|
1957
|
-
index: 0,
|
|
1958
|
-
blockType: "text"
|
|
1959
|
-
};
|
|
1960
|
-
for await (const chunk of lane.stream({
|
|
1961
|
-
...options,
|
|
1962
|
-
system: hasTools ? "" : options.system,
|
|
1963
|
-
messages
|
|
1964
|
-
})) if (chunk.type === "text-delta") {
|
|
1965
|
-
if (hasTools) text += chunk.text;
|
|
1966
|
-
else {
|
|
1967
|
-
text += chunk.text;
|
|
1968
|
-
yield {
|
|
1969
|
-
type: "text-delta",
|
|
1970
|
-
index: 0,
|
|
1971
|
-
text: chunk.text
|
|
1972
|
-
};
|
|
1973
|
-
}
|
|
1974
|
-
} else if (chunk.type === "reasoning-delta" && !hasTools) reasoning += chunk.text;
|
|
1975
|
-
if (!hasTools) {
|
|
1976
|
-
yield {
|
|
1977
|
-
type: "block-end",
|
|
1978
|
-
index: 0,
|
|
1979
|
-
block: {
|
|
1980
|
-
type: "text",
|
|
1981
|
-
text
|
|
1982
|
-
}
|
|
1983
|
-
};
|
|
1984
|
-
if (reasoning !== "") {
|
|
1985
|
-
yield {
|
|
1986
|
-
type: "block-start",
|
|
1987
|
-
index: 1,
|
|
1988
|
-
blockType: "reasoning"
|
|
1989
|
-
};
|
|
1990
|
-
yield {
|
|
1991
|
-
type: "reasoning-delta",
|
|
1992
|
-
index: 1,
|
|
1993
|
-
text: reasoning
|
|
1994
|
-
};
|
|
1995
|
-
yield {
|
|
1996
|
-
type: "block-end",
|
|
1997
|
-
index: 1,
|
|
1998
|
-
block: {
|
|
1999
|
-
type: "reasoning",
|
|
2000
|
-
text: reasoning
|
|
2001
|
-
}
|
|
2002
|
-
};
|
|
2003
|
-
}
|
|
2004
|
-
}
|
|
2005
|
-
if (hasTools) {
|
|
2006
|
-
const output = decodeDoubaoToolResponse(text, options.tools);
|
|
2007
|
-
if (output.calls) {
|
|
2008
|
-
for (const [index, call] of output.calls.entries()) {
|
|
2009
|
-
const id = ToolCallId(`call_${randomUUID()}`);
|
|
2010
|
-
yield {
|
|
2011
|
-
type: "block-start",
|
|
2012
|
-
index,
|
|
2013
|
-
blockType: "tool-call"
|
|
2014
|
-
};
|
|
2015
|
-
yield {
|
|
2016
|
-
type: "tool-call-delta",
|
|
2017
|
-
index,
|
|
2018
|
-
id,
|
|
2019
|
-
name: call.name,
|
|
2020
|
-
argumentsDelta: call.arguments
|
|
2021
|
-
};
|
|
2022
|
-
yield {
|
|
2023
|
-
type: "block-end",
|
|
2024
|
-
index,
|
|
2025
|
-
block: {
|
|
2026
|
-
type: "tool-call",
|
|
2027
|
-
id,
|
|
2028
|
-
name: call.name,
|
|
2029
|
-
arguments: call.arguments
|
|
2030
|
-
}
|
|
2031
|
-
};
|
|
2032
|
-
}
|
|
2033
|
-
yield {
|
|
2034
|
-
type: "finish",
|
|
2035
|
-
reason: { kind: "tool-calls" }
|
|
2036
|
-
};
|
|
2037
|
-
return;
|
|
2038
|
-
}
|
|
2039
|
-
const answer = output.answer ?? "";
|
|
2040
|
-
yield {
|
|
2041
|
-
type: "block-start",
|
|
2042
|
-
index: 0,
|
|
2043
|
-
blockType: "text"
|
|
2044
|
-
};
|
|
2045
|
-
yield {
|
|
2046
|
-
type: "text-delta",
|
|
2047
|
-
index: 0,
|
|
2048
|
-
text: answer
|
|
2049
|
-
};
|
|
2050
|
-
yield {
|
|
2051
|
-
type: "block-end",
|
|
2052
|
-
index: 0,
|
|
2053
|
-
block: {
|
|
2054
|
-
type: "text",
|
|
2055
|
-
text: answer
|
|
2056
|
-
}
|
|
2057
|
-
};
|
|
2058
|
-
}
|
|
2059
|
-
yield {
|
|
2060
|
-
type: "finish",
|
|
2061
|
-
reason: { kind: "stop" }
|
|
2062
|
-
};
|
|
2063
|
-
} catch (error) {
|
|
2064
|
-
yield {
|
|
2065
|
-
type: "finish",
|
|
2066
|
-
reason: {
|
|
2067
|
-
kind: options.signal?.aborted ? "aborted" : "error",
|
|
2068
|
-
failure: {
|
|
2069
|
-
code: "DOUBAO_ERROR",
|
|
2070
|
-
message: error instanceof Error ? error.message : "豆包请求失败"
|
|
2071
|
-
}
|
|
2072
|
-
}
|
|
2073
|
-
};
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
};
|
|
2077
|
-
// src/status-paths.ts
|
|
1892
|
+
// src/file-perms.ts
|
|
2078
1893
|
/**
|
|
2079
|
-
*
|
|
2080
|
-
* Heybash settings card.
|
|
1894
|
+
* Write a file that holds credentials, without leaving it world-readable.
|
|
2081
1895
|
*
|
|
2082
|
-
*
|
|
2083
|
-
*
|
|
2084
|
-
*
|
|
2085
|
-
*
|
|
2086
|
-
*
|
|
1896
|
+
* Every credential this plugin keeps on disk — the durable account list, the
|
|
1897
|
+
* ignore list, any mirrored balance — travelled through a plain `writeFile` with
|
|
1898
|
+
* the process umask as the only protection. On a POSIX host that typically means
|
|
1899
|
+
* `0644`: readable by every other user on the machine, and these files carry
|
|
1900
|
+
* `accessToken` / `refreshToken` verbatim.
|
|
2087
1901
|
*
|
|
2088
|
-
*
|
|
2089
|
-
*/
|
|
2090
|
-
/** Plugin-owned read-only pool status endpoint (account rows + models + shim). */
|
|
2091
|
-
const POOL_STATUS_PATH = "/plugins/dsh-xdpool/status";
|
|
2092
|
-
/** Plugin-owned local account rescan endpoint (re-read desktop snapshots). */
|
|
2093
|
-
const POOL_RESCAN_PATH = "/plugins/dsh-xdpool/accounts/rescan";
|
|
2094
|
-
/**
|
|
2095
|
-
* Re-fetch the upstream model catalog for both regions.
|
|
1902
|
+
* Two rules, and the order matters:
|
|
2096
1903
|
*
|
|
2097
|
-
*
|
|
2098
|
-
*
|
|
2099
|
-
*
|
|
2100
|
-
*
|
|
2101
|
-
*
|
|
1904
|
+
* 1. **Create, don't patch.** `mode` on `writeFile` only applies when the file is
|
|
1905
|
+
* created. The atomic-write pattern already writes a fresh temp file and
|
|
1906
|
+
* renames it over the target, so the temp is created with `0600` and the
|
|
1907
|
+
* rename carries that permission to the destination. Chmod'ing afterwards
|
|
1908
|
+
* would also work but leaves a window where the file exists with the old
|
|
1909
|
+
* mode.
|
|
1910
|
+
* 2. **Still chmod best-effort.** A file written by an older version already
|
|
1911
|
+
* exists with `0644`; the rename replaces the inode, so rule 1 covers it —
|
|
1912
|
+
* but a host that keeps the target in place (or a future caller that writes
|
|
1913
|
+
* directly) would not be covered, and `chmod` is cheap.
|
|
1914
|
+
*
|
|
1915
|
+
* WINDOWS: `mode` is ignored by Node on win32, and there is no ACL equivalent in
|
|
1916
|
+
* the standard library. The honest statement is what actually protects these
|
|
1917
|
+
* files there: they live under the user's own profile (%USERPROFILE%, %LOCALAPPDATA%),
|
|
1918
|
+
* whose inherited ACL excludes other standard users by default. Calling `icacls`
|
|
1919
|
+
* per write would spawn a process on every balance update to re-apply a
|
|
1920
|
+
* protection the parent directory already provides, so this module does not. A
|
|
1921
|
+
* profile relocated to a shared directory is outside what this code can detect —
|
|
1922
|
+
* the README says where the files live so the user can check.
|
|
1923
|
+
*
|
|
1924
|
+
* @module dsh-xdpool/file-perms
|
|
2102
1925
|
*/
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
const POOL_CHECKIN_PATH = "/plugins/dsh-xdpool/checkin";
|
|
2108
|
-
/** Plugin-owned model-selection save endpoint (writes the settings section). */
|
|
2109
|
-
const POOL_MODELS_SAVE_PATH = "/plugins/dsh-xdpool/models/save";
|
|
2110
|
-
/** Switch one account in or out of the pool (card toggle). */
|
|
2111
|
-
const POOL_ACCOUNT_DISABLE_PATH = "/plugins/dsh-xdpool/accounts/disabled";
|
|
1926
|
+
/** Owner-only, for a file that holds a secret. */
|
|
1927
|
+
const SECRET_FILE_MODE = 384;
|
|
1928
|
+
/** Owner-only, for the directory that holds them. */
|
|
1929
|
+
const SECRET_DIR_MODE = 448;
|
|
2112
1930
|
/**
|
|
2113
|
-
*
|
|
1931
|
+
* True on a platform where POSIX modes are meaningful.
|
|
2114
1932
|
*
|
|
2115
|
-
*
|
|
2116
|
-
*
|
|
1933
|
+
* Computed through a `typeof process` guard rather than read straight off the
|
|
1934
|
+
* global: this module is host-only in intent, but `store.ts` imports it and the
|
|
1935
|
+
* browser bundle imports `store.ts` for its row types, so the module body DOES
|
|
1936
|
+
* get bundled for the browser. A bare `process.platform` there throws
|
|
1937
|
+
* `ReferenceError: process is not defined` at first render — and it is the kind
|
|
1938
|
+
* of failure that only shows up in the packaged app.
|
|
2117
1939
|
*/
|
|
2118
|
-
const
|
|
2119
|
-
/** Run one automation job immediately, so the card can verify it on demand. */
|
|
2120
|
-
const POOL_AUTOMATION_RUN_PATH = "/plugins/dsh-xdpool/automation/run";
|
|
2121
|
-
/** Set or clear one account's reserved-credit floor. */
|
|
2122
|
-
const POOL_CREDIT_RESERVE_PATH = "/plugins/dsh-xdpool/accounts/credit-reserve";
|
|
1940
|
+
const POSIX = typeof process === "undefined" ? false : process.platform !== "win32";
|
|
2123
1941
|
/**
|
|
2124
|
-
*
|
|
1942
|
+
* Create the directory a secret lives in, owner-only.
|
|
2125
1943
|
*
|
|
2126
|
-
*
|
|
2127
|
-
*
|
|
2128
|
-
*
|
|
2129
|
-
*
|
|
2130
|
-
*
|
|
2131
|
-
* `?days=N` limits the window; the ledger keeps 90 days.
|
|
2132
|
-
*/
|
|
2133
|
-
const POOL_CREDITS_SPEND_PATH = "/plugins/dsh-xdpool/credits/spend";
|
|
2134
|
-
/**
|
|
2135
|
-
* Name the account to try first, or hand the choice back to the strategy.
|
|
2136
|
-
*
|
|
2137
|
-
* A route rather than a settings write for the reason the ignore list is a file:
|
|
2138
|
-
* the CLI has no settings service, so a card-only settings key could be written
|
|
2139
|
-
* by the card and never by `heybash-xdpool prefer`. The route owns the
|
|
2140
|
-
* write, pushes it into the pool immediately so the very next request sees it,
|
|
2141
|
-
* and is the one path both halves share.
|
|
2142
|
-
*/
|
|
2143
|
-
const POOL_ACCOUNT_PREFER_PATH = "/plugins/dsh-xdpool/accounts/preferred";
|
|
2144
|
-
/**
|
|
2145
|
-
* Read the aggregate lane's state: every registry provider, its saved setting
|
|
2146
|
-
* (never its key), and whether it can serve anything right now.
|
|
2147
|
-
*
|
|
2148
|
-
* Separate from {@link POOL_STATUS_PATH} because it answers a different
|
|
2149
|
-
* question — "what can I configure" rather than "what is my pool doing" — and
|
|
2150
|
-
* because its payload is the WHOLE roster. Folding 76 provider records into the
|
|
2151
|
-
* status document would make every 30-second poll of the pool card carry a
|
|
2152
|
-
* directory nobody reads most of the time.
|
|
2153
|
-
*/
|
|
2154
|
-
const POOL_AGGREGATE_PATH = "/plugins/dsh-xdpool/aggregate";
|
|
2155
|
-
/**
|
|
2156
|
-
* Save one aggregate provider's setting: its key, its on/off switch, its base-URL
|
|
2157
|
-
* override, or the model ids a listing round discovered.
|
|
2158
|
-
*
|
|
2159
|
-
* POST only, and one provider per request — read-modify-write on the host side,
|
|
2160
|
-
* so two tabs editing two providers cannot clobber each other.
|
|
2161
|
-
*/
|
|
2162
|
-
const POOL_AGGREGATE_SAVE_PATH = "/plugins/dsh-xdpool/aggregate/save";
|
|
2163
|
-
/**
|
|
2164
|
-
* Verify one provider's key with a cheap non-generating call, and report what
|
|
2165
|
-
* its listing answered.
|
|
2166
|
-
*
|
|
2167
|
-
* Its own route because it is the only aggregate action that talks to the
|
|
2168
|
-
* network: a probe must never run as a side effect of saving a setting, or
|
|
2169
|
-
* "save" would silently spend the user's rate limit.
|
|
1944
|
+
* `recursive` so a fresh install works, and the mode applies to every directory
|
|
1945
|
+
* this call creates. An existing directory keeps its mode — `mkdir` does not
|
|
1946
|
+
* change what is already there — so `chmod` runs too, best-effort: tightening a
|
|
1947
|
+
* directory that a previous version created permissively is exactly the case
|
|
1948
|
+
* worth fixing, and a failure is not worth aborting a save over.
|
|
2170
1949
|
*/
|
|
2171
|
-
|
|
1950
|
+
async function ensureSecretDir(dir) {
|
|
1951
|
+
await mkdir(dir, {
|
|
1952
|
+
recursive: true,
|
|
1953
|
+
...POSIX ? { mode: SECRET_DIR_MODE } : {}
|
|
1954
|
+
});
|
|
1955
|
+
if (!POSIX) return;
|
|
1956
|
+
try {
|
|
1957
|
+
await chmod(dir, SECRET_DIR_MODE);
|
|
1958
|
+
} catch {}
|
|
1959
|
+
}
|
|
2172
1960
|
/**
|
|
2173
|
-
*
|
|
2174
|
-
*
|
|
2175
|
-
* Its own route, and POST-only, for the same reason the provider probe is: this
|
|
2176
|
-
* is the one action in the plugin that spends the user's credits, so it must
|
|
2177
|
-
* never be reachable by a prefetch, a GET, or any side effect of opening a
|
|
2178
|
-
* settings page. A GET here would let a browser — or anything else that can
|
|
2179
|
-
* reach a loopback port — fire unlimited billed calls by walking URLs.
|
|
1961
|
+
* Write `contents` to `path` with owner-only permissions.
|
|
2180
1962
|
*
|
|
2181
|
-
*
|
|
2182
|
-
*
|
|
2183
|
-
*
|
|
1963
|
+
* Not atomic on its own — callers that need the crash-safe temp+rename dance keep
|
|
1964
|
+
* doing it and just route the temp write through here, which is why the mode is
|
|
1965
|
+
* applied at creation: the rename then carries it to the final file.
|
|
2184
1966
|
*/
|
|
2185
|
-
|
|
1967
|
+
async function writeSecretFile(path, contents) {
|
|
1968
|
+
await writeFile(path, contents, POSIX ? {
|
|
1969
|
+
encoding: "utf8",
|
|
1970
|
+
mode: SECRET_FILE_MODE
|
|
1971
|
+
} : "utf8");
|
|
1972
|
+
if (!POSIX) return;
|
|
1973
|
+
try {
|
|
1974
|
+
await chmod(path, SECRET_FILE_MODE);
|
|
1975
|
+
} catch {}
|
|
1976
|
+
}
|
|
1977
|
+
// src/ignored.ts
|
|
2186
1978
|
/**
|
|
2187
|
-
*
|
|
1979
|
+
* The permanent ignore list: accounts the user has thrown out of the pool.
|
|
2188
1980
|
*
|
|
2189
|
-
*
|
|
2190
|
-
*
|
|
2191
|
-
*
|
|
2192
|
-
*
|
|
2193
|
-
*
|
|
1981
|
+
* Distinct from `disabledAccountIds`, which is a ROTATION preference. A disabled
|
|
1982
|
+
* account stays on the card, can be switched back on, and its credential keeps
|
|
1983
|
+
* being read on every scan. Ignoring is a statement about the ACCOUNT — "this
|
|
1984
|
+
* one is not mine any more" — so an ignored account is skipped BEFORE its
|
|
1985
|
+
* credential is decrypted, never appears among the pool's accounts, and does not
|
|
1986
|
+
* come back when the desktop app writes a fresh `.info` file for it.
|
|
2194
1987
|
*
|
|
2195
|
-
*
|
|
2196
|
-
*
|
|
2197
|
-
*
|
|
2198
|
-
* the
|
|
2199
|
-
|
|
2200
|
-
const POOL_CHANNEL_MODELS_PATH = "/plugins/dsh-xdpool/channels/models";
|
|
2201
|
-
/**
|
|
2202
|
-
* Fetch one provider's live model list and write it back as its discovered set.
|
|
1988
|
+
* It lives in a plugin-owned file rather than in the settings document for one
|
|
1989
|
+
* practical reason: the CLI has no settings service. `dsh-xdpool
|
|
1990
|
+
* ignore <id>` runs without a host, so a settings-only list could be written by
|
|
1991
|
+
* the card and never by the CLI. One file, read by both halves, keeps the two
|
|
1992
|
+
* views of "which accounts are ignored" identical by construction.
|
|
2203
1993
|
*
|
|
2204
|
-
*
|
|
2205
|
-
* changes what the provider contributes to the picker — so it is its own route
|
|
2206
|
-
* with its own confirmation, and a failed round keeps the previous roster.
|
|
1994
|
+
* @module dsh-xdpool/ignored
|
|
2207
1995
|
*/
|
|
2208
|
-
|
|
1996
|
+
/** Directory holding this plugin's own state (imported snapshots, ignore list). */
|
|
1997
|
+
const PLUGIN_DATA_DIR_NAME = ".xdpool";
|
|
1998
|
+
/** File holding the permanent ignore list, inside {@link pluginDataDir}. */
|
|
1999
|
+
const IGNORED_FILE_NAME = "ignored.json";
|
|
2209
2000
|
/**
|
|
2210
|
-
* The
|
|
2001
|
+
* The DSH home directory, honouring the same override the host uses.
|
|
2211
2002
|
*
|
|
2212
|
-
*
|
|
2213
|
-
*
|
|
2214
|
-
*
|
|
2215
|
-
* would put a third-party directory on the critical path of the pool card.
|
|
2003
|
+
* Shared by the CLI and the host so both halves resolve the same file: an
|
|
2004
|
+
* `ignore` written from the terminal has to be visible to the running plugin,
|
|
2005
|
+
* which is only true if they agree on where "home" is.
|
|
2216
2006
|
*/
|
|
2217
|
-
|
|
2007
|
+
function dshHome(env = process.env) {
|
|
2008
|
+
const fromEnv = env["DSH_HOME"];
|
|
2009
|
+
if (typeof fromEnv === "string" && fromEnv.trim() !== "") return fromEnv.trim();
|
|
2010
|
+
return join(homedir(), ".dsh");
|
|
2011
|
+
}
|
|
2012
|
+
/** This plugin's own state directory. */
|
|
2013
|
+
function pluginDataDir(env = process.env) {
|
|
2014
|
+
return join(dshHome(env), PLUGIN_DATA_DIR_NAME);
|
|
2015
|
+
}
|
|
2016
|
+
/** Absolute path of the ignore list. */
|
|
2017
|
+
function ignoredIdsPath(env = process.env) {
|
|
2018
|
+
return join(pluginDataDir(env), IGNORED_FILE_NAME);
|
|
2019
|
+
}
|
|
2218
2020
|
/**
|
|
2219
|
-
*
|
|
2021
|
+
* Normalize whatever the file holds into a clean list.
|
|
2220
2022
|
*
|
|
2221
|
-
*
|
|
2222
|
-
*
|
|
2023
|
+
* Tolerant on purpose: this file is hand-editable and a malformed entry must not
|
|
2024
|
+
* take the pool down. An entry without a usable id is dropped; a missing label
|
|
2025
|
+
* falls back to the id so the card always has something to print.
|
|
2223
2026
|
*/
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
const
|
|
2027
|
+
function normalize$1(raw) {
|
|
2028
|
+
if (typeof raw !== "object" || raw === null) return [];
|
|
2029
|
+
const entries = raw.accounts;
|
|
2030
|
+
if (!Array.isArray(entries)) return [];
|
|
2031
|
+
const out = [];
|
|
2032
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2033
|
+
for (const entry of entries) {
|
|
2034
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
2035
|
+
const record = entry;
|
|
2036
|
+
const id = typeof record["id"] === "string" ? record["id"].trim() : "";
|
|
2037
|
+
if (id === "" || seen.has(id)) continue;
|
|
2038
|
+
seen.add(id);
|
|
2039
|
+
const label = typeof record["label"] === "string" && record["label"].trim() !== "" ? record["label"] : id;
|
|
2040
|
+
const ignoredAt = typeof record["ignoredAt"] === "string" ? record["ignoredAt"] : "";
|
|
2041
|
+
out.push({
|
|
2042
|
+
id,
|
|
2043
|
+
label,
|
|
2044
|
+
ignoredAt
|
|
2045
|
+
});
|
|
2046
|
+
}
|
|
2047
|
+
return out;
|
|
2048
|
+
}
|
|
2227
2049
|
/**
|
|
2228
|
-
*
|
|
2229
|
-
* already owned by another plugin.
|
|
2050
|
+
* Read the ignore list, tolerating every "no list yet" shape.
|
|
2230
2051
|
*
|
|
2231
|
-
*
|
|
2232
|
-
*
|
|
2233
|
-
*
|
|
2234
|
-
* Both halves need the same string — the host to say it, the card to choose
|
|
2235
|
-
* between "this host cannot run the channels" and "another plugin already runs
|
|
2236
|
-
* them", which are opposite sentences — so it is declared with the other wire
|
|
2237
|
-
* constants rather than in `channels.ts`, which the browser bundle may not
|
|
2238
|
-
* import for value.
|
|
2052
|
+
* A missing file, unreadable file, or invalid JSON all mean the same thing to
|
|
2053
|
+
* the caller — nothing is ignored — so none of them throws. The pool must be
|
|
2054
|
+
* able to start on a machine that has never ignored anything.
|
|
2239
2055
|
*/
|
|
2240
|
-
|
|
2056
|
+
async function readIgnoredAccounts(path = ignoredIdsPath()) {
|
|
2057
|
+
try {
|
|
2058
|
+
return normalize$1(JSON.parse(await readFile(path, "utf8")));
|
|
2059
|
+
} catch {
|
|
2060
|
+
return [];
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2241
2063
|
/**
|
|
2242
|
-
*
|
|
2064
|
+
* Synchronous read, for startup.
|
|
2243
2065
|
*
|
|
2244
|
-
*
|
|
2245
|
-
*
|
|
2246
|
-
*
|
|
2247
|
-
*
|
|
2066
|
+
* The host applies the ignore list from inside `apply()`, which is synchronous,
|
|
2067
|
+
* and doing it there removes a startup race: an async load could resolve AFTER
|
|
2068
|
+
* the first account scan, which would let an ignored account slip into the pool
|
|
2069
|
+
* once per boot. The file is a few hundred bytes, so a blocking read at startup
|
|
2070
|
+
* costs nothing measurable.
|
|
2248
2071
|
*/
|
|
2249
|
-
|
|
2072
|
+
function readIgnoredAccountsSync(path = ignoredIdsPath()) {
|
|
2073
|
+
try {
|
|
2074
|
+
return normalize$1(JSON.parse(readFileSync(path, "utf8")));
|
|
2075
|
+
} catch {
|
|
2076
|
+
return [];
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2250
2079
|
/**
|
|
2251
|
-
* Replace the
|
|
2080
|
+
* Replace the ignore list, atomically.
|
|
2252
2081
|
*
|
|
2253
|
-
*
|
|
2254
|
-
*
|
|
2255
|
-
*
|
|
2256
|
-
*
|
|
2257
|
-
*
|
|
2082
|
+
* Written to a sibling temp file and renamed over the target so a crash (or a
|
|
2083
|
+
* concurrent reader) can never observe a half-written document — the ignore
|
|
2084
|
+
* list is the only thing standing between a dead account and the rotation, and
|
|
2085
|
+
* a truncated file reads as "nothing is ignored", which would quietly put every
|
|
2086
|
+
* discarded account back in the pool.
|
|
2258
2087
|
*/
|
|
2259
|
-
|
|
2088
|
+
async function writeIgnoredAccounts(accounts, path = ignoredIdsPath()) {
|
|
2089
|
+
const payload = JSON.stringify({
|
|
2090
|
+
version: 1,
|
|
2091
|
+
accounts
|
|
2092
|
+
}, null, 2);
|
|
2093
|
+
await ensureSecretDir(dirname(path));
|
|
2094
|
+
const temp = `${path}.tmp`;
|
|
2095
|
+
await writeSecretFile(temp, `${payload}\n`);
|
|
2096
|
+
await rename(temp, path);
|
|
2097
|
+
}
|
|
2260
2098
|
/**
|
|
2261
|
-
*
|
|
2099
|
+
* Add one account to the ignore list, preserving the rest.
|
|
2262
2100
|
*
|
|
2263
|
-
*
|
|
2264
|
-
*
|
|
2265
|
-
*
|
|
2266
|
-
* keeps mattering after the plugin is closed.
|
|
2101
|
+
* A read-modify-write rather than a wholesale replace: the card and the CLI can
|
|
2102
|
+
* both be open, and each request names exactly one account, so re-writing the
|
|
2103
|
+
* whole list from a stale view would drop the other side's edits.
|
|
2267
2104
|
*/
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
const POOL_USAGE_PATH = "/plugins/dsh-xdpool/usage";
|
|
2279
|
-
/** The five strategies, as a value, so a request body can be validated against it. */
|
|
2280
|
-
const POOL_DISTRIBUTIONS = Object.freeze([
|
|
2281
|
-
"priority",
|
|
2282
|
-
"round-robin",
|
|
2283
|
-
"balanced",
|
|
2284
|
-
"sticky",
|
|
2285
|
-
"expiry"
|
|
2286
|
-
]);
|
|
2287
|
-
/** True when `value` names one of the five documented strategies. */
|
|
2288
|
-
function isDistributionStrategy(value) {
|
|
2289
|
-
return POOL_DISTRIBUTIONS.includes(value);
|
|
2105
|
+
async function ignoreAccount(account, path = ignoredIdsPath()) {
|
|
2106
|
+
const current = await readIgnoredAccounts(path);
|
|
2107
|
+
if (current.some((entry) => entry.id === account.id)) return current;
|
|
2108
|
+
const next = [...current, {
|
|
2109
|
+
id: account.id,
|
|
2110
|
+
label: account.label ?? account.id,
|
|
2111
|
+
ignoredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2112
|
+
}];
|
|
2113
|
+
await writeIgnoredAccounts(next, path);
|
|
2114
|
+
return next;
|
|
2290
2115
|
}
|
|
2291
|
-
/**
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
* document that already holds an empty list is healed instead of being saved
|
|
2298
|
-
* back as an unrunnable schedule.
|
|
2299
|
-
*
|
|
2300
|
-
* This lives here rather than in `scheduler.ts` because the browser half cannot
|
|
2301
|
-
* import the host module: `scheduler.ts` pulls in `node:crypto` and the whole
|
|
2302
|
-
* upstream client, none of which exists in the browser bundle. Two hand-written
|
|
2303
|
-
* copies would drift, and the drift is invisible — the card would write a
|
|
2304
|
-
* schedule the scheduler does not run.
|
|
2305
|
-
*/
|
|
2306
|
-
const DEFAULT_AUTOMATION_HOURS = {
|
|
2307
|
-
checkin: [9],
|
|
2308
|
-
report: [10],
|
|
2309
|
-
tasks: [11],
|
|
2310
|
-
streak: [12],
|
|
2311
|
-
travel: [9, 21],
|
|
2312
|
-
compensation: [13]
|
|
2313
|
-
};
|
|
2314
|
-
/**
|
|
2315
|
-
* Parse one of the server's amount fields.
|
|
2316
|
-
*
|
|
2317
|
-
* They arrive as formatted strings ("2,100"), and they are the only source of a
|
|
2318
|
-
* percentage for the plans that omit `used_percent`. Returns undefined rather
|
|
2319
|
-
* than NaN so callers can tell "no data" from "zero".
|
|
2320
|
-
*/
|
|
2321
|
-
function parseAmount(value) {
|
|
2322
|
-
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
2323
|
-
if (typeof value !== "string") return void 0;
|
|
2324
|
-
const digits = value.replace(/[^0-9.]/g, "");
|
|
2325
|
-
if (digits === "") return void 0;
|
|
2326
|
-
const parsed = Number(digits);
|
|
2327
|
-
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2116
|
+
/** Drop one account from the ignore list. Returns the resulting list. */
|
|
2117
|
+
async function unignoreAccount(accountId, path = ignoredIdsPath()) {
|
|
2118
|
+
const current = await readIgnoredAccounts(path);
|
|
2119
|
+
const next = current.filter((entry) => entry.id !== accountId);
|
|
2120
|
+
if (next.length !== current.length) await writeIgnoredAccounts(next, path);
|
|
2121
|
+
return next;
|
|
2328
2122
|
}
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2123
|
+
// src/doubao-local-models.ts
|
|
2124
|
+
/** Read the model menu saved by Doubao Work. Menu presence does not prove routing. */
|
|
2125
|
+
const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
2126
|
+
/** Parse only the documented menu path; never return other profile contents. */
|
|
2127
|
+
function parseDoubaoModelPreferences(raw) {
|
|
2128
|
+
try {
|
|
2129
|
+
const prefs = record(JSON.parse(raw));
|
|
2130
|
+
const saman = record(prefs?.["saman"]);
|
|
2131
|
+
const cached = record(saman?.["local_storage_for_web"])?.["frontend-request-cache"];
|
|
2132
|
+
if (typeof cached !== "string") return [];
|
|
2133
|
+
const root = record(JSON.parse(cached));
|
|
2134
|
+
const entry = record(root?.["_DesktopActionBarBriefListRequestCacheDataV1"]);
|
|
2135
|
+
const data = record(entry?.["data"]);
|
|
2136
|
+
const mode = record(data?.["modeSelectData"]);
|
|
2137
|
+
const menu = record(mode?.["menuConfV2"]);
|
|
2138
|
+
const list = record(menu?.["model_list"])?.["item_list"];
|
|
2139
|
+
if (!Array.isArray(list)) return [];
|
|
2140
|
+
const out = [];
|
|
2141
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2142
|
+
for (const value of list) {
|
|
2143
|
+
const row = record(value);
|
|
2144
|
+
const id = row?.["model_item_key"];
|
|
2145
|
+
const name = row?.["name"];
|
|
2146
|
+
if (typeof id !== "string" || !/^[\w.-]{1,64}$/u.test(id) || typeof name !== "string" || name.trim() === "" || name.length > 100 || seen.has(id)) continue;
|
|
2147
|
+
seen.add(id);
|
|
2148
|
+
const sourceMode = row?.["default_mode"];
|
|
2149
|
+
const modeValue = sourceMode === "1" ? "chat" : sourceMode === "3" ? "work" : "unknown";
|
|
2150
|
+
const tags = row?.["tag_list"];
|
|
2151
|
+
const rate = Array.isArray(tags) ? tags.map((tag) => record(tag)?.["text"]).find((text) => typeof text === "string" && text.trim() !== "") : void 0;
|
|
2152
|
+
const opts = record(row?.["reasoning_effort_config"])?.["option_list"];
|
|
2153
|
+
const levels = [];
|
|
2154
|
+
if (Array.isArray(opts)) for (const candidate of opts) {
|
|
2155
|
+
const option = record(candidate), level = option?.["level"], label = option?.["name"];
|
|
2156
|
+
if (typeof level === "number" && Number.isSafeInteger(level) && typeof label === "string" && label.trim() !== "" && !levels.some((item) => item.level === level)) levels.push({
|
|
2157
|
+
level,
|
|
2158
|
+
name: label
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
out.push({
|
|
2162
|
+
id,
|
|
2163
|
+
name,
|
|
2164
|
+
mode: modeValue,
|
|
2165
|
+
...typeof rate === "string" ? { rate } : {},
|
|
2166
|
+
...levels.length ? { reasoning: levels } : {}
|
|
2167
|
+
});
|
|
2168
|
+
}
|
|
2169
|
+
return out;
|
|
2170
|
+
} catch {
|
|
2171
|
+
return [];
|
|
2172
|
+
}
|
|
2333
2173
|
}
|
|
2334
|
-
/**
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
if (!type) return void 0;
|
|
2350
|
-
const start = raw.start_time ?? 0;
|
|
2351
|
-
const end = raw.end_time ?? 0;
|
|
2352
|
-
const usedAmount = parseAmount(raw.used_amount);
|
|
2353
|
-
const totalAmount = parseAmount(raw.total_amount);
|
|
2354
|
-
const fromAmounts = usedAmount !== void 0 && totalAmount !== void 0 && totalAmount > 0 ? Math.min(100, Math.max(0, usedAmount / totalAmount * 100)) : void 0;
|
|
2355
|
-
const used = typeof raw.used_percent === "number" ? raw.used_percent : fromAmounts ?? 0;
|
|
2356
|
-
const base = {
|
|
2357
|
-
type,
|
|
2358
|
-
windowType: raw.window_type,
|
|
2359
|
-
usedPercent: used,
|
|
2360
|
-
remainingPercent: Math.max(0, 100 - used),
|
|
2361
|
-
...label === void 0 || label === "" ? {} : { label },
|
|
2362
|
-
...usedAmount === void 0 ? {} : { usedAmount },
|
|
2363
|
-
...totalAmount === void 0 ? {} : { totalAmount }
|
|
2364
|
-
};
|
|
2365
|
-
if (end <= 0) return {
|
|
2366
|
-
...base,
|
|
2367
|
-
resetsAt: 0,
|
|
2368
|
-
startedAt: 0,
|
|
2369
|
-
windowMs: 0,
|
|
2370
|
-
resetUnknown: true,
|
|
2371
|
-
startsOnUse: true
|
|
2372
|
-
};
|
|
2373
|
-
return {
|
|
2374
|
-
...base,
|
|
2375
|
-
...start <= 0 ? { startsOnUse: true } : {},
|
|
2376
|
-
resetsAt: end,
|
|
2377
|
-
startedAt: start > 0 ? start : 0,
|
|
2378
|
-
windowMs: start > 0 && end > start ? end - start : 0
|
|
2379
|
-
};
|
|
2174
|
+
/** Read a local client menu as an optional hint; never access cookies or session files. */
|
|
2175
|
+
function discoverDoubaoLocalModels(options = {}) {
|
|
2176
|
+
const local = process.env["LOCALAPPDATA"], roaming = process.env["APPDATA"];
|
|
2177
|
+
const dirs = options.paths ?? [
|
|
2178
|
+
join(homedir(), "Library", "Application Support", "DoubaoWork", "Default", "Preferences"),
|
|
2179
|
+
join(homedir(), "Library", "Application Support", "Doubao", "Default", "Preferences"),
|
|
2180
|
+
...local ? [join(local, "Doubao", "User Data", "Default", "Preferences"), join(local, "DoubaoWork", "User Data", "Default", "Preferences")] : [],
|
|
2181
|
+
...roaming ? [join(roaming, "Doubao", "Default", "Preferences"), join(roaming, "DoubaoWork", "Default", "Preferences")] : []
|
|
2182
|
+
];
|
|
2183
|
+
for (const path of dirs) try {
|
|
2184
|
+
if (statSync(path).size > 16777216) continue;
|
|
2185
|
+
const models = parseDoubaoModelPreferences(readFileSync(path, "utf8"));
|
|
2186
|
+
if (models.length > 0) return models;
|
|
2187
|
+
} catch {}
|
|
2188
|
+
return [];
|
|
2380
2189
|
}
|
|
2190
|
+
// src/doubao-model-store.ts
|
|
2191
|
+
const fallback = [
|
|
2192
|
+
{
|
|
2193
|
+
id: "0",
|
|
2194
|
+
name: "豆包 快速",
|
|
2195
|
+
mode: "chat"
|
|
2196
|
+
},
|
|
2197
|
+
{
|
|
2198
|
+
id: "3",
|
|
2199
|
+
name: "豆包 2.1 Turbo",
|
|
2200
|
+
mode: "chat"
|
|
2201
|
+
},
|
|
2202
|
+
{
|
|
2203
|
+
id: "seed-lite-7b",
|
|
2204
|
+
name: "豆包 2.1 Lite",
|
|
2205
|
+
mode: "work"
|
|
2206
|
+
},
|
|
2207
|
+
{
|
|
2208
|
+
id: "5",
|
|
2209
|
+
name: "豆包 2.1 Pro",
|
|
2210
|
+
mode: "work"
|
|
2211
|
+
},
|
|
2212
|
+
{
|
|
2213
|
+
id: "9",
|
|
2214
|
+
name: "自动",
|
|
2215
|
+
mode: "work"
|
|
2216
|
+
},
|
|
2217
|
+
{
|
|
2218
|
+
id: "image-gen",
|
|
2219
|
+
name: "豆包 生图",
|
|
2220
|
+
mode: "chat"
|
|
2221
|
+
}
|
|
2222
|
+
];
|
|
2223
|
+
/** Never merge unknown-mode entries: their actual routing is not known. */
|
|
2224
|
+
function doubaoModelCatalog(local = discoverDoubaoLocalModels()) {
|
|
2225
|
+
const entries = new Map(fallback.map((model) => [model.id, model]));
|
|
2226
|
+
for (const model of local) {
|
|
2227
|
+
if (model.mode === "unknown") continue;
|
|
2228
|
+
entries.set(model.id, model);
|
|
2229
|
+
}
|
|
2230
|
+
return [...entries.values()];
|
|
2231
|
+
}
|
|
2232
|
+
var DoubaoModelStore = class {
|
|
2233
|
+
path;
|
|
2234
|
+
disabled = /* @__PURE__ */ new Set();
|
|
2235
|
+
pending = Promise.resolve();
|
|
2236
|
+
constructor(path = join(pluginDataDir(), "doubao-model-selection.json")) {
|
|
2237
|
+
this.path = path;
|
|
2238
|
+
}
|
|
2239
|
+
async load() {
|
|
2240
|
+
try {
|
|
2241
|
+
const disabled = JSON.parse(await readFile(this.path, "utf8"))?.disabled;
|
|
2242
|
+
if (!Array.isArray(disabled) || !disabled.every((id) => typeof id === "string" && /^[\w.-]{1,64}$/u.test(id))) throw new Error("invalid model selection");
|
|
2243
|
+
this.disabled = new Set(disabled);
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
if (error?.code !== "ENOENT") throw new Error("豆包模型选择配置损坏,无法读取");
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
isEnabled(id) {
|
|
2249
|
+
return !this.disabled.has(id);
|
|
2250
|
+
}
|
|
2251
|
+
disabledIds() {
|
|
2252
|
+
return [...this.disabled];
|
|
2253
|
+
}
|
|
2254
|
+
/** Serialize whole-list updates and publish only after the durable write succeeds. */
|
|
2255
|
+
async setDisabled(ids) {
|
|
2256
|
+
if (ids.length > 200 || ids.some((id) => !/^[\w.-]{1,64}$/u.test(id))) throw new Error("模型选择无效");
|
|
2257
|
+
const next = [...new Set(ids)];
|
|
2258
|
+
const task = this.pending.then(async () => {
|
|
2259
|
+
await mkdir(dirname(this.path), {
|
|
2260
|
+
recursive: true,
|
|
2261
|
+
mode: 448
|
|
2262
|
+
});
|
|
2263
|
+
const temp = `${this.path}.${randomUUID()}.tmp`;
|
|
2264
|
+
try {
|
|
2265
|
+
await writeFile(temp, JSON.stringify({ disabled: next }), {
|
|
2266
|
+
encoding: "utf8",
|
|
2267
|
+
mode: 384,
|
|
2268
|
+
flag: "wx"
|
|
2269
|
+
});
|
|
2270
|
+
await rename(temp, this.path);
|
|
2271
|
+
} finally {
|
|
2272
|
+
await unlink(temp).catch(() => {});
|
|
2273
|
+
}
|
|
2274
|
+
this.disabled = new Set(next);
|
|
2275
|
+
});
|
|
2276
|
+
this.pending = task.catch(() => {});
|
|
2277
|
+
await task;
|
|
2278
|
+
}
|
|
2279
|
+
};
|
|
2280
|
+
// src/doubao-adapter.ts
|
|
2281
|
+
const DOUBAO_PROVIDER_ID = "heybash-doubao";
|
|
2282
|
+
const DIRECT_DOUBAO_MODELS = doubaoModelCatalog([]).filter((model) => model.id === "0" || model.id === "3");
|
|
2283
|
+
const effortId = (level) => ({
|
|
2284
|
+
3: "low",
|
|
2285
|
+
4: "mid",
|
|
2286
|
+
5: "high",
|
|
2287
|
+
6: "xhigh",
|
|
2288
|
+
7: "max"
|
|
2289
|
+
})[level] ?? String(level);
|
|
2290
|
+
var DoubaoAdapter = class extends LlmAdapter {
|
|
2291
|
+
session;
|
|
2292
|
+
models;
|
|
2293
|
+
constructor(session, models) {
|
|
2294
|
+
super();
|
|
2295
|
+
this.session = session;
|
|
2296
|
+
this.models = models;
|
|
2297
|
+
}
|
|
2298
|
+
providerInfo() {
|
|
2299
|
+
return {
|
|
2300
|
+
id: DOUBAO_PROVIDER_ID,
|
|
2301
|
+
name: "豆包"
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
async allModels() {
|
|
2305
|
+
if (this.models === void 0) return DIRECT_DOUBAO_MODELS;
|
|
2306
|
+
await this.models.ready;
|
|
2307
|
+
return this.models.catalog?.() ?? doubaoModelCatalog();
|
|
2308
|
+
}
|
|
2309
|
+
async listModels() {
|
|
2310
|
+
if (!sessionUsable(this.session())) return [];
|
|
2311
|
+
return (await this.allModels()).filter((model) => this.models?.store.isEnabled(model.id) !== false).map((model) => ({
|
|
2312
|
+
provider: DOUBAO_PROVIDER_ID,
|
|
2313
|
+
id: model.id,
|
|
2314
|
+
name: model.name,
|
|
2315
|
+
...model.rate ? { description: model.rate } : {},
|
|
2316
|
+
inputModalities: ["text"]
|
|
2317
|
+
}));
|
|
2318
|
+
}
|
|
2319
|
+
async resolveModel(provider, model) {
|
|
2320
|
+
if (!sessionUsable(this.session()) || provider !== "heybash-doubao") throw new Error("豆包模型不可用,请先登录");
|
|
2321
|
+
const item = (await this.allModels()).find((row) => row.id === model);
|
|
2322
|
+
if (item === void 0) throw new Error("豆包模型不存在或未被客户端菜单识别");
|
|
2323
|
+
const efforts = item.reasoning?.map((option) => ({
|
|
2324
|
+
id: ReasoningEffortId(effortId(option.level)),
|
|
2325
|
+
name: option.name
|
|
2326
|
+
})) ?? [];
|
|
2327
|
+
return {
|
|
2328
|
+
provider,
|
|
2329
|
+
id: item.id,
|
|
2330
|
+
name: item.name,
|
|
2331
|
+
...item.rate ? { description: item.rate } : {},
|
|
2332
|
+
inputModalities: ["text"],
|
|
2333
|
+
context: { contextWindow: DOUBAO_CONTEXT_WINDOW },
|
|
2334
|
+
...efforts.length ? { reasoning: { efforts } } : {}
|
|
2335
|
+
};
|
|
2336
|
+
}
|
|
2337
|
+
async *stream(options) {
|
|
2338
|
+
try {
|
|
2339
|
+
if (options.provider !== "heybash-doubao") throw new Error("豆包模型不可用");
|
|
2340
|
+
const item = (await this.allModels()).find((model) => model.id === options.model);
|
|
2341
|
+
if (item === void 0) throw new Error("豆包模型不存在或未被客户端菜单识别");
|
|
2342
|
+
const lane = createDoubaoLlm({ session: this.session });
|
|
2343
|
+
const hasTools = (options.tools?.length ?? 0) > 0 && item.id !== "image-gen";
|
|
2344
|
+
const messages = hasTools ? [{
|
|
2345
|
+
role: "user",
|
|
2346
|
+
content: [{
|
|
2347
|
+
type: "text",
|
|
2348
|
+
text: doubaoPrompt(options)
|
|
2349
|
+
}]
|
|
2350
|
+
}] : options.messages;
|
|
2351
|
+
let text = "";
|
|
2352
|
+
let reasoning = "";
|
|
2353
|
+
if (!hasTools) yield {
|
|
2354
|
+
type: "block-start",
|
|
2355
|
+
index: 0,
|
|
2356
|
+
blockType: "text"
|
|
2357
|
+
};
|
|
2358
|
+
for await (const chunk of lane.stream({
|
|
2359
|
+
...options,
|
|
2360
|
+
taskMode: item.mode === "work",
|
|
2361
|
+
system: hasTools ? "" : options.system,
|
|
2362
|
+
messages
|
|
2363
|
+
})) if (chunk.type === "text-delta") {
|
|
2364
|
+
if (hasTools) text += chunk.text;
|
|
2365
|
+
else {
|
|
2366
|
+
text += chunk.text;
|
|
2367
|
+
yield {
|
|
2368
|
+
type: "text-delta",
|
|
2369
|
+
index: 0,
|
|
2370
|
+
text: chunk.text
|
|
2371
|
+
};
|
|
2372
|
+
}
|
|
2373
|
+
} else if (chunk.type === "reasoning-delta" && !hasTools) reasoning += chunk.text;
|
|
2374
|
+
if (!hasTools) {
|
|
2375
|
+
yield {
|
|
2376
|
+
type: "block-end",
|
|
2377
|
+
index: 0,
|
|
2378
|
+
block: {
|
|
2379
|
+
type: "text",
|
|
2380
|
+
text
|
|
2381
|
+
}
|
|
2382
|
+
};
|
|
2383
|
+
if (reasoning !== "") {
|
|
2384
|
+
yield {
|
|
2385
|
+
type: "block-start",
|
|
2386
|
+
index: 1,
|
|
2387
|
+
blockType: "reasoning"
|
|
2388
|
+
};
|
|
2389
|
+
yield {
|
|
2390
|
+
type: "reasoning-delta",
|
|
2391
|
+
index: 1,
|
|
2392
|
+
text: reasoning
|
|
2393
|
+
};
|
|
2394
|
+
yield {
|
|
2395
|
+
type: "block-end",
|
|
2396
|
+
index: 1,
|
|
2397
|
+
block: {
|
|
2398
|
+
type: "reasoning",
|
|
2399
|
+
text: reasoning
|
|
2400
|
+
}
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
if (hasTools) {
|
|
2405
|
+
const output = decodeDoubaoToolResponse(text, options.tools);
|
|
2406
|
+
if (output.calls) {
|
|
2407
|
+
for (const [index, call] of output.calls.entries()) {
|
|
2408
|
+
const id = ToolCallId(`call_${randomUUID()}`);
|
|
2409
|
+
yield {
|
|
2410
|
+
type: "block-start",
|
|
2411
|
+
index,
|
|
2412
|
+
blockType: "tool-call"
|
|
2413
|
+
};
|
|
2414
|
+
yield {
|
|
2415
|
+
type: "tool-call-delta",
|
|
2416
|
+
index,
|
|
2417
|
+
id,
|
|
2418
|
+
name: call.name,
|
|
2419
|
+
argumentsDelta: call.arguments
|
|
2420
|
+
};
|
|
2421
|
+
yield {
|
|
2422
|
+
type: "block-end",
|
|
2423
|
+
index,
|
|
2424
|
+
block: {
|
|
2425
|
+
type: "tool-call",
|
|
2426
|
+
id,
|
|
2427
|
+
name: call.name,
|
|
2428
|
+
arguments: call.arguments
|
|
2429
|
+
}
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
yield {
|
|
2433
|
+
type: "finish",
|
|
2434
|
+
reason: { kind: "tool-calls" }
|
|
2435
|
+
};
|
|
2436
|
+
return;
|
|
2437
|
+
}
|
|
2438
|
+
const answer = output.answer ?? "";
|
|
2439
|
+
yield {
|
|
2440
|
+
type: "block-start",
|
|
2441
|
+
index: 0,
|
|
2442
|
+
blockType: "text"
|
|
2443
|
+
};
|
|
2444
|
+
yield {
|
|
2445
|
+
type: "text-delta",
|
|
2446
|
+
index: 0,
|
|
2447
|
+
text: answer
|
|
2448
|
+
};
|
|
2449
|
+
yield {
|
|
2450
|
+
type: "block-end",
|
|
2451
|
+
index: 0,
|
|
2452
|
+
block: {
|
|
2453
|
+
type: "text",
|
|
2454
|
+
text: answer
|
|
2455
|
+
}
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2458
|
+
yield {
|
|
2459
|
+
type: "finish",
|
|
2460
|
+
reason: { kind: "stop" }
|
|
2461
|
+
};
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
yield {
|
|
2464
|
+
type: "finish",
|
|
2465
|
+
reason: {
|
|
2466
|
+
kind: options.signal?.aborted ? "aborted" : "error",
|
|
2467
|
+
failure: {
|
|
2468
|
+
code: "DOUBAO_ERROR",
|
|
2469
|
+
message: error instanceof Error ? error.message : "豆包请求失败"
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
};
|
|
2476
|
+
// src/status-paths.ts
|
|
2381
2477
|
/**
|
|
2382
|
-
*
|
|
2478
|
+
* Node-free constants and types shared by the Host and browser halves of the
|
|
2479
|
+
* Heybash settings card.
|
|
2383
2480
|
*
|
|
2384
|
-
*
|
|
2385
|
-
*
|
|
2386
|
-
*
|
|
2387
|
-
*
|
|
2388
|
-
*
|
|
2389
|
-
*/
|
|
2390
|
-
const QUOTA_FAILURE_TTL_MS = 3e4;
|
|
2391
|
-
/**
|
|
2392
|
-
* Remember a failed reading, and return it.
|
|
2481
|
+
* Pool's runtime state already lives in `src/status.ts` (`buildStatus` /
|
|
2482
|
+
* `WorkBuddyStatus`); this module only carves the cross-domain (Host→browser)
|
|
2483
|
+
* JSON document into a shape that stays token-free and matches what the
|
|
2484
|
+
* browser card renders. Route paths are plugin-owned and mounted on the Host's
|
|
2485
|
+
* same-origin web server (see `src/web-status.ts`).
|
|
2393
2486
|
*
|
|
2394
|
-
*
|
|
2395
|
-
* thrown) must go through it: a failure that skips the memo is exactly the bug
|
|
2396
|
-
* this exists to prevent.
|
|
2487
|
+
* @module dsh-xdpool/status-paths
|
|
2397
2488
|
*/
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
}
|
|
2489
|
+
/** Plugin-owned read-only pool status endpoint (account rows + models + shim). */
|
|
2490
|
+
const POOL_STATUS_PATH = "/plugins/dsh-xdpool/status";
|
|
2491
|
+
/** Plugin-owned local account rescan endpoint (re-read desktop snapshots). */
|
|
2492
|
+
const POOL_RESCAN_PATH = "/plugins/dsh-xdpool/accounts/rescan";
|
|
2403
2493
|
/**
|
|
2404
|
-
*
|
|
2405
|
-
*
|
|
2406
|
-
*
|
|
2494
|
+
* Re-fetch the upstream model catalog for both regions.
|
|
2495
|
+
*
|
|
2496
|
+
* Separate from {@link POOL_RESCAN_PATH} because they answer different
|
|
2497
|
+
* questions, and conflating them misled users: "detect accounts again" only
|
|
2498
|
+
* re-read the desktop snapshots, so it could NOT recover a model list that had
|
|
2499
|
+
* fallen back to the static table after a failed startup fetch. The only way
|
|
2500
|
+
* out was restarting DSH.
|
|
2407
2501
|
*/
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
const fallbackFlags = [
|
|
2418
|
-
windowExhausted,
|
|
2419
|
-
enterpriseExhausted,
|
|
2420
|
-
incentiveExhausted
|
|
2421
|
-
].filter((flag) => typeof flag === "boolean");
|
|
2422
|
-
const flags = activeFlags.length > 0 ? activeFlags : fallbackFlags;
|
|
2423
|
-
return flags.length > 0 && flags.every(Boolean);
|
|
2424
|
-
}
|
|
2425
|
-
async function fetchQuota(options = {}) {
|
|
2426
|
-
const now = Date.now();
|
|
2427
|
-
if (!options.force && cached && now - cached.fetchedAt < 3e5) return cached;
|
|
2428
|
-
if (!options.force && cachedFailure !== void 0 && now - cachedFailureAt < QUOTA_FAILURE_TTL_MS) return cachedFailure;
|
|
2429
|
-
/**
|
|
2430
|
-
* No session is a quotable answer, not a throw.
|
|
2431
|
-
*
|
|
2432
|
-
* The quota panel sits beside the chat card, and a user who has not signed in yet still
|
|
2433
|
-
* needs to SEE it — with "not signed in" in the error field — rather than have the panel
|
|
2434
|
-
* disappear or the card throw on render.
|
|
2435
|
-
*/
|
|
2436
|
-
let credentials;
|
|
2437
|
-
try {
|
|
2438
|
-
credentials = requireDoubaoCredentials();
|
|
2439
|
-
} catch (error) {
|
|
2440
|
-
return rememberFailure({
|
|
2441
|
-
exhausted: false,
|
|
2442
|
-
windows: [],
|
|
2443
|
-
fetchedAt: now,
|
|
2444
|
-
error: error instanceof Error ? error.message : "Doubao credentials unavailable."
|
|
2445
|
-
});
|
|
2446
|
-
}
|
|
2447
|
-
try {
|
|
2448
|
-
const response = await fetch(buildQueryUrl(QUOTA_ENDPOINT, credentials.pairs.get("msToken")), {
|
|
2449
|
-
method: "POST",
|
|
2450
|
-
headers: buildHeaders(credentials, { "content-type": "application/json" }),
|
|
2451
|
-
body: JSON.stringify({ product_line: "membership" })
|
|
2452
|
-
});
|
|
2453
|
-
if (!response.ok) return rememberFailure({
|
|
2454
|
-
exhausted: false,
|
|
2455
|
-
windows: [],
|
|
2456
|
-
fetchedAt: now,
|
|
2457
|
-
error: `HTTP ${response.status}`
|
|
2458
|
-
});
|
|
2459
|
-
const payload = await response.json();
|
|
2460
|
-
const sections = [payload.data?.window_limit_section, payload.data?.incentive_quota_section];
|
|
2461
|
-
const windows = [];
|
|
2462
|
-
for (const section of sections) for (const group of section?.window_limit_groups ?? []) for (const limit of group.window_limits ?? []) {
|
|
2463
|
-
const normalized = normalizeWindow(limit, group.feature_group_name);
|
|
2464
|
-
if (normalized) windows.push(normalized);
|
|
2465
|
-
}
|
|
2466
|
-
const quota = {
|
|
2467
|
-
exhausted: evaluateQuotaExhausted(payload.data),
|
|
2468
|
-
windows,
|
|
2469
|
-
fetchedAt: now
|
|
2470
|
-
};
|
|
2471
|
-
const plan = payload.data?.current_subscription?.display?.short_name;
|
|
2472
|
-
if (plan) quota.plan = plan;
|
|
2473
|
-
if (payload.data?.member_info?.hasActiveSubscription !== void 0) quota.planActive = payload.data.member_info.hasActiveSubscription;
|
|
2474
|
-
cached = quota;
|
|
2475
|
-
cachedFailure = void 0;
|
|
2476
|
-
return quota;
|
|
2477
|
-
} catch (error) {
|
|
2478
|
-
return rememberFailure({
|
|
2479
|
-
exhausted: false,
|
|
2480
|
-
windows: [],
|
|
2481
|
-
fetchedAt: now,
|
|
2482
|
-
error: error.message
|
|
2483
|
-
});
|
|
2484
|
-
}
|
|
2485
|
-
}
|
|
2486
|
-
let cached;
|
|
2487
|
-
/** The last FAILED reading, reused for {@link QUOTA_FAILURE_TTL_MS}. */
|
|
2488
|
-
let cachedFailure;
|
|
2489
|
-
let cachedFailureAt = 0;
|
|
2490
|
-
// src/doubao-routes.ts
|
|
2491
|
-
/** Write a JSON response. */
|
|
2492
|
-
function json$1(res, status, body) {
|
|
2493
|
-
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
2494
|
-
res.end(JSON.stringify(body));
|
|
2495
|
-
}
|
|
2502
|
+
const POOL_CATALOG_REFRESH_PATH = "/plugins/dsh-xdpool/models/refresh";
|
|
2503
|
+
/** Plugin-owned cooldown reset endpoint (clear all 429 cooldowns). */
|
|
2504
|
+
const POOL_RESET_COOLDOWN_PATH = "/plugins/dsh-xdpool/cooldowns/reset";
|
|
2505
|
+
/** Plugin-owned daily check-in action endpoint (claim today's reward). */
|
|
2506
|
+
const POOL_CHECKIN_PATH = "/plugins/dsh-xdpool/checkin";
|
|
2507
|
+
/** Plugin-owned model-selection save endpoint (writes the settings section). */
|
|
2508
|
+
const POOL_MODELS_SAVE_PATH = "/plugins/dsh-xdpool/models/save";
|
|
2509
|
+
/** Switch one account in or out of the pool (card toggle). */
|
|
2510
|
+
const POOL_ACCOUNT_DISABLE_PATH = "/plugins/dsh-xdpool/accounts/disabled";
|
|
2496
2511
|
/**
|
|
2497
|
-
*
|
|
2512
|
+
* Throw one account out of the pool for good, or take it back.
|
|
2498
2513
|
*
|
|
2499
|
-
*
|
|
2500
|
-
*
|
|
2501
|
-
* the UI made — the paste arrived, was rejected `403` before any parsing ran, and the card
|
|
2502
|
-
* reported it as a bad cookie. A page in the user's browser driving this endpoint is
|
|
2503
|
-
* cross-origin by construction and always sends `Origin`, so the hostname check covers it.
|
|
2514
|
+
* Separate from the disable route because the semantics differ: disabling is a
|
|
2515
|
+
* rotation preference the account survives, ignoring survives the account.
|
|
2504
2516
|
*/
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
return url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
|
|
2511
|
-
} catch {
|
|
2512
|
-
return false;
|
|
2513
|
-
}
|
|
2514
|
-
}
|
|
2517
|
+
const POOL_ACCOUNT_IGNORE_PATH = "/plugins/dsh-xdpool/accounts/ignored";
|
|
2518
|
+
/** Run one automation job immediately, so the card can verify it on demand. */
|
|
2519
|
+
const POOL_AUTOMATION_RUN_PATH = "/plugins/dsh-xdpool/automation/run";
|
|
2520
|
+
/** Set or clear one account's reserved-credit floor. */
|
|
2521
|
+
const POOL_CREDIT_RESERVE_PATH = "/plugins/dsh-xdpool/accounts/credit-reserve";
|
|
2515
2522
|
/**
|
|
2516
|
-
*
|
|
2523
|
+
* Estimated credit spend, per channel and per model.
|
|
2517
2524
|
*
|
|
2518
|
-
*
|
|
2519
|
-
*
|
|
2525
|
+
* Derived from the pack's own token ledger, never from a credit counter — the pack
|
|
2526
|
+
* records tokens, and the vendor's balance is only visible when it is read again. The
|
|
2527
|
+
* arithmetic (tokens ÷ 1e6 × the model's published multiplier) and the honesty about
|
|
2528
|
+
* its error live in `credits.ts`.
|
|
2529
|
+
*
|
|
2530
|
+
* `?days=N` limits the window; the ledger keeps 90 days.
|
|
2520
2531
|
*/
|
|
2521
|
-
|
|
2522
|
-
ctx.effect(() => {
|
|
2523
|
-
const disposeSession = ctx.webServer.register({
|
|
2524
|
-
kind: "exact",
|
|
2525
|
-
path: POOL_DOUBAO_SESSION_PATH,
|
|
2526
|
-
handler: async (req, res) => {
|
|
2527
|
-
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2528
|
-
try {
|
|
2529
|
-
if (req.method === "DELETE") {
|
|
2530
|
-
deps.clear();
|
|
2531
|
-
setDoubaoSession(void 0);
|
|
2532
|
-
return json$1(res, 200, {
|
|
2533
|
-
ok: true,
|
|
2534
|
-
signedIn: false
|
|
2535
|
-
});
|
|
2536
|
-
}
|
|
2537
|
-
if (req.method === "POST") {
|
|
2538
|
-
/**
|
|
2539
|
-
* Start an interactive sign-in, and answer when it lands or times out.
|
|
2540
|
-
*
|
|
2541
|
-
* The window stays open for the whole budget: a QR scan plus a phone confirmation
|
|
2542
|
-
* is a minute of a person's time, and cutting it short would make the lane look
|
|
2543
|
-
* broken to anyone who was simply slower than the timer.
|
|
2544
|
-
*/
|
|
2545
|
-
const result = await browserLogin();
|
|
2546
|
-
if (!result.ok || result.session === void 0) return json$1(res, 200, {
|
|
2547
|
-
ok: false,
|
|
2548
|
-
signedIn: false,
|
|
2549
|
-
message: result.reason ?? "登录失败"
|
|
2550
|
-
});
|
|
2551
|
-
deps.save(result.session);
|
|
2552
|
-
setDoubaoSession(result.session);
|
|
2553
|
-
return json$1(res, 200, {
|
|
2554
|
-
ok: true,
|
|
2555
|
-
signedIn: true,
|
|
2556
|
-
message: "登录成功,会话已保存"
|
|
2557
|
-
});
|
|
2558
|
-
}
|
|
2559
|
-
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2560
|
-
const stored = deps.session();
|
|
2561
|
-
return json$1(res, 200, {
|
|
2562
|
-
ok: true,
|
|
2563
|
-
signedIn: sessionUsable(stored),
|
|
2564
|
-
...stored?.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
|
|
2565
|
-
});
|
|
2566
|
-
} catch (error) {
|
|
2567
|
-
return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
2568
|
-
}
|
|
2569
|
-
}
|
|
2570
|
-
});
|
|
2571
|
-
const disposeQuota = ctx.webServer.register({
|
|
2572
|
-
kind: "exact",
|
|
2573
|
-
path: POOL_DOUBAO_QUOTA_PATH,
|
|
2574
|
-
handler: async (req, res) => {
|
|
2575
|
-
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2576
|
-
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2577
|
-
const session = deps.session();
|
|
2578
|
-
if (session === void 0 || !sessionUsable(session)) return json$1(res, 200, {
|
|
2579
|
-
ok: false,
|
|
2580
|
-
signedIn: false,
|
|
2581
|
-
windows: []
|
|
2582
|
-
});
|
|
2583
|
-
try {
|
|
2584
|
-
setDoubaoSession(session);
|
|
2585
|
-
const quota = await fetchQuota({ force: true });
|
|
2586
|
-
return json$1(res, 200, {
|
|
2587
|
-
ok: quota.error === void 0,
|
|
2588
|
-
signedIn: true,
|
|
2589
|
-
exhausted: quota.exhausted,
|
|
2590
|
-
...quota.error === void 0 ? {} : { error: quota.error },
|
|
2591
|
-
windows: quota.windows
|
|
2592
|
-
});
|
|
2593
|
-
} catch (error) {
|
|
2594
|
-
return json$1(res, 200, {
|
|
2595
|
-
ok: false,
|
|
2596
|
-
signedIn: true,
|
|
2597
|
-
windows: [],
|
|
2598
|
-
error: error instanceof Error ? error.message : String(error)
|
|
2599
|
-
});
|
|
2600
|
-
}
|
|
2601
|
-
}
|
|
2602
|
-
});
|
|
2603
|
-
return () => {
|
|
2604
|
-
disposeSession();
|
|
2605
|
-
disposeQuota();
|
|
2606
|
-
};
|
|
2607
|
-
});
|
|
2608
|
-
}
|
|
2609
|
-
// src/file-perms.ts
|
|
2532
|
+
const POOL_CREDITS_SPEND_PATH = "/plugins/dsh-xdpool/credits/spend";
|
|
2610
2533
|
/**
|
|
2611
|
-
*
|
|
2534
|
+
* Name the account to try first, or hand the choice back to the strategy.
|
|
2612
2535
|
*
|
|
2613
|
-
*
|
|
2614
|
-
*
|
|
2615
|
-
* the
|
|
2616
|
-
*
|
|
2617
|
-
*
|
|
2536
|
+
* A route rather than a settings write for the reason the ignore list is a file:
|
|
2537
|
+
* the CLI has no settings service, so a card-only settings key could be written
|
|
2538
|
+
* by the card and never by `heybash-xdpool prefer`. The route owns the
|
|
2539
|
+
* write, pushes it into the pool immediately so the very next request sees it,
|
|
2540
|
+
* and is the one path both halves share.
|
|
2541
|
+
*/
|
|
2542
|
+
const POOL_ACCOUNT_PREFER_PATH = "/plugins/dsh-xdpool/accounts/preferred";
|
|
2543
|
+
/**
|
|
2544
|
+
* Read the aggregate lane's state: every registry provider, its saved setting
|
|
2545
|
+
* (never its key), and whether it can serve anything right now.
|
|
2618
2546
|
*
|
|
2619
|
-
*
|
|
2547
|
+
* Separate from {@link POOL_STATUS_PATH} because it answers a different
|
|
2548
|
+
* question — "what can I configure" rather than "what is my pool doing" — and
|
|
2549
|
+
* because its payload is the WHOLE roster. Folding 76 provider records into the
|
|
2550
|
+
* status document would make every 30-second poll of the pool card carry a
|
|
2551
|
+
* directory nobody reads most of the time.
|
|
2552
|
+
*/
|
|
2553
|
+
const POOL_AGGREGATE_PATH = "/plugins/dsh-xdpool/aggregate";
|
|
2554
|
+
/**
|
|
2555
|
+
* Save one aggregate provider's setting: its key, its on/off switch, its base-URL
|
|
2556
|
+
* override, or the model ids a listing round discovered.
|
|
2620
2557
|
*
|
|
2621
|
-
*
|
|
2622
|
-
*
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
*
|
|
2627
|
-
*
|
|
2628
|
-
* exists with `0644`; the rename replaces the inode, so rule 1 covers it —
|
|
2629
|
-
* but a host that keeps the target in place (or a future caller that writes
|
|
2630
|
-
* directly) would not be covered, and `chmod` is cheap.
|
|
2558
|
+
* POST only, and one provider per request — read-modify-write on the host side,
|
|
2559
|
+
* so two tabs editing two providers cannot clobber each other.
|
|
2560
|
+
*/
|
|
2561
|
+
const POOL_AGGREGATE_SAVE_PATH = "/plugins/dsh-xdpool/aggregate/save";
|
|
2562
|
+
/**
|
|
2563
|
+
* Verify one provider's key with a cheap non-generating call, and report what
|
|
2564
|
+
* its listing answered.
|
|
2631
2565
|
*
|
|
2632
|
-
*
|
|
2633
|
-
*
|
|
2634
|
-
*
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
*
|
|
2639
|
-
* the README says where the files live so the user can check.
|
|
2566
|
+
* Its own route because it is the only aggregate action that talks to the
|
|
2567
|
+
* network: a probe must never run as a side effect of saving a setting, or
|
|
2568
|
+
* "save" would silently spend the user's rate limit.
|
|
2569
|
+
*/
|
|
2570
|
+
const POOL_AGGREGATE_TEST_PATH = "/plugins/dsh-xdpool/aggregate/test";
|
|
2571
|
+
/**
|
|
2572
|
+
* Send one real streaming call to one model and report how it answered.
|
|
2640
2573
|
*
|
|
2641
|
-
*
|
|
2574
|
+
* Its own route, and POST-only, for the same reason the provider probe is: this
|
|
2575
|
+
* is the one action in the plugin that spends the user's credits, so it must
|
|
2576
|
+
* never be reachable by a prefetch, a GET, or any side effect of opening a
|
|
2577
|
+
* settings page. A GET here would let a browser — or anything else that can
|
|
2578
|
+
* reach a loopback port — fire unlimited billed calls by walking URLs.
|
|
2579
|
+
*
|
|
2580
|
+
* `provider` and `model` are resolved through the host's own adapter registry
|
|
2581
|
+
* rather than through this plugin's lanes, because that registry is the only
|
|
2582
|
+
* place that knows which credential and endpoint a given provider id serves.
|
|
2583
|
+
*/
|
|
2584
|
+
const POOL_MODEL_PROBE_PATH = "/plugins/dsh-xdpool/model/test";
|
|
2585
|
+
/**
|
|
2586
|
+
* POST-only: ask what models several login channels contribute right now.
|
|
2587
|
+
*
|
|
2588
|
+
* A route rather than more fields on {@link POOL_CHANNELS_PATH} because the
|
|
2589
|
+
* answer changes as accounts come and go while the roster does not, and the
|
|
2590
|
+
* login page polls only its own logins — folding live per-provider catalogues
|
|
2591
|
+
* into the roster document would either go stale the moment someone signed in,
|
|
2592
|
+
* or make every page refresh spend a round trip on thirteen providers.
|
|
2593
|
+
*
|
|
2594
|
+
* Read from the host rather than from the pack's own `model.list`, because the
|
|
2595
|
+
* pack keeps only `id`, `name` and two flags and throws away exactly the fields
|
|
2596
|
+
* this is for. The host's catalogue is the same one the model picker reads, so
|
|
2597
|
+
* the two agree by construction instead of by luck.
|
|
2598
|
+
*/
|
|
2599
|
+
const POOL_CHANNEL_MODELS_PATH = "/plugins/dsh-xdpool/channels/models";
|
|
2600
|
+
/**
|
|
2601
|
+
* Fetch one provider's live model list and write it back as its discovered set.
|
|
2602
|
+
*
|
|
2603
|
+
* Separate from the probe on purpose. The probe ANSWERS; this one COMMITS — it
|
|
2604
|
+
* changes what the provider contributes to the picker — so it is its own route
|
|
2605
|
+
* with its own confirmation, and a failed round keeps the previous roster.
|
|
2606
|
+
*/
|
|
2607
|
+
const POOL_AGGREGATE_DISCOVER_PATH = "/plugins/dsh-xdpool/aggregate/discover";
|
|
2608
|
+
/**
|
|
2609
|
+
* The thirteen login channels the vendored pack provides.
|
|
2610
|
+
*
|
|
2611
|
+
* Separate from the aggregate document for the same reason: the two lanes answer
|
|
2612
|
+
* different questions. The aggregate roster is "what can I point a key at", the
|
|
2613
|
+
* channel list is "what can I scan a QR code into", and mixing them in one poll
|
|
2614
|
+
* would put a third-party directory on the critical path of the pool card.
|
|
2615
|
+
*/
|
|
2616
|
+
const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
|
|
2617
|
+
/**
|
|
2618
|
+
* The Doubao lane's session.
|
|
2619
|
+
*
|
|
2620
|
+
* POST starts an interactive browser sign-in and answers once it lands;
|
|
2621
|
+
* GET reports whether a session is stored; DELETE forgets it.
|
|
2622
|
+
*/
|
|
2623
|
+
const POOL_DOUBAO_SESSION_PATH = "/plugins/dsh-xdpool/doubao/session";
|
|
2624
|
+
/** The Doubao quota: the windows the account has, with their reset countdowns. */
|
|
2625
|
+
const POOL_DOUBAO_QUOTA_PATH = "/plugins/dsh-xdpool/doubao/quota";
|
|
2626
|
+
/** Model menu and persisted selection. */
|
|
2627
|
+
const POOL_DOUBAO_MODELS_PATH = "/plugins/dsh-xdpool/doubao/models";
|
|
2628
|
+
/**
|
|
2629
|
+
* The `reason` the channel document carries when the login-channel route is
|
|
2630
|
+
* already owned by another plugin.
|
|
2631
|
+
*
|
|
2632
|
+
* The pack we vendor is byte-identical to the one the sibling login-channel
|
|
2633
|
+
* build mounts, and both claim the same fetch route; the host has no query for
|
|
2634
|
+
* what is already registered, so the loser of that race can only tell it lost.
|
|
2635
|
+
* Both halves need the same string — the host to say it, the card to choose
|
|
2636
|
+
* between "this host cannot run the channels" and "another plugin already runs
|
|
2637
|
+
* them", which are opposite sentences — so it is declared with the other wire
|
|
2638
|
+
* constants rather than in `channels.ts`, which the browser bundle may not
|
|
2639
|
+
* import for value.
|
|
2640
|
+
*/
|
|
2641
|
+
const ROUTE_OWNED_ELSEWHERE = "already-mounted-elsewhere";
|
|
2642
|
+
/**
|
|
2643
|
+
* The routing chains, and the whole model roster a member may name.
|
|
2644
|
+
*
|
|
2645
|
+
* One route for both because the editor cannot be drawn without the roster: a
|
|
2646
|
+
* member is chosen from a list, and a list of ids with no names, windows or
|
|
2647
|
+
* vendors is a list nobody can pick from. Reading two documents on one panel
|
|
2648
|
+
* open would also mean the roster could be a second older than the chains.
|
|
2642
2649
|
*/
|
|
2643
|
-
|
|
2644
|
-
const SECRET_FILE_MODE = 384;
|
|
2645
|
-
/** Owner-only, for the directory that holds them. */
|
|
2646
|
-
const SECRET_DIR_MODE = 448;
|
|
2650
|
+
const POOL_COMBOS_PATH = "/plugins/dsh-xdpool/combos";
|
|
2647
2651
|
/**
|
|
2648
|
-
*
|
|
2652
|
+
* Replace the whole chain list in one write.
|
|
2649
2653
|
*
|
|
2650
|
-
*
|
|
2651
|
-
*
|
|
2652
|
-
*
|
|
2653
|
-
*
|
|
2654
|
-
*
|
|
2655
|
-
* of failure that only shows up in the packaged app.
|
|
2654
|
+
* A single table replace rather than a per-chain patch: the editor's unit of
|
|
2655
|
+
* intent is "this is my routing table", and deleting one member is
|
|
2656
|
+
* indistinguishable from deleting that member's chain once ids are equal — so a
|
|
2657
|
+
* merge rule would have to guess, and a wrong guess silently resurrects a row the
|
|
2658
|
+
* user deleted.
|
|
2656
2659
|
*/
|
|
2657
|
-
const
|
|
2660
|
+
const POOL_COMBOS_SAVE_PATH = "/plugins/dsh-xdpool/combos/save";
|
|
2658
2661
|
/**
|
|
2659
|
-
*
|
|
2662
|
+
* The LAN relay's own state, and the only way to change it.
|
|
2660
2663
|
*
|
|
2661
|
-
*
|
|
2662
|
-
*
|
|
2663
|
-
*
|
|
2664
|
-
*
|
|
2665
|
-
* worth fixing, and a failure is not worth aborting a save over.
|
|
2664
|
+
* One GET and one POST rather than a separate settings surface, because the relay
|
|
2665
|
+
* is a switch you have to be able to kill from the same card that turns it on —
|
|
2666
|
+
* a relay left listening on a network interface is the one failure here that
|
|
2667
|
+
* keeps mattering after the plugin is closed.
|
|
2666
2668
|
*/
|
|
2667
|
-
|
|
2668
|
-
await mkdir(dir, {
|
|
2669
|
-
recursive: true,
|
|
2670
|
-
...POSIX ? { mode: SECRET_DIR_MODE } : {}
|
|
2671
|
-
});
|
|
2672
|
-
if (!POSIX) return;
|
|
2673
|
-
try {
|
|
2674
|
-
await chmod(dir, SECRET_DIR_MODE);
|
|
2675
|
-
} catch {}
|
|
2676
|
-
}
|
|
2669
|
+
const POOL_RELAY_PATH = "/plugins/dsh-xdpool/relay";
|
|
2677
2670
|
/**
|
|
2678
|
-
*
|
|
2671
|
+
* Read the usage panel's aggregate.
|
|
2679
2672
|
*
|
|
2680
|
-
*
|
|
2681
|
-
*
|
|
2682
|
-
*
|
|
2673
|
+
* GET only, and token-free by construction: the recorder holds counts and
|
|
2674
|
+
* timings, never a prompt. The document type is `UsageSummary` from
|
|
2675
|
+
* `src/stats.ts` rather than a copy declared here, because that module stays
|
|
2676
|
+
* Node-free precisely so the browser half can import the SAME declaration
|
|
2677
|
+
* instead of a second one that could quietly drift.
|
|
2683
2678
|
*/
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2679
|
+
const POOL_USAGE_PATH = "/plugins/dsh-xdpool/usage";
|
|
2680
|
+
/** The five strategies, as a value, so a request body can be validated against it. */
|
|
2681
|
+
const POOL_DISTRIBUTIONS = Object.freeze([
|
|
2682
|
+
"priority",
|
|
2683
|
+
"round-robin",
|
|
2684
|
+
"balanced",
|
|
2685
|
+
"sticky",
|
|
2686
|
+
"expiry"
|
|
2687
|
+
]);
|
|
2688
|
+
/** True when `value` names one of the five documented strategies. */
|
|
2689
|
+
function isDistributionStrategy(value) {
|
|
2690
|
+
return POOL_DISTRIBUTIONS.includes(value);
|
|
2693
2691
|
}
|
|
2694
|
-
// src/ignored.ts
|
|
2695
2692
|
/**
|
|
2696
|
-
* The
|
|
2697
|
-
*
|
|
2698
|
-
* Distinct from `disabledAccountIds`, which is a ROTATION preference. A disabled
|
|
2699
|
-
* account stays on the card, can be switched back on, and its credential keeps
|
|
2700
|
-
* being read on every scan. Ignoring is a statement about the ACCOUNT — "this
|
|
2701
|
-
* one is not mine any more" — so an ignored account is skipped BEFORE its
|
|
2702
|
-
* credential is decrypted, never appears among the pool's accounts, and does not
|
|
2703
|
-
* come back when the desktop app writes a fresh `.info` file for it.
|
|
2693
|
+
* The schedule every automation job falls back to.
|
|
2704
2694
|
*
|
|
2705
|
-
*
|
|
2706
|
-
*
|
|
2707
|
-
*
|
|
2708
|
-
*
|
|
2709
|
-
*
|
|
2695
|
+
* Shared by both halves on purpose. The host uses it when a configured hour
|
|
2696
|
+
* list arrives empty (the settings schema materializes "never configured" into
|
|
2697
|
+
* `[]`), and the card uses it when it writes the `automation` block back, so a
|
|
2698
|
+
* document that already holds an empty list is healed instead of being saved
|
|
2699
|
+
* back as an unrunnable schedule.
|
|
2710
2700
|
*
|
|
2711
|
-
*
|
|
2701
|
+
* This lives here rather than in `scheduler.ts` because the browser half cannot
|
|
2702
|
+
* import the host module: `scheduler.ts` pulls in `node:crypto` and the whole
|
|
2703
|
+
* upstream client, none of which exists in the browser bundle. Two hand-written
|
|
2704
|
+
* copies would drift, and the drift is invisible — the card would write a
|
|
2705
|
+
* schedule the scheduler does not run.
|
|
2712
2706
|
*/
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2707
|
+
const DEFAULT_AUTOMATION_HOURS = {
|
|
2708
|
+
checkin: [9],
|
|
2709
|
+
report: [10],
|
|
2710
|
+
tasks: [11],
|
|
2711
|
+
streak: [12],
|
|
2712
|
+
travel: [9, 21],
|
|
2713
|
+
compensation: [13]
|
|
2714
|
+
};
|
|
2717
2715
|
/**
|
|
2718
|
-
*
|
|
2716
|
+
* Parse one of the server's amount fields.
|
|
2719
2717
|
*
|
|
2720
|
-
*
|
|
2721
|
-
*
|
|
2722
|
-
*
|
|
2718
|
+
* They arrive as formatted strings ("2,100"), and they are the only source of a
|
|
2719
|
+
* percentage for the plans that omit `used_percent`. Returns undefined rather
|
|
2720
|
+
* than NaN so callers can tell "no data" from "zero".
|
|
2723
2721
|
*/
|
|
2724
|
-
function
|
|
2725
|
-
|
|
2726
|
-
if (typeof
|
|
2727
|
-
|
|
2722
|
+
function parseAmount(value) {
|
|
2723
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
2724
|
+
if (typeof value !== "string") return void 0;
|
|
2725
|
+
const digits = value.replace(/[^0-9.]/g, "");
|
|
2726
|
+
if (digits === "") return void 0;
|
|
2727
|
+
const parsed = Number(digits);
|
|
2728
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2728
2729
|
}
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2730
|
+
function mapWindowType(value) {
|
|
2731
|
+
if (value === 1) return "five_hour";
|
|
2732
|
+
if (value === 2) return "weekly";
|
|
2733
|
+
if (value === 3) return "incentive";
|
|
2732
2734
|
}
|
|
2733
|
-
/**
|
|
2734
|
-
|
|
2735
|
-
|
|
2735
|
+
/**
|
|
2736
|
+
* Convert one server window into the shape the UI consumes.
|
|
2737
|
+
*
|
|
2738
|
+
* Three shapes are observed:
|
|
2739
|
+
*
|
|
2740
|
+
* - both timestamps present: a rolling window with a real reset instant;
|
|
2741
|
+
* - both zero: the window has not started yet (Doubao renders
|
|
2742
|
+
* 「开始使用后计时」); the reset instant is unknown and MUST NOT be invented;
|
|
2743
|
+
* - only `end_time`: a promotional grant with an expiry but no start.
|
|
2744
|
+
*
|
|
2745
|
+
* Reconstructing a missing start from the nominal window length used to make
|
|
2746
|
+
* the card count down to a moment the server never sent — off by up to a week.
|
|
2747
|
+
*/
|
|
2748
|
+
function normalizeWindow(raw, label) {
|
|
2749
|
+
const type = raw.window_type === void 0 ? void 0 : mapWindowType(raw.window_type);
|
|
2750
|
+
if (!type) return void 0;
|
|
2751
|
+
const start = raw.start_time ?? 0;
|
|
2752
|
+
const end = raw.end_time ?? 0;
|
|
2753
|
+
const usedAmount = parseAmount(raw.used_amount);
|
|
2754
|
+
const totalAmount = parseAmount(raw.total_amount);
|
|
2755
|
+
const fromAmounts = usedAmount !== void 0 && totalAmount !== void 0 && totalAmount > 0 ? Math.min(100, Math.max(0, usedAmount / totalAmount * 100)) : void 0;
|
|
2756
|
+
const used = typeof raw.used_percent === "number" ? raw.used_percent : fromAmounts ?? 0;
|
|
2757
|
+
const base = {
|
|
2758
|
+
type,
|
|
2759
|
+
windowType: raw.window_type,
|
|
2760
|
+
usedPercent: used,
|
|
2761
|
+
remainingPercent: Math.max(0, 100 - used),
|
|
2762
|
+
...label === void 0 || label === "" ? {} : { label },
|
|
2763
|
+
...usedAmount === void 0 ? {} : { usedAmount },
|
|
2764
|
+
...totalAmount === void 0 ? {} : { totalAmount }
|
|
2765
|
+
};
|
|
2766
|
+
if (end <= 0) return {
|
|
2767
|
+
...base,
|
|
2768
|
+
resetsAt: 0,
|
|
2769
|
+
startedAt: 0,
|
|
2770
|
+
windowMs: 0,
|
|
2771
|
+
resetUnknown: true,
|
|
2772
|
+
startsOnUse: true
|
|
2773
|
+
};
|
|
2774
|
+
return {
|
|
2775
|
+
...base,
|
|
2776
|
+
...start <= 0 ? { startsOnUse: true } : {},
|
|
2777
|
+
resetsAt: end,
|
|
2778
|
+
startedAt: start > 0 ? start : 0,
|
|
2779
|
+
windowMs: start > 0 && end > start ? end - start : 0
|
|
2780
|
+
};
|
|
2736
2781
|
}
|
|
2737
2782
|
/**
|
|
2738
|
-
*
|
|
2783
|
+
* How long a FAILED reading is reused.
|
|
2739
2784
|
*
|
|
2740
|
-
*
|
|
2741
|
-
*
|
|
2742
|
-
*
|
|
2785
|
+
* The quota endpoint is consulted before every chat turn, and a failure used to
|
|
2786
|
+
* be forgotten immediately — so an outage cost every single turn another round
|
|
2787
|
+
* trip that was going to fail the same way, on the request's critical path. The
|
|
2788
|
+
* window is short enough that a recovery is invisible (a turn later) and long
|
|
2789
|
+
* enough to stop that fan-out.
|
|
2743
2790
|
*/
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2791
|
+
const QUOTA_FAILURE_TTL_MS = 3e4;
|
|
2792
|
+
/**
|
|
2793
|
+
* Remember a failed reading, and return it.
|
|
2794
|
+
*
|
|
2795
|
+
* One helper because all three failure exits (no credentials, HTTP error,
|
|
2796
|
+
* thrown) must go through it: a failure that skips the memo is exactly the bug
|
|
2797
|
+
* this exists to prevent.
|
|
2798
|
+
*/
|
|
2799
|
+
function rememberFailure(quota) {
|
|
2800
|
+
cachedFailure = quota;
|
|
2801
|
+
cachedFailureAt = Date.now();
|
|
2802
|
+
return quota;
|
|
2803
|
+
}
|
|
2804
|
+
/**
|
|
2805
|
+
* Only report the account as exhausted when all active quota entitlements say
|
|
2806
|
+
* so: an exhausted promotional bonus must not block turns while the main
|
|
2807
|
+
* window still has headroom.
|
|
2808
|
+
*/
|
|
2809
|
+
function evaluateQuotaExhausted(data) {
|
|
2810
|
+
const hasActiveGroups = (section) => Boolean(section?.window_limit_groups?.some((g) => (g.window_limits?.length ?? 0) > 0));
|
|
2811
|
+
const windowExhausted = data?.window_limit_section?.usage_exhausted;
|
|
2812
|
+
const enterpriseExhausted = data?.enterprise_window_limit_section?.usage_exhausted;
|
|
2813
|
+
const incentiveExhausted = data?.incentive_quota_section?.usage_exhausted;
|
|
2814
|
+
const activeFlags = [];
|
|
2815
|
+
if (typeof windowExhausted === "boolean") activeFlags.push(windowExhausted);
|
|
2816
|
+
if (typeof enterpriseExhausted === "boolean" && hasActiveGroups(data?.enterprise_window_limit_section)) activeFlags.push(enterpriseExhausted);
|
|
2817
|
+
if (typeof incentiveExhausted === "boolean" && hasActiveGroups(data?.incentive_quota_section)) activeFlags.push(incentiveExhausted);
|
|
2818
|
+
const fallbackFlags = [
|
|
2819
|
+
windowExhausted,
|
|
2820
|
+
enterpriseExhausted,
|
|
2821
|
+
incentiveExhausted
|
|
2822
|
+
].filter((flag) => typeof flag === "boolean");
|
|
2823
|
+
const flags = activeFlags.length > 0 ? activeFlags : fallbackFlags;
|
|
2824
|
+
return flags.length > 0 && flags.every(Boolean);
|
|
2825
|
+
}
|
|
2826
|
+
async function fetchQuota(options = {}) {
|
|
2827
|
+
const now = Date.now();
|
|
2828
|
+
if (!options.force && cached && now - cached.fetchedAt < 3e5) return cached;
|
|
2829
|
+
if (!options.force && cachedFailure !== void 0 && now - cachedFailureAt < QUOTA_FAILURE_TTL_MS) return cachedFailure;
|
|
2830
|
+
/**
|
|
2831
|
+
* No session is a quotable answer, not a throw.
|
|
2832
|
+
*
|
|
2833
|
+
* The quota panel sits beside the chat card, and a user who has not signed in yet still
|
|
2834
|
+
* needs to SEE it — with "not signed in" in the error field — rather than have the panel
|
|
2835
|
+
* disappear or the card throw on render.
|
|
2836
|
+
*/
|
|
2837
|
+
let credentials;
|
|
2838
|
+
try {
|
|
2839
|
+
credentials = requireDoubaoCredentials();
|
|
2840
|
+
} catch (error) {
|
|
2841
|
+
return rememberFailure({
|
|
2842
|
+
exhausted: false,
|
|
2843
|
+
windows: [],
|
|
2844
|
+
fetchedAt: now,
|
|
2845
|
+
error: error instanceof Error ? error.message : "Doubao credentials unavailable."
|
|
2762
2846
|
});
|
|
2763
2847
|
}
|
|
2764
|
-
return out;
|
|
2765
|
-
}
|
|
2766
|
-
/**
|
|
2767
|
-
* Read the ignore list, tolerating every "no list yet" shape.
|
|
2768
|
-
*
|
|
2769
|
-
* A missing file, unreadable file, or invalid JSON all mean the same thing to
|
|
2770
|
-
* the caller — nothing is ignored — so none of them throws. The pool must be
|
|
2771
|
-
* able to start on a machine that has never ignored anything.
|
|
2772
|
-
*/
|
|
2773
|
-
async function readIgnoredAccounts(path = ignoredIdsPath()) {
|
|
2774
2848
|
try {
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2849
|
+
const response = await fetch(buildQueryUrl(QUOTA_ENDPOINT, credentials.pairs.get("msToken")), {
|
|
2850
|
+
method: "POST",
|
|
2851
|
+
headers: buildHeaders(credentials, { "content-type": "application/json" }),
|
|
2852
|
+
body: JSON.stringify({ product_line: "membership" })
|
|
2853
|
+
});
|
|
2854
|
+
if (!response.ok) return rememberFailure({
|
|
2855
|
+
exhausted: false,
|
|
2856
|
+
windows: [],
|
|
2857
|
+
fetchedAt: now,
|
|
2858
|
+
error: `HTTP ${response.status}`
|
|
2859
|
+
});
|
|
2860
|
+
const payload = await response.json();
|
|
2861
|
+
const sections = [payload.data?.window_limit_section, payload.data?.incentive_quota_section];
|
|
2862
|
+
const windows = [];
|
|
2863
|
+
for (const section of sections) for (const group of section?.window_limit_groups ?? []) for (const limit of group.window_limits ?? []) {
|
|
2864
|
+
const normalized = normalizeWindow(limit, group.feature_group_name);
|
|
2865
|
+
if (normalized) windows.push(normalized);
|
|
2866
|
+
}
|
|
2867
|
+
const quota = {
|
|
2868
|
+
exhausted: evaluateQuotaExhausted(payload.data),
|
|
2869
|
+
windows,
|
|
2870
|
+
fetchedAt: now
|
|
2871
|
+
};
|
|
2872
|
+
const plan = payload.data?.current_subscription?.display?.short_name;
|
|
2873
|
+
if (plan) quota.plan = plan;
|
|
2874
|
+
if (payload.data?.member_info?.hasActiveSubscription !== void 0) quota.planActive = payload.data.member_info.hasActiveSubscription;
|
|
2875
|
+
cached = quota;
|
|
2876
|
+
cachedFailure = void 0;
|
|
2877
|
+
return quota;
|
|
2878
|
+
} catch (error) {
|
|
2879
|
+
return rememberFailure({
|
|
2880
|
+
exhausted: false,
|
|
2881
|
+
windows: [],
|
|
2882
|
+
fetchedAt: now,
|
|
2883
|
+
error: error.message
|
|
2884
|
+
});
|
|
2778
2885
|
}
|
|
2779
2886
|
}
|
|
2887
|
+
let cached;
|
|
2888
|
+
/** The last FAILED reading, reused for {@link QUOTA_FAILURE_TTL_MS}. */
|
|
2889
|
+
let cachedFailure;
|
|
2890
|
+
let cachedFailureAt = 0;
|
|
2891
|
+
// src/doubao-routes.ts
|
|
2892
|
+
/** Write a JSON response. */
|
|
2893
|
+
function json$1(res, status, body) {
|
|
2894
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
2895
|
+
res.end(JSON.stringify(body));
|
|
2896
|
+
}
|
|
2780
2897
|
/**
|
|
2781
|
-
*
|
|
2898
|
+
* Whether the request came from the host's own page.
|
|
2782
2899
|
*
|
|
2783
|
-
*
|
|
2784
|
-
*
|
|
2785
|
-
* the
|
|
2786
|
-
*
|
|
2787
|
-
*
|
|
2900
|
+
* An ABSENT `Origin` is allowed and is the common case: only cross-origin requests carry the
|
|
2901
|
+
* header, so a same-origin request from the card sends none. Requiring it refused every call
|
|
2902
|
+
* the UI made — the paste arrived, was rejected `403` before any parsing ran, and the card
|
|
2903
|
+
* reported it as a bad cookie. A page in the user's browser driving this endpoint is
|
|
2904
|
+
* cross-origin by construction and always sends `Origin`, so the hostname check covers it.
|
|
2788
2905
|
*/
|
|
2789
|
-
function
|
|
2906
|
+
function loopbackOrigin$1(req) {
|
|
2907
|
+
const origin = req.headers.origin;
|
|
2908
|
+
if (typeof origin !== "string" || origin === "") return true;
|
|
2790
2909
|
try {
|
|
2791
|
-
|
|
2910
|
+
const url = new URL(origin);
|
|
2911
|
+
return url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
|
|
2792
2912
|
} catch {
|
|
2793
|
-
return
|
|
2913
|
+
return false;
|
|
2794
2914
|
}
|
|
2795
2915
|
}
|
|
2796
2916
|
/**
|
|
2797
|
-
*
|
|
2798
|
-
*
|
|
2799
|
-
* Written to a sibling temp file and renamed over the target so a crash (or a
|
|
2800
|
-
* concurrent reader) can never observe a half-written document — the ignore
|
|
2801
|
-
* list is the only thing standing between a dead account and the rotation, and
|
|
2802
|
-
* a truncated file reads as "nothing is ignored", which would quietly put every
|
|
2803
|
-
* discarded account back in the pool.
|
|
2804
|
-
*/
|
|
2805
|
-
async function writeIgnoredAccounts(accounts, path = ignoredIdsPath()) {
|
|
2806
|
-
const payload = JSON.stringify({
|
|
2807
|
-
version: 1,
|
|
2808
|
-
accounts
|
|
2809
|
-
}, null, 2);
|
|
2810
|
-
await ensureSecretDir(dirname(path));
|
|
2811
|
-
const temp = `${path}.tmp`;
|
|
2812
|
-
await writeSecretFile(temp, `${payload}\n`);
|
|
2813
|
-
await rename(temp, path);
|
|
2814
|
-
}
|
|
2815
|
-
/**
|
|
2816
|
-
* Add one account to the ignore list, preserving the rest.
|
|
2917
|
+
* Mount the Doubao routes.
|
|
2817
2918
|
*
|
|
2818
|
-
*
|
|
2819
|
-
*
|
|
2820
|
-
* whole list from a stale view would drop the other side's edits.
|
|
2919
|
+
* The sign-in route answers `signedIn: false` rather than an error when the user closes the
|
|
2920
|
+
* window: "did not finish signing in" is an ordinary state, and the card says so.
|
|
2821
2921
|
*/
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2922
|
+
function registerDoubaoRoutes(ctx, deps) {
|
|
2923
|
+
ctx.effect(() => {
|
|
2924
|
+
const disposeSession = ctx.webServer.register({
|
|
2925
|
+
kind: "exact",
|
|
2926
|
+
path: POOL_DOUBAO_SESSION_PATH,
|
|
2927
|
+
handler: async (req, res) => {
|
|
2928
|
+
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2929
|
+
try {
|
|
2930
|
+
if (req.method === "DELETE") {
|
|
2931
|
+
deps.clear();
|
|
2932
|
+
setDoubaoSession(void 0);
|
|
2933
|
+
return json$1(res, 200, {
|
|
2934
|
+
ok: true,
|
|
2935
|
+
signedIn: false
|
|
2936
|
+
});
|
|
2937
|
+
}
|
|
2938
|
+
if (req.method === "POST") {
|
|
2939
|
+
/**
|
|
2940
|
+
* Start an interactive sign-in, and answer when it lands or times out.
|
|
2941
|
+
*
|
|
2942
|
+
* The window stays open for the whole budget: a QR scan plus a phone confirmation
|
|
2943
|
+
* is a minute of a person's time, and cutting it short would make the lane look
|
|
2944
|
+
* broken to anyone who was simply slower than the timer.
|
|
2945
|
+
*/
|
|
2946
|
+
const result = await browserLogin();
|
|
2947
|
+
if (!result.ok || result.session === void 0) return json$1(res, 200, {
|
|
2948
|
+
ok: false,
|
|
2949
|
+
signedIn: false,
|
|
2950
|
+
message: result.reason ?? "登录失败"
|
|
2951
|
+
});
|
|
2952
|
+
deps.save(result.session);
|
|
2953
|
+
setDoubaoSession(result.session);
|
|
2954
|
+
return json$1(res, 200, {
|
|
2955
|
+
ok: true,
|
|
2956
|
+
signedIn: true,
|
|
2957
|
+
message: "登录成功,会话已保存"
|
|
2958
|
+
});
|
|
2959
|
+
}
|
|
2960
|
+
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2961
|
+
const stored = deps.session();
|
|
2962
|
+
return json$1(res, 200, {
|
|
2963
|
+
ok: true,
|
|
2964
|
+
signedIn: sessionUsable(stored),
|
|
2965
|
+
...stored?.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
|
|
2966
|
+
});
|
|
2967
|
+
} catch (error) {
|
|
2968
|
+
return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
});
|
|
2972
|
+
const disposeQuota = ctx.webServer.register({
|
|
2973
|
+
kind: "exact",
|
|
2974
|
+
path: POOL_DOUBAO_QUOTA_PATH,
|
|
2975
|
+
handler: async (req, res) => {
|
|
2976
|
+
if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
2977
|
+
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
2978
|
+
const session = deps.session();
|
|
2979
|
+
if (session === void 0 || !sessionUsable(session)) return json$1(res, 200, {
|
|
2980
|
+
ok: false,
|
|
2981
|
+
signedIn: false,
|
|
2982
|
+
windows: []
|
|
2983
|
+
});
|
|
2984
|
+
try {
|
|
2985
|
+
setDoubaoSession(session);
|
|
2986
|
+
const quota = await fetchQuota({ force: true });
|
|
2987
|
+
return json$1(res, 200, {
|
|
2988
|
+
ok: quota.error === void 0,
|
|
2989
|
+
signedIn: true,
|
|
2990
|
+
exhausted: quota.exhausted,
|
|
2991
|
+
...quota.error === void 0 ? {} : { error: quota.error },
|
|
2992
|
+
windows: quota.windows
|
|
2993
|
+
});
|
|
2994
|
+
} catch (error) {
|
|
2995
|
+
return json$1(res, 200, {
|
|
2996
|
+
ok: false,
|
|
2997
|
+
signedIn: true,
|
|
2998
|
+
windows: [],
|
|
2999
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3000
|
+
});
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
});
|
|
3004
|
+
const disposeModels = ctx.webServer.register({
|
|
3005
|
+
kind: "exact",
|
|
3006
|
+
path: POOL_DOUBAO_MODELS_PATH,
|
|
3007
|
+
handler: async (req, res) => {
|
|
3008
|
+
if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
|
|
3009
|
+
try {
|
|
3010
|
+
await deps.models.ready;
|
|
3011
|
+
if (req.method === "PUT") {
|
|
3012
|
+
let raw = "";
|
|
3013
|
+
for await (const chunk of req) {
|
|
3014
|
+
raw += String(chunk);
|
|
3015
|
+
if (raw.length > 16384) return json$1(res, 413, { error: "模型选择数据过大" });
|
|
3016
|
+
}
|
|
3017
|
+
const ids = JSON.parse(raw)?.disabled;
|
|
3018
|
+
if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) return json$1(res, 400, { error: "模型选择无效" });
|
|
3019
|
+
const allowed = /* @__PURE__ */ new Set([...deps.models.catalog().map((model) => model.id), ...deps.models.store.disabledIds()]);
|
|
3020
|
+
if (ids.some((id) => !allowed.has(id))) return json$1(res, 400, { error: "模型选择包含未知模型" });
|
|
3021
|
+
await deps.models.store.setDisabled(ids);
|
|
3022
|
+
deps.models.changed();
|
|
3023
|
+
} else if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
|
|
3024
|
+
return json$1(res, 200, {
|
|
3025
|
+
ok: true,
|
|
3026
|
+
disabledIds: deps.models.store.disabledIds(),
|
|
3027
|
+
models: deps.models.catalog().map((model) => ({
|
|
3028
|
+
...model,
|
|
3029
|
+
enabled: deps.models.store.isEnabled(model.id)
|
|
3030
|
+
}))
|
|
3031
|
+
});
|
|
3032
|
+
} catch (error) {
|
|
3033
|
+
return json$1(res, 500, { error: error instanceof Error ? error.message : "读取模型失败" });
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
});
|
|
3037
|
+
return () => {
|
|
3038
|
+
disposeSession();
|
|
3039
|
+
disposeQuota();
|
|
3040
|
+
disposeModels();
|
|
3041
|
+
};
|
|
3042
|
+
});
|
|
2839
3043
|
}
|
|
2840
3044
|
// src/doubao-store.ts
|
|
2841
3045
|
/**
|
|
@@ -3675,8 +3879,20 @@ function contentOfFrame(frame) {
|
|
|
3675
3879
|
* Body markers win over status, because the upstream reuses 400/200 for
|
|
3676
3880
|
* several distinct conditions.
|
|
3677
3881
|
*/
|
|
3882
|
+
/** Business codes the gateway uses for "this account is risk-flagged". */
|
|
3883
|
+
const RISK_BLOCK_CODES = ["11140", "11141"];
|
|
3678
3884
|
function classifyUpstreamError(status, body) {
|
|
3679
3885
|
if (status === 402) return "hard_credit";
|
|
3886
|
+
/**
|
|
3887
|
+
* Risk control first, and only for a 403.
|
|
3888
|
+
*
|
|
3889
|
+
* `11140` is what the gateway returns when the ACCOUNT is flagged. It arrives with 403, so
|
|
3890
|
+
* the blanket rule below swallowed it into `session_dead` and the card told the user their
|
|
3891
|
+
* key was invalid — several times, since re-signing in changes nothing about a flag.
|
|
3892
|
+
*/
|
|
3893
|
+
if (status === 403) {
|
|
3894
|
+
for (const code of RISK_BLOCK_CODES) if (new RegExp(`"code"\\s*:\\s*"?${code}"?(?=\\s*[,}])`, "u").test(body)) return "risk_blocked";
|
|
3895
|
+
}
|
|
3680
3896
|
if (status === 401 || status === 403) return "session_dead";
|
|
3681
3897
|
const lower = body.toLowerCase();
|
|
3682
3898
|
for (const code of HARD_CREDIT_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "hard_credit";
|
|
@@ -22843,11 +23059,14 @@ function createChannelLane(options) {
|
|
|
22843
23059
|
const { llm, providers, toId, attachments, onRows, logger } = options;
|
|
22844
23060
|
const cache = /* @__PURE__ */ new Map();
|
|
22845
23061
|
const inflight = /* @__PURE__ */ new Map();
|
|
23062
|
+
const generations = /* @__PURE__ */ new Map();
|
|
23063
|
+
let rosterGeneration = 0;
|
|
22846
23064
|
const fetchRows = (channel) => {
|
|
22847
23065
|
const hit = cache.get(channel);
|
|
22848
23066
|
if (hit !== void 0 && Date.now() - hit.at < LISTING_TTL_MS) return Promise.resolve(hit.rows);
|
|
22849
23067
|
const running = inflight.get(channel);
|
|
22850
23068
|
if (running !== void 0) return running;
|
|
23069
|
+
const generation = generations.get(channel) ?? 0;
|
|
22851
23070
|
const tracked = llm.listModels(channel).then((models) => Promise.all(models.map(async (model) => {
|
|
22852
23071
|
let supportedEfforts;
|
|
22853
23072
|
let supportsImages;
|
|
@@ -22872,21 +23091,32 @@ function createChannelLane(options) {
|
|
|
22872
23091
|
logger?.warn?.(`heybash-xdpool: channel ${channel} listed no models: ${String(error)}`);
|
|
22873
23092
|
return [];
|
|
22874
23093
|
}).then((rows) => {
|
|
22875
|
-
cache.set(channel, {
|
|
23094
|
+
if ((generations.get(channel) ?? 0) === generation) cache.set(channel, {
|
|
22876
23095
|
at: Date.now(),
|
|
22877
23096
|
rows
|
|
22878
23097
|
});
|
|
22879
|
-
inflight.delete(channel);
|
|
23098
|
+
if (inflight.get(channel) === tracked) inflight.delete(channel);
|
|
22880
23099
|
return rows;
|
|
22881
23100
|
});
|
|
22882
23101
|
inflight.set(channel, tracked);
|
|
22883
23102
|
return tracked;
|
|
22884
23103
|
};
|
|
22885
23104
|
return {
|
|
23105
|
+
invalidate: (channel) => {
|
|
23106
|
+
rosterGeneration += 1;
|
|
23107
|
+
generations.set(channel, (generations.get(channel) ?? 0) + 1);
|
|
23108
|
+
cache.delete(channel);
|
|
23109
|
+
inflight.delete(channel);
|
|
23110
|
+
},
|
|
22886
23111
|
rows: async () => {
|
|
22887
|
-
|
|
22888
|
-
|
|
22889
|
-
|
|
23112
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
23113
|
+
const revision = rosterGeneration;
|
|
23114
|
+
const rows = (await Promise.all(providers().map(fetchRows))).flat();
|
|
23115
|
+
if (revision !== rosterGeneration) continue;
|
|
23116
|
+
await onRows?.(rows);
|
|
23117
|
+
return rows;
|
|
23118
|
+
}
|
|
23119
|
+
throw new Error("channel model list changed while refreshing");
|
|
22890
23120
|
},
|
|
22891
23121
|
resolve: (id) => {
|
|
22892
23122
|
const separator = id.indexOf(":");
|
|
@@ -23169,6 +23399,7 @@ const KIND_STATUS = {
|
|
|
23169
23399
|
hard_credit: 402,
|
|
23170
23400
|
soft_rate: 429,
|
|
23171
23401
|
session_dead: 401,
|
|
23402
|
+
risk_blocked: 403,
|
|
23172
23403
|
not_found: 502,
|
|
23173
23404
|
server: 502,
|
|
23174
23405
|
client: 400
|
|
@@ -24091,6 +24322,7 @@ function createWorkBuddyShim(options) {
|
|
|
24091
24322
|
};
|
|
24092
24323
|
if (result.kind === "soft_rate") pool.penalize(account.id, parseRateLimitReset(result.message), member.modelId);
|
|
24093
24324
|
else if (result.kind === "session_dead") pool.penalizeCredentialDead(account.id);
|
|
24325
|
+
else if (result.kind === "risk_blocked") pool.penalize(account.id, Date.now() + 18e5);
|
|
24094
24326
|
else if (result.kind === "hard_credit") pool.penalizeExhausted(account.id);
|
|
24095
24327
|
noteSwitch(member.modelId, result.kind, result.status);
|
|
24096
24328
|
continue;
|
|
@@ -24321,6 +24553,11 @@ function createWorkBuddyShim(options) {
|
|
|
24321
24553
|
}
|
|
24322
24554
|
continue;
|
|
24323
24555
|
}
|
|
24556
|
+
if (result.kind === "risk_blocked") {
|
|
24557
|
+
pool.penalize(account.id, Date.now() + 18e5);
|
|
24558
|
+
logger?.warn(`heybash-xdpool: ${account.label} is risk-blocked; cooling the account and rotating`);
|
|
24559
|
+
continue;
|
|
24560
|
+
}
|
|
24324
24561
|
if (result.kind === "hard_credit") {
|
|
24325
24562
|
pool.penalizeExhausted(account.id);
|
|
24326
24563
|
logger?.warn(`heybash-xdpool: ${account.label} has no credits left (attempt ${attempt + 1}/${maxAttempts}); rotating`);
|
|
@@ -24701,6 +24938,10 @@ async function recoverFromContextOverrun(options) {
|
|
|
24701
24938
|
pool.penalizeExhausted(account.id);
|
|
24702
24939
|
continue;
|
|
24703
24940
|
}
|
|
24941
|
+
if (result.kind === "risk_blocked") {
|
|
24942
|
+
pool.penalize(account.id, Date.now() + 18e5);
|
|
24943
|
+
continue;
|
|
24944
|
+
}
|
|
24704
24945
|
if (result.kind === "soft_rate") {
|
|
24705
24946
|
pool.penalize(account.id, parseRateLimitReset(result.message), modelId);
|
|
24706
24947
|
continue;
|
|
@@ -26573,6 +26814,7 @@ function apply(ctx, config = {}) {
|
|
|
26573
26814
|
let doubaoSession;
|
|
26574
26815
|
let doubaoAdapterHandle;
|
|
26575
26816
|
let doubaoSessionRevision = 0;
|
|
26817
|
+
let invalidateDoubaoLane;
|
|
26576
26818
|
/** Point every reader at a session: the lane, and the upstream's own holder. */
|
|
26577
26819
|
const adoptDoubaoSession = (session) => {
|
|
26578
26820
|
doubaoSessionRevision += 1;
|
|
@@ -26581,6 +26823,7 @@ function apply(ctx, config = {}) {
|
|
|
26581
26823
|
try {
|
|
26582
26824
|
doubaoAdapterHandle?.replace([DOUBAO_PROVIDER_ID]);
|
|
26583
26825
|
} catch {}
|
|
26826
|
+
invalidateDoubaoLane?.();
|
|
26584
26827
|
};
|
|
26585
26828
|
/**
|
|
26586
26829
|
* Restore the session written by an earlier run.
|
|
@@ -26594,7 +26837,13 @@ function apply(ctx, config = {}) {
|
|
|
26594
26837
|
readStoredSession().then((stored) => {
|
|
26595
26838
|
if (stored !== void 0 && doubaoSessionRevision === restoreRevision) adoptDoubaoSession(stored);
|
|
26596
26839
|
});
|
|
26597
|
-
const
|
|
26840
|
+
const doubaoModelStore = new DoubaoModelStore();
|
|
26841
|
+
const doubaoModelsReady = doubaoModelStore.load();
|
|
26842
|
+
doubaoModelsReady.catch((error) => ctx.logger.warn("heybash-xdpool: could not load Doubao model selection", error));
|
|
26843
|
+
const doubaoLlm = new DoubaoAdapter(() => doubaoSession, {
|
|
26844
|
+
ready: doubaoModelsReady,
|
|
26845
|
+
store: doubaoModelStore
|
|
26846
|
+
});
|
|
26598
26847
|
const hostLlm = ctx.llm;
|
|
26599
26848
|
const channelLane = createChannelLane({
|
|
26600
26849
|
llm: {
|
|
@@ -26627,6 +26876,10 @@ function apply(ctx, config = {}) {
|
|
|
26627
26876
|
attachments: () => ctx.get("attachments"),
|
|
26628
26877
|
logger: ctx.logger
|
|
26629
26878
|
});
|
|
26879
|
+
invalidateDoubaoLane = () => {
|
|
26880
|
+
channelLane.invalidate(DOUBAO_LANE_CHANNEL);
|
|
26881
|
+
channelLane.rows().catch((error) => ctx.logger.warn("heybash-xdpool: could not refresh Doubao model list", error));
|
|
26882
|
+
};
|
|
26630
26883
|
/**
|
|
26631
26884
|
* The gateway allowlist, re-read per request.
|
|
26632
26885
|
*
|
|
@@ -26803,6 +27056,18 @@ function apply(ctx, config = {}) {
|
|
|
26803
27056
|
*/
|
|
26804
27057
|
registerDoubaoRoutes(webCtx, {
|
|
26805
27058
|
session: () => doubaoSession,
|
|
27059
|
+
models: {
|
|
27060
|
+
ready: doubaoModelsReady,
|
|
27061
|
+
store: doubaoModelStore,
|
|
27062
|
+
catalog: doubaoModelCatalog,
|
|
27063
|
+
changed: () => {
|
|
27064
|
+
channelLane.invalidate(DOUBAO_LANE_CHANNEL);
|
|
27065
|
+
try {
|
|
27066
|
+
doubaoAdapterHandle?.replace([DOUBAO_PROVIDER_ID]);
|
|
27067
|
+
} catch {}
|
|
27068
|
+
channelLane.rows().catch((error) => ctx.logger.warn("heybash-xdpool: could not refresh Doubao model list", error));
|
|
27069
|
+
}
|
|
27070
|
+
},
|
|
26806
27071
|
save: (session) => {
|
|
26807
27072
|
adoptDoubaoSession(session);
|
|
26808
27073
|
writeStoredSession(session);
|