dsh-xdpool 2.7.1 → 2.7.3

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/lib/index.js CHANGED
@@ -3,13 +3,13 @@ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
3
3
  import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, truncateSync, writeFileSync } from "node:fs";
4
4
  import { homedir, hostname, tmpdir } from "node:os";
5
5
  import { basename, dirname, join, resolve } from "node:path";
6
- import crypto, { createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
6
+ import crypto$1, { createDecipheriv, createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
+ import { LlmAdapter, LlmError, ReasoningEffortId, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
7
8
  import { chmod, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
8
9
  import z from "@deepseek-ai/schemastery";
9
10
  import { fileURLToPath, pathToFileURL } from "node:url";
10
11
  import { createProvider } from "@earendil-works/pi-ai";
11
12
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
12
- import { resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
13
13
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
14
14
  import { env } from "node:process";
15
15
  import http, { createServer, request } from "node:http";
@@ -76,19 +76,44 @@ function browserProfileDir() {
76
76
  }
77
77
  /** The port the sign-in browser listens on. Unusual enough to avoid a real session. */
78
78
  const DEBUG_PORT = 9333;
79
- /** Browsers that can be driven, in the order they are preferred. */
80
- const CANDIDATES = [
79
+ /**
80
+ * Browsers this can drive, and where they actually live.
81
+ *
82
+ * EVERY Chromium-based browser speaks the same DevTools protocol, so this is not "Chrome
83
+ * only". Edge ships with Windows, and users install Chrome, Brave, Vivaldi and Chromium into
84
+ * their own profile directory rather than into `Program Files` — a user who has one of those
85
+ * but not a machine-wide Chrome was told "no browser found", which reads as a broken feature.
86
+ *
87
+ * The per-user entries matter most: a machine-wide install needs administrator rights, so the
88
+ * browser a normal user actually has is often under `%LOCALAPPDATA%`.
89
+ */
90
+ const MACHINE_BROWSERS = [
81
91
  "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
82
92
  "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
83
93
  "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
84
- "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
94
+ "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
95
+ "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe",
96
+ "C:\\Program Files\\Vivaldi\\Application\\vivaldi.exe"
97
+ ];
98
+ /** Per-user install locations, which the machine-wide list above cannot know about. */
99
+ const PER_USER_BROWSERS = [
100
+ "Google\\Chrome\\Application\\chrome.exe",
101
+ "Microsoft\\Edge\\Application\\msedge.exe",
102
+ "BraveSoftware\\Brave-Browser\\Application\\brave.exe",
103
+ "Vivaldi\\Application\\vivaldi.exe"
85
104
  ];
86
- /** The first installed browser, or undefined. */
105
+ /**
106
+ * The first driveable browser, or undefined.
107
+ *
108
+ * Machine-wide installs are tried first because that is the common case on a work machine;
109
+ * per-user installs are the fallback, and they are what a user without administrator rights
110
+ * will have.
111
+ */
87
112
  function findBrowser() {
88
- for (const candidate of CANDIDATES) if (existsSync(candidate)) return candidate;
113
+ for (const candidate of MACHINE_BROWSERS) if (existsSync(candidate)) return candidate;
89
114
  const local = process.env["LOCALAPPDATA"];
90
- if (local !== void 0) for (const name of ["Google\\Chrome\\Application\\chrome.exe", "Microsoft\\Edge\\Application\\msedge.exe"]) {
91
- const path = join(local, name);
115
+ if (local !== void 0) for (const relative of PER_USER_BROWSERS) {
116
+ const path = join(local, relative);
92
117
  if (existsSync(path)) return path;
93
118
  }
94
119
  }
@@ -104,6 +129,28 @@ function cookieHeader(session) {
104
129
  }
105
130
  /** The client version the reference implementation was measured against. */
106
131
  const DOUBAO_VERSION$1 = "2.31.4";
132
+ /**
133
+ * The headers that make an external request indistinguishable from the app's.
134
+ *
135
+ * `extra` is applied last so a caller can override the cookie header for a specific turn.
136
+ */
137
+ function buildHeaders$1(session, extra = {}) {
138
+ return {
139
+ "User-Agent": session.userAgent,
140
+ Referer: "chrome://doubao-chat/",
141
+ accept: "*/*",
142
+ "accept-language": "zh-CN,zh;q=0.9",
143
+ "sec-ch-ua": "\"Chromium\";v=\"147\", \"Not.A/Brand\";v=\"8\"",
144
+ "sec-ch-ua-mobile": "?0",
145
+ "sec-ch-ua-platform": "\"Windows\"",
146
+ "sec-fetch-dest": "empty",
147
+ "sec-fetch-mode": "cors",
148
+ "sec-fetch-site": "same-origin",
149
+ "agw-js-conv": "str",
150
+ cookie: cookieHeader(session),
151
+ ...extra
152
+ };
153
+ }
107
154
  /** Sleep for a moment without pulling in a helper. */
108
155
  function sleep$2(ms) {
109
156
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -214,6 +261,20 @@ function terminate(child) {
214
261
  */
215
262
  async function browserLogin(options = {}) {
216
263
  const say = options.onProgress ?? (() => {});
264
+ /**
265
+ * A SIGN-IN WINDOW OF OUR OWN, and that is the arrangement the reference implementation
266
+ * uses for the same reason.
267
+ *
268
+ * The other channels in this plugin return a `loginUrl` and let the page call
269
+ * `window.open`, so their buttons always produce a window — the browser is the user's own
270
+ * default. Doubao cannot use that door: a window opened that way has no debugging port, so
271
+ * the cookies it collects cannot be read, and the session is lost the moment the tab
272
+ * closes.
273
+ *
274
+ * So the window is started here, with a dedicated profile the user's own browser never
275
+ * touches, and the debugging port is what makes the result readable. Nothing is asked of
276
+ * the user beyond signing in once.
277
+ */
217
278
  const exe = findBrowser();
218
279
  if (exe === void 0) return {
219
280
  ok: false,
@@ -578,18 +639,503 @@ const DOUBAO_MODELS = [
578
639
  reasoning: true
579
640
  }
580
641
  ];
581
- /** The listing rows the card and the lane both show. */
582
- function doubaoListing() {
583
- return DOUBAO_MODELS.map((model) => {
584
- const parts = [];
585
- if (model.badge !== void 0 && model.badge !== "") parts.push(model.badge);
586
- if (model.reasoning === true) parts.push("推理");
587
- return {
588
- id: model.id,
589
- name: model.name,
590
- ...parts.length === 0 ? {} : { description: parts.join(" · ") }
591
- };
642
+ //#endregion
643
+ //#region src/doubao-client-cache.ts
644
+ /**
645
+ * The full Doubao model menu, read from the desktop client's own cache.
646
+ *
647
+ * WHY THE WEB CATALOGUE IS SHORT
648
+ *
649
+ * `brief_list` answers with feature ENTRIES (writing, images, video…) and none of the model
650
+ * keys, so a session alone yields the six models that are measured to work. The account can
651
+ * use more — Doubao publishes third-party models as `person-*` slugs (DeepSeek, Kimi, GLM),
652
+ * and the desktop client knows all of them.
653
+ *
654
+ * WHERE IT KEEPS THEM
655
+ *
656
+ * The client caches the menu in its Chromium profile:
657
+ *
658
+ * %LOCALAPPDATA%/Doubao/User Data/Default/IndexedDB/chrome_doubao-launcher_0.indexeddb.leveldb
659
+ *
660
+ * A LevelDB store, so there is no key to look up without the library — but the records are
661
+ * plain V8-serialised blobs, and the model entries sit at `model_item_key` followed by the
662
+ * display `name`. Scanning the log files for that sequence is what the reference
663
+ * implementation does, and it is what this does too.
664
+ *
665
+ * WHEN IT IS ABSENT
666
+ *
667
+ * Nothing guarantees the desktop client is installed or has ever run. A missing directory is
668
+ * the ordinary case on a machine that only uses the web product, and it must not be reported
669
+ * as a failure — the six measured models are still there.
670
+ *
671
+ * @module dsh-xdpool/doubao-client-cache
672
+ */
673
+ /** The cache stores that carry the menu, newest first. */
674
+ const CACHE_DB_DIRS = ["chrome_doubao-launcher_0.indexeddb.leveldb", "chrome_doubao-chat_0.indexeddb.leveldb"];
675
+ /** Where the client keeps its Chromium profile. */
676
+ function userDataDirs() {
677
+ const out = [];
678
+ const local = process.env["LOCALAPPDATA"];
679
+ if (local !== void 0) out.push(join(local, "Doubao", "User Data"));
680
+ const roaming = process.env["APPDATA"];
681
+ if (roaming !== void 0) out.push(join(roaming, "Doubao"));
682
+ return out;
683
+ }
684
+ /** Every cache directory that exists. */
685
+ function cacheDirs() {
686
+ const found = [];
687
+ const seen = /* @__PURE__ */ new Set();
688
+ for (const base of userDataDirs()) for (const db of CACHE_DB_DIRS) {
689
+ const full = join(base, "Default", "IndexedDB", db);
690
+ const key = full.toLowerCase();
691
+ if (!seen.has(key) && existsSync(full)) {
692
+ seen.add(key);
693
+ found.push(full);
694
+ }
695
+ }
696
+ return found;
697
+ }
698
+ /** Read a LEB128 varint. Returns [value, nextOffset] or undefined. */
699
+ function readVarint(buf, at) {
700
+ let result = 0;
701
+ let pos = at;
702
+ let bytes = 0;
703
+ for (;;) {
704
+ if (pos >= buf.length) return void 0;
705
+ const byte = buf[pos];
706
+ if (byte === void 0) return void 0;
707
+ result |= (byte & 127) << 7 * bytes;
708
+ pos += 1;
709
+ bytes += 1;
710
+ if ((byte & 128) === 0) break;
711
+ if (bytes > 4) return void 0;
712
+ }
713
+ return [result >>> 0, pos];
714
+ }
715
+ /** Read a structured-clone string at `at`. Returns [value, nextOffset]. */
716
+ function readV8String(buf, at) {
717
+ const tag = buf[at];
718
+ const sized = readVarint(buf, at + 1);
719
+ if (sized === void 0) return void 0;
720
+ const [length, dataAt] = sized;
721
+ const end = dataAt + length;
722
+ if (length <= 0 || end > buf.length) return void 0;
723
+ if (tag === 34) return [buf.subarray(dataAt, end).toString("latin1"), end];
724
+ if (tag === 99) return [buf.subarray(dataAt, end).toString("utf16le"), end];
725
+ }
726
+ /** Find the `name` property following `from` and decode its value. */
727
+ function readNameAfter(buf, from, to) {
728
+ for (let i = from; i < to - 6; i++) {
729
+ if (buf[i] !== 34) continue;
730
+ const sized = readVarint(buf, i + 1);
731
+ if (sized === void 0) continue;
732
+ const [length, dataAt] = sized;
733
+ if (length !== 4 || dataAt + 4 > buf.length) continue;
734
+ if (buf.subarray(dataAt, dataAt + 4).toString("latin1") !== "name") continue;
735
+ const value = readV8String(buf, dataAt + 4);
736
+ if (value === void 0) return void 0;
737
+ const [name, next] = value;
738
+ if (next > to) return void 0;
739
+ return name;
740
+ }
741
+ }
742
+ /**
743
+ * Whether a string has the shape of a model key.
744
+ *
745
+ * Shape, not length: the earlier bound of 24 characters silently dropped every `person-*`
746
+ * model, because those slugs run to 37. The server is the only authority on which keys exist,
747
+ * so this only rejects what could not be a key at all.
748
+ */
749
+ function looksLikeModelKey(value) {
750
+ return /^[\w.-]{1,64}$/u.test(value);
751
+ }
752
+ /** Whether a string has the shape of a display name rather than a field name or URL. */
753
+ function looksLikeModelName(value) {
754
+ if (value.length < 2 || value.length > 40) return false;
755
+ if (!/[\u4e00-\u9fa5A-Za-z]/u.test(value)) return false;
756
+ return !/^[a-z_]+$/u.test(value) && !value.includes("http");
757
+ }
758
+ /**
759
+ * Parse one LevelDB value buffer for (key, name) pairs.
760
+ *
761
+ * Exported so the encoding can be tested with synthetic bytes: the real cache belongs to
762
+ * another application and changes whenever it updates, so a parser that can only be exercised
763
+ * against it cannot be trusted to keep working.
764
+ */
765
+ function parseCacheBuffer(buf) {
766
+ const out = /* @__PURE__ */ new Map();
767
+ /**
768
+ * A second, text-based pass over the same buffer.
769
+ *
770
+ * V8 does not store a long string as one contiguous run: a key of 37 characters arrives as
771
+ * several chunks (`person-deepseek-v4-` + `1` + `.flash-26` + `1017`), each with its own
772
+ * length prefix. The structured reader below decodes the FIRST chunk and then stops, because
773
+ * the next byte is not a string tag — so a model whose slug happens to be split was skipped
774
+ * entirely, which is why DeepSeek was missing while Kimi and GLM were not.
775
+ *
776
+ * The scan below reconciles the fragments: every `person-…` run in the printable text is a
777
+ * candidate, and the longest key that starts the same way wins. That is what turns
778
+ * `person-deepseek-v4-` back into `person-deepseek-v4-1-flash-261017`.
779
+ */
780
+ const text = buf.toString("latin1");
781
+ const slugs = [...new Set([...text.matchAll(/person-[a-z0-9][a-z0-9-]{4,60}/gu)].map((match) => match[0]))];
782
+ for (const slug of slugs) {
783
+ /**
784
+ * Only a COMPLETE slug is a model.
785
+ *
786
+ * The fragments outnumber the real keys: the same record contributes
787
+ * `person-deepseek-v4-` and `ash-26`, and a naive run turns both into "models". Doubao
788
+ * slugs end in a six-digit date stamp (`…-261017`), so requiring that shape keeps the
789
+ * sixteen real keys and drops every piece of a split one.
790
+ */
791
+ if (!/^person-[a-z0-9-]+-\d{6}$/u.test(slug)) continue;
792
+ if (out.has(slug)) continue;
793
+ const name = nameForSlug(buf, slug);
794
+ /**
795
+ * The window and the multiplier travel WITH the model in this cache.
796
+ *
797
+ * Measured on a real record: `total_window_size: 300000` and a `tag.text` of `"1.48x"` sit
798
+ * beside `model_item_key` and `name`. Neither is on any HTTP endpoint this lane can call —
799
+ * `brief_list` returns feature entries and no model fields at all — so the cache is the only
800
+ * source for the two numbers the picker wants to print.
801
+ */
802
+ const meta = metaNear(buf, slug);
803
+ out.set(slug, {
804
+ id: slug,
805
+ name: name ?? nameFromSlug(slug),
806
+ badge: "工作任务",
807
+ reasoning: true,
808
+ ...meta.contextWindow === void 0 ? {} : { contextWindow: meta.contextWindow },
809
+ ...meta.rate === void 0 ? {} : { rate: meta.rate }
810
+ });
811
+ }
812
+ const KEY = Buffer.from("model_item_key");
813
+ let at = -1;
814
+ while ((at = buf.indexOf(KEY, at + 1)) !== -1) {
815
+ const keyRead = readV8String(buf, at + KEY.length);
816
+ if (keyRead === void 0) continue;
817
+ const [firstChunk, afterKey] = keyRead;
818
+ if (!looksLikeModelKey(firstChunk)) continue;
819
+ /**
820
+ * A leaf key such as `0` / `3` / `seed-lite-7b` arrives whole. A `person-*` key may be
821
+ * truncated here, which is why the slug pass above exists; if this read is short, skip it
822
+ * rather than storing a partial id the upstream would reject.
823
+ */
824
+ const key = firstChunk.endsWith("-") ? void 0 : firstChunk;
825
+ if (key === void 0) continue;
826
+ const name = readNameAfter(buf, afterKey, Math.min(buf.length, afterKey + 220));
827
+ if (name === void 0 || !looksLikeModelName(name)) continue;
828
+ if (!out.has(key)) out.set(key, {
829
+ id: key,
830
+ name,
831
+ /**
832
+ * Third-party slugs are 「工作任务」 models: the client runs them through the task lane,
833
+ * and `seed-lite-7b` / `5` / `9` are already badged that way in the static list.
834
+ */
835
+ ...key.startsWith("person-") || key === "seed-lite-7b" || key === "5" || key === "9" ? { badge: "工作任务" } : {},
836
+ reasoning: true
837
+ });
838
+ }
839
+ return [...out.values()];
840
+ }
841
+ /**
842
+ * The display name belonging to a slug, read from the buffer.
843
+ *
844
+ * The name sits after the key in the same record. It is matched by finding the slug in the raw
845
+ * bytes and taking the first readable name-like string that follows — which is what makes the
846
+ * card show "DeepSeek V4.1 Flash" rather than the raw slug.
847
+ */
848
+ function nameForSlug(buf, slug) {
849
+ const at = buf.indexOf(Buffer.from(slug, "latin1"));
850
+ if (at < 0) return void 0;
851
+ /**
852
+ * A short window AFTER the key, and a strict shape.
853
+ *
854
+ * The display name follows its key in the same record, but the bytes between them are
855
+ * encoding noise that decodes into plausible-looking garbage ("enableDeepThinkingSwitchT",
856
+ * "namec K"). Widening the window made that worse, so the match is narrowed instead: a name
857
+ * is a run of letters/CJK that STARTS with a capital or a Han character, contains no
858
+ * camelCase tail (which is how a field name reads), and is not one of the known field words.
859
+ */
860
+ const window = buf.subarray(at + slug.length, Math.min(buf.length, at + slug.length + 200)).toString("utf8");
861
+ for (const match of window.matchAll(/[一-龥A-Z][一-龥A-Za-z0-9]*(?:[ .·][一-龥A-Za-z0-9]+){0,3}/gu)) {
862
+ const candidate = match[0].trim();
863
+ if (candidate.length < 2 || candidate.length > 40) continue;
864
+ if (!/[一-龥]/u.test(candidate) && !/^[A-Z][A-Za-z0-9]*(?: [A-Z0-9][A-Za-z0-9.]*){1,4}$/u.test(candidate)) continue;
865
+ if (/^(Model|Name|Version|Switch|Expert|Jump|Deep|Person|Http|Samantha|Item|List|Menu|Conf)/u.test(candidate)) continue;
866
+ return candidate;
867
+ }
868
+ }
869
+ /**
870
+ * The window and multiplier recorded beside a model key.
871
+ *
872
+ * Both live in the same V8 record as the key, a few hundred bytes after it, so they are read
873
+ * from the same window the name is: `total_window_size` (or `context_window`) as a number, and
874
+ * the first `tag.text` that reads like a multiplier. Either may be absent — a model on a plan
875
+ * that publishes no figure simply has neither, and printing an invented one would be worse than
876
+ * printing nothing.
877
+ */
878
+ function metaNear(buf, slug) {
879
+ const at = buf.indexOf(Buffer.from(slug, "latin1"));
880
+ if (at < 0) return {};
881
+ const text = buf.subarray(at, Math.min(buf.length, at + 1200)).toString("latin1");
882
+ const out = {};
883
+ const rate = /(\d+(?:\.\d+)?x|免费|限时免费)/iu.exec(text);
884
+ if (rate?.[1] !== void 0) out.rate = rate[1].trim();
885
+ /**
886
+ * A context window: `total_window_size` followed by its digits.
887
+ *
888
+ * Matched loosely on the boundary between the name and the number because the serialised form
889
+ * has no separator to anchor on — any non-digit run of up to 24 bytes is allowed between them.
890
+ */
891
+ const size = /total_window_size[^0-9]{1,24}(\d{4,7})/u.exec(text) ?? /context_window[^0-9]{1,24}(\d{4,7})/u.exec(text) ?? /(\d{3})k_\d{3}/u.exec(text);
892
+ if (size?.[1] !== void 0) out.contextWindow = size[0].includes("k_") ? Number(size[1]) * 1e3 : Number(size[1]);
893
+ return out;
894
+ }
895
+ /**
896
+ * A presentable name derived from a model slug.
897
+ *
898
+ * `person-kimi-k3-1-pro-highspeed` reads as "Kimi K3.1 Pro Highspeed": the vendor prefix and
899
+ * the date stamp are dropped, and version numbers are joined back together. Used only when the
900
+ * cache bytes do not yield the real display name.
901
+ */
902
+ function nameFromSlug(slug) {
903
+ const body = slug.replace(/^person-/u, "").replace(/-\d{6}$/u, "").split("-").filter((part) => part !== "");
904
+ /**
905
+ * Join version numbers: `deepseek-v4-1-flash` is "DeepSeek V4.1 Flash", not "V4 1 Flash".
906
+ *
907
+ * A part that is a bare digit and directly follows a `v<number>` token belongs to that
908
+ * version — which is how Doubao writes every version in its own slugs.
909
+ */
910
+ const words = [];
911
+ for (const part of body) {
912
+ const previous = words[words.length - 1];
913
+ if (/^\d+$/u.test(part) && previous !== void 0 && /^v\d+$/iu.test(previous)) {
914
+ words[words.length - 1] = `${previous}.${part}`;
915
+ continue;
916
+ }
917
+ if (/^\d+$/u.test(part) && previous !== void 0 && /\d$/u.test(previous)) {
918
+ words[words.length - 1] = `${previous}.${part}`;
919
+ continue;
920
+ }
921
+ words.push(part);
922
+ }
923
+ const KNOWN = {
924
+ kimi: "Kimi",
925
+ glm: "GLM",
926
+ deepseek: "DeepSeek",
927
+ qwen: "Qwen",
928
+ doubao: "Doubao",
929
+ pro: "Pro",
930
+ flash: "Flash",
931
+ highspeed: "高速",
932
+ lite: "Lite",
933
+ turbo: "Turbo",
934
+ a: "A",
935
+ b: "B"
936
+ };
937
+ return words.map((word) => KNOWN[word.toLowerCase()] ?? (word.length <= 2 ? word.toUpperCase() : `${word.charAt(0).toUpperCase()}${word.slice(1)}`)).join(" ");
938
+ }
939
+ /** Scan one LevelDB directory for model entries. */
940
+ function scanDir(dir) {
941
+ const found = /* @__PURE__ */ new Map();
942
+ let files;
943
+ try {
944
+ files = readdirSync(dir);
945
+ } catch {
946
+ return [];
947
+ }
948
+ for (const file of files) {
949
+ if (!/\.(log|ldb|sst)$/iu.test(file)) continue;
950
+ let buf;
951
+ try {
952
+ buf = readFileSync(join(dir, file));
953
+ } catch {
954
+ continue;
955
+ }
956
+ for (const model of parseCacheBuffer(buf)) if (!found.has(model.id)) found.set(model.id, model);
957
+ }
958
+ return [...found.values()];
959
+ }
960
+ /**
961
+ * Every model the desktop client's cache knows, or an empty list.
962
+ *
963
+ * Never throws: a machine without the client, a cache mid-write, or a future format change all
964
+ * mean "no extra models", which is a state the caller already handles.
965
+ */
966
+ function modelsFromClientCache() {
967
+ const out = /* @__PURE__ */ new Map();
968
+ for (const dir of cacheDirs()) for (const model of scanDir(dir)) if (!out.has(model.id)) out.set(model.id, model);
969
+ return [...out.values()];
970
+ }
971
+ //#endregion
972
+ //#region src/doubao-catalog-live.ts
973
+ /**
974
+ * The Doubao catalogue, asked of the account.
975
+ *
976
+ * WHY THE STATIC LIST IS NOT ENOUGH
977
+ *
978
+ * `doubao-models.ts` carries the six entries read off a real client request. Doubao also
979
+ * publishes a LONGER roster per account — the 「工作任务」 family plus third-party models
980
+ * (DeepSeek, Kimi, GLM) that are only visible once a session exists. Reading it costs one
981
+ * request and makes the picker match what the account can actually use.
982
+ *
983
+ * The endpoint and body were measured against the live service: `brief_list` requires
984
+ * `{language_code, bot_id}` and the `Agw-Js-Conv` header. An empty body is answered
985
+ * `710010202 common invalid param`, and no body at all is answered "system error" — both of
986
+ * which read like a broken request rather than a missing field.
987
+ *
988
+ * FAILURE IS NOT FATAL
989
+ *
990
+ * A catalogue read that fails leaves the static list in place. The lane stays usable with the
991
+ * six models that are known to work, which beats an empty picker because one optional call
992
+ * went wrong.
993
+ *
994
+ * @module dsh-xdpool/doubao-catalog-live
995
+ */
996
+ /** The endpoint that lists what the account may use. */
997
+ const BRIEF_LIST_ENDPOINT = "https://www.doubao.com/alice/slot/action_bar_v3/brief_list";
998
+ /** The bot whose roster is being asked for — the default Doubao assistant. */
999
+ const BOT_ID = "7338286299411103781";
1000
+ /** How long a live listing is reused. */
1001
+ const TTL_MS = 6e5;
1002
+ /** The query the endpoint expects. */
1003
+ const CLIENT_PARAMS$2 = {
1004
+ aid: "497858",
1005
+ real_aid: "497858",
1006
+ version_code: "20800",
1007
+ device_platform: "web",
1008
+ doubao_device_platform: "web",
1009
+ language: "zh",
1010
+ region: "CN",
1011
+ sys_region: "CN",
1012
+ pkg_type: "release_version",
1013
+ pc_version: "2.1.7",
1014
+ chromium_version: "148.0.7816.0",
1015
+ client_platform: "pc_client",
1016
+ runtime: "web",
1017
+ runtime_version: "3.5.4",
1018
+ samantha_web: "1",
1019
+ "use-olympus-account": "1"
1020
+ };
1021
+ let cached$1;
1022
+ /**
1023
+ * Read the roster from the account.
1024
+ *
1025
+ * `now` is injectable so a test can exercise the cache without waiting.
1026
+ */
1027
+ async function fetchLiveModels(session, options = {}) {
1028
+ const now = options.now ?? Date.now();
1029
+ if (options.force !== true && cached$1 !== void 0 && now - cached$1.at < TTL_MS) return cached$1.models;
1030
+ if (session === void 0 || !sessionUsable(session)) return DOUBAO_MODELS;
1031
+ const params = new URLSearchParams({
1032
+ ...CLIENT_PARAMS$2,
1033
+ web_tab_id: crypto.randomUUID()
592
1034
  });
1035
+ let raw;
1036
+ try {
1037
+ raw = await (await fetch(`${BRIEF_LIST_ENDPOINT}?${params.toString()}`, {
1038
+ method: "POST",
1039
+ headers: {
1040
+ "content-type": "application/json",
1041
+ accept: "*/*",
1042
+ "user-agent": session.userAgent,
1043
+ Referer: "chrome://doubao-chat/",
1044
+ "agw-js-conv": "str",
1045
+ cookie: cookieHeader(session)
1046
+ },
1047
+ body: JSON.stringify({
1048
+ language_code: "zh",
1049
+ bot_id: BOT_ID
1050
+ }),
1051
+ signal: AbortSignal.timeout(12e3)
1052
+ })).json();
1053
+ } catch {
1054
+ return DOUBAO_MODELS;
1055
+ }
1056
+ /**
1057
+ * The desktop client's cache is the only source of the `person-*` models.
1058
+ *
1059
+ * The web catalogue answers with feature entries and no model keys, so a session alone
1060
+ * cannot reveal that the account may also call Kimi, GLM and friends. Those slugs are in the
1061
+ * client's IndexedDB whenever it has been installed and run — measured on this machine as
1062
+ * `person-kimi-k3-261111`, `person-glm-5-3-261111` and one more. Nothing breaks when the
1063
+ * client is absent: the list simply stays at the measured six.
1064
+ */
1065
+ const fromCache = modelsFromClientCache();
1066
+ const discovered = [...modelsFrom(raw), ...fromCache];
1067
+ if (discovered.length === 0) return DOUBAO_MODELS;
1068
+ /**
1069
+ * The static entries come FIRST, by id, and the discovered ones fill in behind them.
1070
+ *
1071
+ * The six in `DOUBAO_MODELS` are the ones measured to work end to end, including the image
1072
+ * alias that is not a Doubao model key at all — a live listing cannot produce that, and it
1073
+ * must not be dropped because the server never heard of it.
1074
+ */
1075
+ const byId = /* @__PURE__ */ new Map();
1076
+ for (const model of DOUBAO_MODELS) byId.set(model.id, model);
1077
+ for (const model of discovered) {
1078
+ if (byId.has(model.id)) {
1079
+ const known = byId.get(model.id);
1080
+ if (known !== void 0 && known.badge === void 0 && model.badge !== void 0) byId.set(model.id, {
1081
+ ...known,
1082
+ badge: model.badge
1083
+ });
1084
+ continue;
1085
+ }
1086
+ byId.set(model.id, model);
1087
+ }
1088
+ const models = [...byId.values()];
1089
+ cached$1 = {
1090
+ at: now,
1091
+ models
1092
+ };
1093
+ return models;
1094
+ }
1095
+ /**
1096
+ * Pull model rows out of whatever shape the endpoint answered with.
1097
+ *
1098
+ * The document is nested and has changed shape between builds, so the walk looks for the
1099
+ * FIELDS rather than a fixed path: any object carrying a `model_item_key` (or a `key` next to
1100
+ * a name) is a model. That is what keeps this working when the envelope is rearranged.
1101
+ */
1102
+ function modelsFrom(raw) {
1103
+ const out = [];
1104
+ const seen = /* @__PURE__ */ new Set();
1105
+ const walk = (node, depth) => {
1106
+ if (depth > 12 || node === null || typeof node !== "object") return;
1107
+ if (Array.isArray(node)) {
1108
+ for (const entry of node) walk(entry, depth + 1);
1109
+ return;
1110
+ }
1111
+ const record = node;
1112
+ const key = typeof record.model_item_key === "string" ? record.model_item_key : typeof record.key === "string" ? record.key : void 0;
1113
+ const name = typeof record.name === "string" ? record.name : typeof record.title === "string" ? record.title : typeof record.localized_name === "string" ? record.localized_name : void 0;
1114
+ if (key !== void 0 && key !== "" && name !== void 0 && name !== "" && !seen.has(key)) {
1115
+ seen.add(key);
1116
+ const badge = badgeOf(record.tag_list);
1117
+ out.push({
1118
+ id: key,
1119
+ name,
1120
+ ...badge === void 0 ? {} : { badge },
1121
+ reasoning: true
1122
+ });
1123
+ }
1124
+ for (const value of Object.values(record)) walk(value, depth + 1);
1125
+ };
1126
+ walk(raw, 0);
1127
+ return out;
1128
+ }
1129
+ /** The tag text the card shows beside a model, when the server sent one. */
1130
+ function badgeOf(tagList) {
1131
+ if (!Array.isArray(tagList)) return void 0;
1132
+ for (const tag of tagList) {
1133
+ if (typeof tag === "string" && tag.trim() !== "") return tag.trim();
1134
+ if (typeof tag === "object" && tag !== null) {
1135
+ const text = tag.text;
1136
+ if (typeof text === "string" && text.trim() !== "") return text.trim();
1137
+ }
1138
+ }
593
1139
  }
594
1140
  //#endregion
595
1141
  //#region src/doubao-upstream.ts
@@ -659,6 +1205,7 @@ const REQUIRED_COOKIE_NAMES = [
659
1205
  ];
660
1206
  const CHAT_ENDPOINT = "https://www.doubao.com/chat/completion";
661
1207
  const QUOTA_ENDPOINT = "https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/";
1208
+ const ACCOUNT_ENDPOINT = "https://www.doubao.com/passport/account/info/v2/";
662
1209
  const TOOL_LOCAL_ACK_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/ack";
663
1210
  const TOOL_LOCAL_UPLOAD_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/upload_command_result";
664
1211
  const TOOL_LOCAL_COMPLETE_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/complete";
@@ -677,7 +1224,7 @@ const DOUBAO_VERSION = "2.31.4";
677
1224
  * them fixed is what makes an external request look like the same install to
678
1225
  * the risk-control layer.
679
1226
  */
680
- const CLIENT_PARAMS = {
1227
+ const CLIENT_PARAMS$1 = {
681
1228
  aid: "582478",
682
1229
  real_aid: "582478",
683
1230
  version_code: "20800",
@@ -725,7 +1272,7 @@ function buildHeaders(credentials, extra = {}) {
725
1272
  }
726
1273
  function buildQueryUrl(endpoint, msToken) {
727
1274
  const params = new URLSearchParams({
728
- ...CLIENT_PARAMS,
1275
+ ...CLIENT_PARAMS$1,
729
1276
  web_tab_id: randomUUID()
730
1277
  });
731
1278
  if (msToken) params.set("msToken", msToken);
@@ -810,8 +1357,8 @@ function buildGeneralTaskParam(localMessageId, workspace, prompt) {
810
1357
  runtime_type: 2,
811
1358
  device_name: hostname(),
812
1359
  workspace,
813
- local_device_id: CLIENT_PARAMS.device_id,
814
- local_app_id: CLIENT_PARAMS.aid,
1360
+ local_device_id: CLIENT_PARAMS$1.device_id,
1361
+ local_app_id: CLIENT_PARAMS$1.aid,
815
1362
  sandbox_auth_type: 2
816
1363
  },
817
1364
  agent_task_param_change: {
@@ -1320,7 +1867,7 @@ async function runToolLocalResponder(uniqueKey, credentials, isStreamDone, signa
1320
1867
  if (seq === 0 || postStreamPolls >= 8) break;
1321
1868
  postStreamPolls += 1;
1322
1869
  }
1323
- const msgId = `${uniqueKey}:${CLIENT_PARAMS.device_id}:${CLIENT_PARAMS.aid}:message:${seq}`;
1870
+ const msgId = `${uniqueKey}:${CLIENT_PARAMS$1.device_id}:${CLIENT_PARAMS$1.aid}:message:${seq}`;
1324
1871
  let ack;
1325
1872
  try {
1326
1873
  ack = await postToolJson(TOOL_LOCAL_ACK_ENDPOINT, { msg_ids: [msgId] });
@@ -1768,8 +2315,35 @@ const THINKING_BLOCK_TYPE = 10040;
1768
2315
  * client has nothing to register, so the agent has nowhere to run.
1769
2316
  */
1770
2317
  const CODE_TASK_RUNTIME_UNAVAILABLE = 710010702;
2318
+ /** Quick reachability probe that does not consume any inference quota. */
2319
+ /**
2320
+ * The account's own display name.
2321
+ *
2322
+ * The card showed "豆包账号" for every account, because the session carries no name — only
2323
+ * cookies. `passport/account/info/v2` answers `data.name`, which is what the vendor calls the
2324
+ * user, so a pool with two Doubao accounts can tell them apart.
2325
+ *
2326
+ * A failed read returns undefined rather than throwing: the name is cosmetic, and a card
2327
+ * without it is still correct.
2328
+ */
2329
+ async function fetchAccountName(session) {
2330
+ if (session === void 0 || !sessionUsable(session)) return void 0;
2331
+ try {
2332
+ const response = await fetch(buildQueryUrl(ACCOUNT_ENDPOINT), {
2333
+ method: "GET",
2334
+ headers: buildHeaders$1(session),
2335
+ signal: AbortSignal.timeout(1e4)
2336
+ });
2337
+ if (!response.ok) return void 0;
2338
+ const payload = await response.json();
2339
+ for (const candidate of [payload.data?.name, payload.data?.screen_name]) if (typeof candidate === "string" && candidate.trim() !== "") return candidate.trim();
2340
+ return;
2341
+ } catch {
2342
+ return;
2343
+ }
2344
+ }
1771
2345
  /** The text of a host content value, which may be a string or a block list. */
1772
- function textOf$1(content) {
2346
+ function textOf$2(content) {
1773
2347
  if (typeof content === "string") return content;
1774
2348
  if (!Array.isArray(content)) return "";
1775
2349
  const out = [];
@@ -1795,7 +2369,7 @@ function promptFromMessages(messages) {
1795
2369
  const parts = [];
1796
2370
  for (const message of messages) {
1797
2371
  if (typeof message !== "object" || message === null) continue;
1798
- const text = textOf$1(message["content"]);
2372
+ const text = textOf$2(message["content"]);
1799
2373
  if (text !== "") parts.push(text);
1800
2374
  }
1801
2375
  return parts.join("\n\n");
@@ -1811,7 +2385,11 @@ function createDoubaoLlm(options) {
1811
2385
  return {
1812
2386
  listModels: async (provider) => {
1813
2387
  if (provider !== "doubao") return [];
1814
- return doubaoListing();
2388
+ return (await fetchLiveModels(options.session())).map((model) => ({
2389
+ id: model.id,
2390
+ name: model.name,
2391
+ ...model.badge === void 0 ? {} : { description: model.badge }
2392
+ }));
1815
2393
  },
1816
2394
  stream: async function* (streamOptions) {
1817
2395
  const session = options.session();
@@ -2038,6 +2616,20 @@ const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
2038
2616
  const POOL_DOUBAO_SESSION_PATH = "/plugins/dsh-xdpool/doubao/session";
2039
2617
  /** The Doubao quota: the windows the account has, with their reset countdowns. */
2040
2618
  const POOL_DOUBAO_QUOTA_PATH = "/plugins/dsh-xdpool/doubao/quota";
2619
+ /** The models the account may use, as the vendor publishes them. */
2620
+ const POOL_DOUBAO_MODELS_PATH = "/plugins/dsh-xdpool/doubao/models";
2621
+ /** The account's credit tasks: what is waiting, and what has been collected. */
2622
+ const POOL_DOUBAO_CAMPAIGN_PATH = "/plugins/dsh-xdpool/doubao/campaign";
2623
+ /** Collect every claimable task. */
2624
+ const POOL_DOUBAO_CLAIM_PATH = "/plugins/dsh-xdpool/doubao/claim";
2625
+ /**
2626
+ * Doubao's credit automation: read the switch, or turn it on and off.
2627
+ *
2628
+ * Doubao's points come from campaign tasks rather than a daily button, so automation here means
2629
+ * "collect whatever is claimable, on a schedule" — the same promise WorkBuddy's automation
2630
+ * makes, over a different mechanism.
2631
+ */
2632
+ const POOL_DOUBAO_AUTOMATION_PATH = "/plugins/dsh-xdpool/doubao/automation";
2041
2633
  /**
2042
2634
  * The `reason` the channel document carries when the login-channel route is
2043
2635
  * already owned by another plugin.
@@ -2125,6 +2717,291 @@ const DEFAULT_AUTOMATION_HOURS = {
2125
2717
  travel: [9, 21],
2126
2718
  compensation: [13]
2127
2719
  };
2720
+ //#endregion
2721
+ //#region src/doubao-campaign.ts
2722
+ /**
2723
+ * Doubao's credit tasks: what is waiting, and claiming it.
2724
+ *
2725
+ * WHAT WAS MEASURED
2726
+ *
2727
+ * `POST /alice/ug/campaign/v3/detail/` with `{campaign_group_code:"pc_incentive_task_mvp_v3"}`
2728
+ * returns the account's tasks and milestones. Each claimable entry carries a NUMERIC `task_id`
2729
+ * and a `campaign_item_code`, and
2730
+ *
2731
+ * POST /alice/ug/campaign/item/reward/claim/
2732
+ * { task_id: <the numeric id>, campaign_group_code, campaign_item_code }
2733
+ *
2734
+ * answers success. Two ways to get it wrong, both measured: sending the `campaign_code` as
2735
+ * `task_id` answers `710010202`, and sending `task_id` as a string answers the same.
2736
+ *
2737
+ * THE DAILY SIGN-IN
2738
+ *
2739
+ * `/alice/ug/campaign/landing/checkin` is the endpoint the client's own check-in button calls,
2740
+ * and it is used as-is. What it answers is the account's business: one account was observed to
2741
+ * be refused with `710010702 系统错误` while the same call is the documented path for every
2742
+ * other, which reads as a flagged account rather than a broken endpoint — so the result is
2743
+ * passed through and the caller reports it.
2744
+ *
2745
+ * @module dsh-xdpool/doubao-campaign
2746
+ */
2747
+ /** The campaign this account's tasks belong to. */
2748
+ const CAMPAIGN_GROUP = "pc_incentive_task_mvp_v3";
2749
+ const DETAIL_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/v3/detail/";
2750
+ const CLAIM_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/item/reward/claim/";
2751
+ const CHECKIN_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/landing/checkin";
2752
+ /**
2753
+ * The query parameters these endpoints require.
2754
+ *
2755
+ * Measured: the same body without them is answered `{code:1, msg:"invalid param"}` with HTTP
2756
+ * 200 — a refusal that reads as a malformed request and is actually a missing client
2757
+ * identity. The campaign endpoints are served by a different backend from the chat one and
2758
+ * check this envelope more strictly.
2759
+ */
2760
+ const CLIENT_PARAMS = {
2761
+ aid: "497858",
2762
+ real_aid: "497858",
2763
+ device_platform: "web",
2764
+ doubao_device_platform: "web",
2765
+ language: "zh",
2766
+ region: "CN",
2767
+ sys_region: "CN",
2768
+ pkg_type: "release_version",
2769
+ pc_version: "2.1.7",
2770
+ client_platform: "pc_client",
2771
+ runtime: "web",
2772
+ runtime_version: "3.5.4",
2773
+ samantha_web: "1",
2774
+ "use-olympus-account": "1"
2775
+ };
2776
+ /** The endpoint with the client envelope attached. */
2777
+ function buildUrl(endpoint) {
2778
+ return `${endpoint}?${new URLSearchParams({
2779
+ ...CLIENT_PARAMS,
2780
+ web_tab_id: crypto.randomUUID()
2781
+ }).toString()}`;
2782
+ }
2783
+ /** The headers every campaign call needs. */
2784
+ function headers(session) {
2785
+ return {
2786
+ "content-type": "application/json",
2787
+ accept: "*/*",
2788
+ "user-agent": session.userAgent,
2789
+ Referer: "chrome://doubao-chat/",
2790
+ "agw-js-conv": "str",
2791
+ cookie: cookieHeader(session)
2792
+ };
2793
+ }
2794
+ /** Pull a numeric field that may arrive as a number or a numeric string. */
2795
+ function numberOf$1(value) {
2796
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2797
+ if (typeof value === "string" && value.trim() !== "") {
2798
+ const parsed = Number(value);
2799
+ if (Number.isFinite(parsed)) return parsed;
2800
+ }
2801
+ }
2802
+ /** A text field that may arrive under any of several names. */
2803
+ function textOf$1(record, names) {
2804
+ for (const name of names) {
2805
+ const value = record[name];
2806
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
2807
+ }
2808
+ }
2809
+ /**
2810
+ * Walk the detail document for task rows.
2811
+ *
2812
+ * The envelope is nested and has been rearranged between builds, so the walk looks for the
2813
+ * FIELDS a task needs (a numeric id plus a campaign item code) rather than a fixed path. That
2814
+ * is what keeps it working when the server adds a wrapper level.
2815
+ */
2816
+ function tasksFrom(raw) {
2817
+ const out = [];
2818
+ const seen = /* @__PURE__ */ new Set();
2819
+ const walk = (node, depth) => {
2820
+ if (depth > 10 || node === null || typeof node !== "object") return;
2821
+ if (Array.isArray(node)) {
2822
+ for (const entry of node) walk(entry, depth + 1);
2823
+ return;
2824
+ }
2825
+ const record = node;
2826
+ /**
2827
+ * A task is identified by its campaign code — a SLUG, not a number.
2828
+ *
2829
+ * The claim call takes that slug, together with the campaign group. `task_id` does not
2830
+ * appear anywhere in this document; assuming it did meant every row was skipped and the
2831
+ * card reported "no tasks" against an account that had eight.
2832
+ */
2833
+ const itemCode = textOf$1(record, [
2834
+ "campaign_code",
2835
+ "campaign_item_code",
2836
+ "campaignItemCode",
2837
+ "item_code"
2838
+ ]);
2839
+ const title = textOf$1(record, [
2840
+ "title",
2841
+ "name",
2842
+ "task_name"
2843
+ ]);
2844
+ /**
2845
+ * A node that is not a task is not a dead end.
2846
+ *
2847
+ * Returning here would abandon the whole subtree — and the tasks live under `data.tasks`,
2848
+ * so the very first wrapper node has neither field and every row below it was skipped.
2849
+ * `walk(child)` continues instead, which is what lets the envelope be rearranged.
2850
+ */
2851
+ if (itemCode === void 0 || title === void 0 || seen.has(itemCode)) {
2852
+ for (const value of Object.values(record)) walk(value, depth + 1);
2853
+ return;
2854
+ }
2855
+ seen.add(itemCode);
2856
+ const status = numberOf$1(record["task_status"] ?? record["status"] ?? record["state"]) ?? 0;
2857
+ /**
2858
+ * What the statuses mean, measured on a live account:
2859
+ * 0 — not started (the guidance card)
2860
+ * 1 — completed, reward may be collectable
2861
+ * 3 — a choice step that is itself a task
2862
+ *
2863
+ * "Completed" is not "collected": the claim call is what moves the points, so the card
2864
+ * offers the button for a completed task and stops offering it once the server's own
2865
+ * totals show the reward landed.
2866
+ */
2867
+ const claimed = record["claimed"] === true || record["is_claimed"] === true;
2868
+ const claimable = (status === 1 || status === 3) && !claimed;
2869
+ out.push({
2870
+ itemCode,
2871
+ title,
2872
+ claimable,
2873
+ claimed,
2874
+ status,
2875
+ ...typeof record["subtitle"] === "string" && record["subtitle"] !== "" ? { progress: record["subtitle"] } : {}
2876
+ });
2877
+ };
2878
+ walk(raw, 0);
2879
+ return out;
2880
+ }
2881
+ /**
2882
+ * Read the account's tasks.
2883
+ *
2884
+ * A failure is reported through `error`, not thrown: the card sits beside the quota panel and
2885
+ * must render whether or not the campaign is reachable.
2886
+ */
2887
+ async function fetchCampaign(session) {
2888
+ if (session === void 0 || !sessionUsable(session)) return {
2889
+ tasks: [],
2890
+ claimableCount: 0,
2891
+ error: "还没有登录态"
2892
+ };
2893
+ try {
2894
+ const payload = await (await fetch(buildUrl(DETAIL_ENDPOINT), {
2895
+ method: "POST",
2896
+ headers: headers(session),
2897
+ body: JSON.stringify({ campaign_group_code: CAMPAIGN_GROUP }),
2898
+ signal: AbortSignal.timeout(2e4)
2899
+ })).json();
2900
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2901
+ const message = textOf$1(payload, ["msg", "message"]) ?? "";
2902
+ if (code !== void 0 && code !== 0) return {
2903
+ tasks: [],
2904
+ claimableCount: 0,
2905
+ error: message === "" ? `上游返回 ${String(code)}` : message
2906
+ };
2907
+ const tasks = tasksFrom(payload);
2908
+ const progress = payload["data"]?.["progress"];
2909
+ const earned = numberOf$1(progress?.["total_amount"]);
2910
+ return {
2911
+ tasks,
2912
+ claimableCount: tasks.filter((task) => task.claimable).length,
2913
+ ...earned === void 0 ? {} : { earned }
2914
+ };
2915
+ } catch (error) {
2916
+ return {
2917
+ tasks: [],
2918
+ claimableCount: 0,
2919
+ error: error instanceof Error ? error.message : String(error)
2920
+ };
2921
+ }
2922
+ }
2923
+ /**
2924
+ * Collect every claimable task.
2925
+ *
2926
+ * `task_id` is sent as a NUMBER and paired with the item code: a string, or the campaign code
2927
+ * in its place, is answered `710010202`. That is the whole reason this loop is explicit rather
2928
+ * than a single "claim all" call — the endpoint takes one item at a time.
2929
+ */
2930
+ async function claimTasks(session) {
2931
+ if (session === void 0 || !sessionUsable(session)) return {
2932
+ claimed: 0,
2933
+ failed: 0,
2934
+ reason: "还没有登录态"
2935
+ };
2936
+ const campaign = await fetchCampaign(session);
2937
+ if (campaign.error !== void 0) return {
2938
+ claimed: 0,
2939
+ failed: 0,
2940
+ reason: campaign.error
2941
+ };
2942
+ const pending = campaign.tasks.filter((task) => task.claimable);
2943
+ if (pending.length === 0) return {
2944
+ claimed: 0,
2945
+ failed: 0
2946
+ };
2947
+ let claimed = 0;
2948
+ let failed = 0;
2949
+ let reason;
2950
+ for (const task of pending) try {
2951
+ const payload = await (await fetch(buildUrl(CLAIM_ENDPOINT), {
2952
+ method: "POST",
2953
+ signal: AbortSignal.timeout(15e3),
2954
+ headers: headers(session),
2955
+ body: JSON.stringify({
2956
+ campaign_group_code: CAMPAIGN_GROUP,
2957
+ campaign_item_code: task.itemCode
2958
+ })
2959
+ })).json();
2960
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2961
+ if (code === void 0 || code === 0) claimed += 1;
2962
+ else {
2963
+ failed += 1;
2964
+ reason ??= textOf$1(payload, ["msg", "message"]) ?? `上游返回 ${String(code)}`;
2965
+ }
2966
+ } catch (error) {
2967
+ failed += 1;
2968
+ reason ??= error instanceof Error ? error.message : String(error);
2969
+ }
2970
+ return {
2971
+ claimed,
2972
+ failed,
2973
+ ...reason === void 0 ? {} : { reason }
2974
+ };
2975
+ }
2976
+ async function attemptCheckin(session) {
2977
+ if (session === void 0 || !sessionUsable(session)) return {
2978
+ ok: false,
2979
+ message: "还没有登录态"
2980
+ };
2981
+ try {
2982
+ const payload = await (await fetch(buildUrl(CHECKIN_ENDPOINT), {
2983
+ method: "POST",
2984
+ signal: AbortSignal.timeout(15e3),
2985
+ headers: headers(session),
2986
+ body: JSON.stringify({ scene: CAMPAIGN_GROUP })
2987
+ })).json();
2988
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2989
+ if (code === void 0 || code === 0) return {
2990
+ ok: true,
2991
+ message: "签到成功"
2992
+ };
2993
+ const message = textOf$1(payload, ["msg", "message"]) ?? "";
2994
+ return {
2995
+ ok: false,
2996
+ message: message === "" ? `上游返回 ${String(code)}` : message
2997
+ };
2998
+ } catch (error) {
2999
+ return {
3000
+ ok: false,
3001
+ message: error instanceof Error ? error.message : String(error)
3002
+ };
3003
+ }
3004
+ }
2128
3005
  /**
2129
3006
  * Parse one of the server's amount fields.
2130
3007
  *
@@ -2303,6 +3180,18 @@ let cachedFailure;
2303
3180
  let cachedFailureAt = 0;
2304
3181
  //#endregion
2305
3182
  //#region src/doubao-routes.ts
3183
+ /** Read a JSON body, or an empty object when there is none. */
3184
+ async function readJson(req) {
3185
+ const chunks = [];
3186
+ for await (const chunk of req) chunks.push(chunk);
3187
+ if (chunks.length === 0) return {};
3188
+ try {
3189
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
3190
+ return parsed !== null && typeof parsed === "object" ? parsed : {};
3191
+ } catch {
3192
+ return {};
3193
+ }
3194
+ }
2306
3195
  /** Write a JSON response. */
2307
3196
  function json$1(res, status, body) {
2308
3197
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
@@ -2389,10 +3278,22 @@ function registerDoubaoRoutes(ctx, deps) {
2389
3278
  });
2390
3279
  }
2391
3280
  const stored = deps.session();
3281
+ if (!sessionUsable(stored)) return json$1(res, 200, {
3282
+ ok: true,
3283
+ signedIn: false
3284
+ });
3285
+ /**
3286
+ * The name travels with the session answer.
3287
+ *
3288
+ * The card needs it to label the account, and it is the only place the two are known
3289
+ * together — fetching it separately would double the card's round trips.
3290
+ */
3291
+ const name = await fetchAccountName(stored);
2392
3292
  return json$1(res, 200, {
2393
3293
  ok: true,
2394
- signedIn: sessionUsable(stored),
2395
- ...stored?.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
3294
+ signedIn: true,
3295
+ ...name === void 0 ? {} : { name },
3296
+ ...stored.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
2396
3297
  });
2397
3298
  } catch (error) {
2398
3299
  return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -2423,21 +3324,476 @@ function registerDoubaoRoutes(ctx, deps) {
2423
3324
  });
2424
3325
  } catch (error) {
2425
3326
  return json$1(res, 200, {
2426
- ok: false,
2427
- signedIn: true,
2428
- windows: [],
2429
- error: error instanceof Error ? error.message : String(error)
3327
+ ok: false,
3328
+ signedIn: true,
3329
+ windows: [],
3330
+ error: error instanceof Error ? error.message : String(error)
3331
+ });
3332
+ }
3333
+ }
3334
+ });
3335
+ const disposeModels = ctx.webServer.register({
3336
+ kind: "exact",
3337
+ path: POOL_DOUBAO_MODELS_PATH,
3338
+ handler: async (req, res) => {
3339
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3340
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3341
+ /**
3342
+ * The same list the picker gets.
3343
+ *
3344
+ * The card used to render its own copy from the static catalogue, so a signed-in
3345
+ * account showed six models on the card and twelve in the picker. One route, one
3346
+ * answer.
3347
+ */
3348
+ try {
3349
+ return json$1(res, 200, {
3350
+ ok: true,
3351
+ models: await fetchLiveModels(deps.session())
3352
+ });
3353
+ } catch (error) {
3354
+ return json$1(res, 200, {
3355
+ ok: false,
3356
+ models: [],
3357
+ error: error instanceof Error ? error.message : String(error)
3358
+ });
3359
+ }
3360
+ }
3361
+ });
3362
+ const disposeCampaign = ctx.webServer.register({
3363
+ kind: "exact",
3364
+ path: POOL_DOUBAO_CAMPAIGN_PATH,
3365
+ handler: async (req, res) => {
3366
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3367
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3368
+ const session = deps.session();
3369
+ const campaign = await fetchCampaign(session);
3370
+ return json$1(res, 200, {
3371
+ ok: campaign.error === void 0,
3372
+ signedIn: session !== void 0,
3373
+ ...campaign
3374
+ });
3375
+ }
3376
+ });
3377
+ const disposeClaim = ctx.webServer.register({
3378
+ kind: "exact",
3379
+ path: POOL_DOUBAO_CLAIM_PATH,
3380
+ handler: async (req, res) => {
3381
+ if (req.method !== "POST") return json$1(res, 405, { error: "method not allowed" });
3382
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3383
+ const result = await claimTasks(deps.session());
3384
+ return json$1(res, 200, {
3385
+ ok: result.failed === 0,
3386
+ ...result
3387
+ });
3388
+ }
3389
+ });
3390
+ const disposeAutomation = ctx.webServer.register({
3391
+ kind: "exact",
3392
+ path: POOL_DOUBAO_AUTOMATION_PATH,
3393
+ handler: async (req, res) => {
3394
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3395
+ const automation = deps.automation();
3396
+ try {
3397
+ if (req.method === "POST") {
3398
+ /**
3399
+ * `{ enabled }` flips the switch; an empty body runs one pass.
3400
+ *
3401
+ * Two actions, one route, because they are one concept to the card: the pane's
3402
+ * checkbox and its "run now" button both mean "make the automation do its job".
3403
+ */
3404
+ const body = await readJson(req);
3405
+ if (typeof body["enabled"] === "boolean") {
3406
+ automation.setEnabled(body["enabled"]);
3407
+ return json$1(res, 200, {
3408
+ ok: true,
3409
+ ...automation.state()
3410
+ });
3411
+ }
3412
+ return json$1(res, 200, {
3413
+ ok: true,
3414
+ ...await automation.runOnce()
3415
+ });
3416
+ }
3417
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3418
+ return json$1(res, 200, {
3419
+ ok: true,
3420
+ ...automation.state()
2430
3421
  });
3422
+ } catch (error) {
3423
+ return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
2431
3424
  }
2432
3425
  }
2433
3426
  });
2434
3427
  return () => {
2435
3428
  disposeSession();
2436
3429
  disposeQuota();
3430
+ disposeModels();
3431
+ disposeCampaign();
3432
+ disposeClaim();
3433
+ disposeAutomation();
2437
3434
  };
2438
3435
  });
2439
3436
  }
2440
3437
  //#endregion
3438
+ //#region src/doubao-automation.ts
3439
+ /**
3440
+ * Doubao's credit automation.
3441
+ *
3442
+ * WHAT "AUTOMATION" MEANS HERE
3443
+ *
3444
+ * WorkBuddy's automation claims a daily check-in. Doubao has no working check-in endpoint — it
3445
+ * answers `710010702 系统错误` for every account, including from Doubao's own client — but it
3446
+ * does have campaign tasks whose rewards are collectable, and `daily_signin` is one of them.
3447
+ * So the automation is: collect every claimable task, on a schedule, and record what it did.
3448
+ *
3449
+ * The distinction matters for what the card can promise. This cannot make a check-in succeed;
3450
+ * it can only collect what the server has already marked finished. When nothing is claimable it
3451
+ * says so rather than reporting a failure.
3452
+ *
3453
+ * @module dsh-xdpool/doubao-automation
3454
+ */
3455
+ /** How often a pass runs while the switch is on. */
3456
+ const INTERVAL_MS = 216e5;
3457
+ /**
3458
+ * The automation, wired to a session getter.
3459
+ *
3460
+ * `runOn()` is separate from the timer so the card's manual button and the scheduled pass do the
3461
+ * same thing — a second implementation for the button would be the one that drifts.
3462
+ */
3463
+ function createDoubaoAutomation(options) {
3464
+ let enabled = false;
3465
+ let state = { enabled: false };
3466
+ let timer;
3467
+ const clearTimer = () => {
3468
+ if (timer !== void 0) {
3469
+ clearInterval(timer);
3470
+ timer = void 0;
3471
+ }
3472
+ };
3473
+ /**
3474
+ * One pass.
3475
+ *
3476
+ * "Nothing to collect" is recorded as a note rather than a failure: an account whose tasks are
3477
+ * all done has nothing wrong with it, and reporting that as an error every six hours is how a
3478
+ * working feature reads as broken.
3479
+ */
3480
+ const runPass = async () => {
3481
+ const session = options.session();
3482
+ if (session === void 0) {
3483
+ state = {
3484
+ ...state,
3485
+ enabled,
3486
+ lastNote: "还没有登录态"
3487
+ };
3488
+ return state;
3489
+ }
3490
+ /**
3491
+ * The daily sign-in first, then the tasks.
3492
+ *
3493
+ * `daily_signin` appears in the campaign as a task, but the endpoint its own button calls
3494
+ * is a separate one — and claiming the task does not perform the sign-in that earns it. So
3495
+ * both are attempted, and a refused sign-in does not stop the task collection that follows.
3496
+ */
3497
+ const checkin = await attemptCheckin(session);
3498
+ const before = await fetchCampaign(session);
3499
+ if (before.error !== void 0) {
3500
+ state = {
3501
+ ...state,
3502
+ enabled,
3503
+ lastNote: before.error
3504
+ };
3505
+ return state;
3506
+ }
3507
+ const checkinNote = checkin.ok ? "签到成功" : checkin.message;
3508
+ if (before.claimableCount === 0) {
3509
+ state = {
3510
+ ...state,
3511
+ enabled,
3512
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
3513
+ lastClaimed: 0,
3514
+ lastNote: "今天没有可领取的积分",
3515
+ lastCheckin: checkinNote
3516
+ };
3517
+ return state;
3518
+ }
3519
+ const result = await claimTasks(session);
3520
+ state = {
3521
+ ...state,
3522
+ enabled,
3523
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
3524
+ lastClaimed: result.claimed,
3525
+ lastCheckin: checkinNote,
3526
+ ...result.reason === void 0 ? {} : { lastNote: result.reason }
3527
+ };
3528
+ options.logger?.info?.(`[xdpool] doubao automation: claimed ${String(result.claimed)} task(s)` + (result.failed > 0 ? `, ${String(result.failed)} failed` : ""));
3529
+ return state;
3530
+ };
3531
+ const arm = () => {
3532
+ clearTimer();
3533
+ if (!enabled) return;
3534
+ timer = setInterval(() => {
3535
+ runPass();
3536
+ }, INTERVAL_MS);
3537
+ if (typeof timer === "object" && timer !== null && "unref" in timer) timer.unref();
3538
+ };
3539
+ return {
3540
+ state: () => state,
3541
+ setEnabled: (next) => {
3542
+ enabled = next;
3543
+ state = {
3544
+ ...state,
3545
+ enabled: next
3546
+ };
3547
+ arm();
3548
+ if (next) runPass();
3549
+ },
3550
+ runOnce: async () => await runPass(),
3551
+ stop: () => {
3552
+ clearTimer();
3553
+ }
3554
+ };
3555
+ }
3556
+ //#endregion
3557
+ //#region src/doubao-host-adapter.ts
3558
+ /**
3559
+ * Doubao as a host adapter.
3560
+ *
3561
+ * WHY THIS IS NEEDED
3562
+ *
3563
+ * `channel-lane.ts` serves `<channel>:<model>` ids for a gateway route, but the model PICKER
3564
+ * reads the host's adapter registry — `ctx.llm.registerAdapter([id], adapter)`. Every channel in
3565
+ * the pack registers one; Doubao did not, so a signed-in account with ten models enabled showed
3566
+ * nothing in the picker at all. The lane made the models reachable over HTTP; this makes them
3567
+ * visible in the list.
3568
+ *
3569
+ * WHAT IT IMPLEMENTS
3570
+ *
3571
+ * The five methods `LlmAdapter` requires, in the shape the pack's own adapters use:
3572
+ * `providerInfo`, `listModels`, `resolveModel`, `prepareCall`, `stream`. The wire stays in
3573
+ * `doubao-upstream.ts` — the module ported from a working implementation — so nothing here
3574
+ * invents request details.
3575
+ *
3576
+ * WHAT IT REPORTS ABOUT A MODEL
3577
+ *
3578
+ * The picker shows what these fields say, so they carry the same facts the other channels do:
3579
+ * context window, output ceiling, whether the model reasons, and the multiplier as a tag. A
3580
+ * model with no published figure says nothing rather than inventing one.
3581
+ *
3582
+ * @module dsh-xdpool/doubao-host-adapter
3583
+ */
3584
+ /** The provider id the picker groups by. */
3585
+ const DOUBAO_PROVIDER_ID = "doubao";
3586
+ /** The name the picker shows for the group. */
3587
+ const DOUBAO_PROVIDER_NAME = "豆包";
3588
+ /**
3589
+ * The context window this lane reports.
3590
+ *
3591
+ * Doubao does not publish a per-model window on the endpoints this lane calls, and the chat
3592
+ * itself accepts far more than the client advertises. 256k is what the reference implementation
3593
+ * settled on after measuring; reporting nothing would make the picker show "—" beside every
3594
+ * model, which reads as a broken channel.
3595
+ */
3596
+ const CONTEXT_WINDOW = 256e3;
3597
+ /** The output ceiling the lane requests. */
3598
+ const MAX_OUTPUT_TOKENS = 65536;
3599
+ /**
3600
+ * The multiplier, when the name carries one.
3601
+ *
3602
+ * Every vendor in this plugin writes the price into the model name; Doubao's own models are
3603
+ * included in the promotion programme, so the same shape appears (`… · x0.00`, `… · 免费`). The
3604
+ * split is done here rather than in the card so the PICKER sees it too.
3605
+ */
3606
+ function rateOf(name) {
3607
+ return /[·・]\s*(x\s*[\d.]+(?:\s*→\s*x?[\d.]+)?|免费|限时免费)/iu.exec(name)?.[1]?.trim();
3608
+ }
3609
+ /** The name without its trailing price. */
3610
+ function bareName(name) {
3611
+ return name.replace(/\s*[·・]\s*(?:x\s*[\d.]+(?:\s*→\s*x?[\d.]+)?|免费|限时免费|正式版.*)$/iu, "").trim();
3612
+ }
3613
+ /**
3614
+ * The adapter.
3615
+ *
3616
+ * `listModels` reads the account's live roster through `fetchLiveModels`, which merges the
3617
+ * measured six with whatever `brief_list` returns and whatever the desktop client's cache holds —
3618
+ * that is where the `person-*` models (DeepSeek, Kimi, GLM) come from.
3619
+ */
3620
+ var DoubaoHostAdapter = class extends LlmAdapter {
3621
+ options;
3622
+ /** The last roster read, so a picker redraw does not re-fetch. */
3623
+ cached;
3624
+ constructor(options) {
3625
+ super();
3626
+ this.options = options;
3627
+ }
3628
+ providerInfo(_provider) {
3629
+ return {
3630
+ id: DOUBAO_PROVIDER_ID,
3631
+ name: DOUBAO_PROVIDER_NAME
3632
+ };
3633
+ }
3634
+ async listModels(_provider) {
3635
+ const models = await fetchLiveModels(this.options.session());
3636
+ this.cached = {
3637
+ at: Date.now(),
3638
+ models
3639
+ };
3640
+ return models.map((model) => this.describe(model));
3641
+ }
3642
+ async resolveModel(provider, model, _signal) {
3643
+ const known = this.cached?.models.find((entry) => entry.id === model) ?? DOUBAO_MODELS.find((entry) => entry.id === model);
3644
+ if (known === void 0) return this.describe({
3645
+ id: model,
3646
+ name: model,
3647
+ reasoning: true
3648
+ });
3649
+ return this.describe(known);
3650
+ }
3651
+ async prepareCall(provider, model, signal) {
3652
+ return {
3653
+ model: await this.resolveModel(provider, model, signal),
3654
+ stream: (streamOptions) => this.stream(streamOptions)
3655
+ };
3656
+ }
3657
+ /**
3658
+ * One turn.
3659
+ *
3660
+ * Text and reasoning are queued separately and drained as they arrive, so a long answer
3661
+ * appears progressively instead of landing whole. An image answer is appended as markdown —
3662
+ * the client renders it without knowing about Doubao's own image blocks.
3663
+ */
3664
+ async *stream(options) {
3665
+ const session = this.options.session();
3666
+ if (session === void 0 || !sessionUsable(session)) throw new LlmError("还没有浏览器登录态。请在豆包卡片里点「重新登录」扫码一次。", "auth");
3667
+ const modelId = typeof options["model"] === "string" ? options["model"] : "";
3668
+ if (modelId === "") throw new LlmError("这条请求没有指定模型", "invalid");
3669
+ const messages = Array.isArray(options["messages"]) ? options["messages"] : [];
3670
+ const system = typeof options["system"] === "string" ? options["system"] : "";
3671
+ const body = promptOf(messages);
3672
+ const prompt = system === "" ? body : `${system}\n\n${body}`;
3673
+ if (prompt === "") throw new LlmError("这条请求没有可发送的文字", "invalid");
3674
+ const requested = options["reasoningEffort"];
3675
+ const level = typeof requested === "string" && [
3676
+ "low",
3677
+ "mid",
3678
+ "high"
3679
+ ].includes(requested) ? requested : "mid";
3680
+ const signal = options["signal"] instanceof AbortSignal ? options["signal"] : new AbortController().signal;
3681
+ const textQueue = [];
3682
+ const reasoningQueue = [];
3683
+ let done = false;
3684
+ let failure;
3685
+ let images = [];
3686
+ const turn = chat(prompt, {
3687
+ modelKey: modelId,
3688
+ reasoningLevel: level,
3689
+ signal,
3690
+ callbacks: {
3691
+ onText: (chunk) => {
3692
+ if (chunk !== "") textQueue.push(chunk);
3693
+ },
3694
+ onThinking: (chunk) => {
3695
+ if (chunk !== "") reasoningQueue.push(chunk);
3696
+ }
3697
+ }
3698
+ }).then((result) => {
3699
+ if (typeof result.conversationId === "string" && result.conversationId !== "") this.options.onConversationId?.(result.conversationId);
3700
+ if (Array.isArray(result.images)) images = result.images;
3701
+ }).catch((error) => {
3702
+ failure = error instanceof Error ? error : new Error(String(error));
3703
+ }).finally(() => {
3704
+ done = true;
3705
+ });
3706
+ while (!done || textQueue.length > 0 || reasoningQueue.length > 0) {
3707
+ const thinking = reasoningQueue.shift();
3708
+ if (thinking !== void 0) {
3709
+ yield {
3710
+ type: "reasoning-delta",
3711
+ index: 0,
3712
+ text: thinking
3713
+ };
3714
+ continue;
3715
+ }
3716
+ const text = textQueue.shift();
3717
+ if (text !== void 0) {
3718
+ yield {
3719
+ type: "text-delta",
3720
+ index: 0,
3721
+ text
3722
+ };
3723
+ continue;
3724
+ }
3725
+ if (done) break;
3726
+ await Promise.race([turn, new Promise((resolve) => setTimeout(resolve, 20))]);
3727
+ }
3728
+ await turn;
3729
+ if (failure !== void 0) throw failure;
3730
+ for (const image of images) if (typeof image.url === "string" && image.url !== "") yield {
3731
+ type: "text-delta",
3732
+ index: 0,
3733
+ text: `\n\n![生成图](${image.url})\n`
3734
+ };
3735
+ }
3736
+ /** Everything the picker shows for one model. */
3737
+ describe(model) {
3738
+ const rate = rateOf(model.name);
3739
+ const free = rate !== void 0 && (/免费/u.test(rate) || /^x\s*0*\.?0+$/iu.test(rate));
3740
+ return {
3741
+ provider: DOUBAO_PROVIDER_ID,
3742
+ id: model.id,
3743
+ name: bareName(model.name),
3744
+ inputModalities: ["text", "image"],
3745
+ defaultMaxTokens: MAX_OUTPUT_TOKENS,
3746
+ context: { contextWindow: CONTEXT_WINDOW },
3747
+ reasoning: {
3748
+ efforts: [
3749
+ {
3750
+ id: ReasoningEffortId("low"),
3751
+ name: "低"
3752
+ },
3753
+ {
3754
+ id: ReasoningEffortId("mid"),
3755
+ name: "中"
3756
+ },
3757
+ {
3758
+ id: ReasoningEffortId("high"),
3759
+ name: "高"
3760
+ }
3761
+ ],
3762
+ defaultEffort: ReasoningEffortId("mid")
3763
+ },
3764
+ ...rate === void 0 ? {} : { tags: [{
3765
+ text: rate,
3766
+ tone: free ? "free" : "price"
3767
+ }] }
3768
+ };
3769
+ }
3770
+ };
3771
+ /** The readable text of the host's message list. */
3772
+ function promptOf(messages) {
3773
+ const parts = [];
3774
+ for (const message of messages) {
3775
+ if (typeof message !== "object" || message === null) continue;
3776
+ const content = message["content"];
3777
+ if (typeof content === "string") {
3778
+ if (content !== "") parts.push(content);
3779
+ continue;
3780
+ }
3781
+ if (!Array.isArray(content)) continue;
3782
+ const texts = [];
3783
+ for (const block of content) {
3784
+ if (typeof block === "string") {
3785
+ texts.push(block);
3786
+ continue;
3787
+ }
3788
+ if (typeof block !== "object" || block === null) continue;
3789
+ const text = block["text"];
3790
+ if (typeof text === "string") texts.push(text);
3791
+ }
3792
+ if (texts.length > 0) parts.push(texts.join("\n"));
3793
+ }
3794
+ return parts.join("\n\n");
3795
+ }
3796
+ //#endregion
2441
3797
  //#region src/file-perms.ts
2442
3798
  /**
2443
3799
  * Write a file that holds credentials, without leaving it world-readable.
@@ -8021,60 +9377,8 @@ function catalogFromUpstream(models, region = "cn") {
8021
9377
  return models.map(toModelInfo);
8022
9378
  }
8023
9379
  //#endregion
8024
- //#region src/channels.ts
8025
- /**
8026
- * Mount the vendored free-channel pack.
8027
- *
8028
- * Thirteen login channels — CodeArts, WorkBuddy 国内版/国际版, LobsterAI, Qoder ×2,
8029
- * TRAE, Cline, Loomy, Raccoon, MiniMax Code, ZCode and Gemini — arrive as one
8030
- * MIT-licensed bundle we carry rather than re-implement. Each is a real protocol
8031
- * adapter with its own login handshake; rewriting twelve of them here would only
8032
- * produce a slower, drift-prone copy of work that upstream already validates.
8033
- *
8034
- * Provenance and rebuild notes live in `vendor/channel-pack/NOTICE.md`.
8035
- */
8036
- /** Directory of this module, used to locate the sibling `vendor/` tree. */
8037
- const HERE = dirname(fileURLToPath(import.meta.url));
8038
- /**
8039
- * Where the pack lives relative to the built entry.
8040
- *
8041
- * `src/index.ts` compiles to `lib/index.js`, so from there `vendor/` is one level
8042
- * up. Kept as a computed path rather than `import.meta.resolve` because the
8043
- * installed layout is a flat `node_modules/dsh-xdpool/{lib,vendor}`,
8044
- * which is not resolvable as a bare specifier.
8045
- */
8046
- const PACK_ENTRY = join(HERE, "..", "vendor", "channel-pack", "pack.js");
8047
- /**
8048
- * `PACK_ENTRY` as a URL, which is the only spelling `import()` accepts.
8049
- *
8050
- * On POSIX the two are interchangeable enough that the bug hid for a while; on
8051
- * Windows a bare `D:\...` path is not a specifier at all, and the loader answers
8052
- * `Only URLs with a scheme in: file, data, node, and electron are supported`
8053
- * before it ever looks at the disk. `pathToFileURL` also handles the drive
8054
- * letter and the backslashes, so this is the portable spelling rather than a
8055
- * Windows special case.
8056
- */
8057
- const PACK_ENTRY_URL = pathToFileURL(PACK_ENTRY).href;
8058
- /**
8059
- * The thirteen channels the pack registers, with the copy the card shows.
8060
- *
8061
- * `org`, `accent` and the login flow are lifted from the pack's own table
8062
- * (`CHANNEL_PROVIDERS` in its client bundle) so the card and the pack cannot
8063
- * disagree about what a channel is. Nothing here decides behaviour — the pack
8064
- * still owns the protocol — so a channel that changes its login flow upstream
8065
- * needs a data edit here, not a code change.
8066
- *
8067
- * `note` is the exception: it is ours, not the pack's, and it is Chinese on
8068
- * purpose. The user asked for each card to state in Chinese how much of that
8069
- * vendor's model usage is actually free, because the roster they were reading
8070
- * said "每日免费额度" eleven times over — a phrase that names the existence of a
8071
- * free allowance without ever saying what it is. Each line below names the
8072
- * models on the free line and, where the vendor publishes a figure, the figure
8073
- * itself. Where no figure is published, the line says so rather than inventing
8074
- * a number: a quota we guessed would be the one number on the card a user would
8075
- * plan their day around.
8076
- */
8077
- const REGISTERED_CHANNELS = [
9380
+ //#region src/channel-roster.ts
9381
+ const REGISTERED_CHANNELS$1 = [
8078
9382
  {
8079
9383
  id: "codearts",
8080
9384
  name: "CodeArts",
@@ -8235,9 +9539,72 @@ const REGISTERED_CHANNELS = [
8235
9539
  accent: "#325AB4",
8236
9540
  note: "浏览器扫码登录一次;对话与「工作任务」模型、生图、活动赠送额度都在这里",
8237
9541
  login: "browser",
9542
+ loginHint: "doubao",
8238
9543
  credits: { quota: true }
8239
9544
  }
8240
9545
  ];
9546
+ //#endregion
9547
+ //#region src/channels.ts
9548
+ /**
9549
+ * Mount the vendored free-channel pack.
9550
+ *
9551
+ * Thirteen login channels — CodeArts, WorkBuddy 国内版/国际版, LobsterAI, Qoder ×2,
9552
+ * TRAE, Cline, Loomy, Raccoon, MiniMax Code, ZCode and Gemini — arrive as one
9553
+ * MIT-licensed bundle we carry rather than re-implement. Each is a real protocol
9554
+ * adapter with its own login handshake; rewriting twelve of them here would only
9555
+ * produce a slower, drift-prone copy of work that upstream already validates.
9556
+ *
9557
+ * Provenance and rebuild notes live in `vendor/channel-pack/NOTICE.md`.
9558
+ */
9559
+ /** Directory of this module, used to locate the sibling `vendor/` tree. */
9560
+ const HERE = dirname(fileURLToPath(import.meta.url));
9561
+ /**
9562
+ * Where the pack lives relative to the built entry.
9563
+ *
9564
+ * `src/index.ts` compiles to `lib/index.js`, so from there `vendor/` is one level
9565
+ * up. Kept as a computed path rather than `import.meta.resolve` because the
9566
+ * installed layout is a flat `node_modules/dsh-xdpool/{lib,vendor}`,
9567
+ * which is not resolvable as a bare specifier.
9568
+ */
9569
+ const PACK_ENTRY = join(HERE, "..", "vendor", "channel-pack", "pack.js");
9570
+ /**
9571
+ * `PACK_ENTRY` as a URL, which is the only spelling `import()` accepts.
9572
+ *
9573
+ * On POSIX the two are interchangeable enough that the bug hid for a while; on
9574
+ * Windows a bare `D:\...` path is not a specifier at all, and the loader answers
9575
+ * `Only URLs with a scheme in: file, data, node, and electron are supported`
9576
+ * before it ever looks at the disk. `pathToFileURL` also handles the drive
9577
+ * letter and the backslashes, so this is the portable spelling rather than a
9578
+ * Windows special case.
9579
+ */
9580
+ const PACK_ENTRY_URL = pathToFileURL(PACK_ENTRY).href;
9581
+ /**
9582
+ * The thirteen channels the pack registers, with the copy the card shows.
9583
+ *
9584
+ * `org`, `accent` and the login flow are lifted from the pack's own table
9585
+ * (`CHANNEL_PROVIDERS` in its client bundle) so the card and the pack cannot
9586
+ * disagree about what a channel is. Nothing here decides behaviour — the pack
9587
+ * still owns the protocol — so a channel that changes its login flow upstream
9588
+ * needs a data edit here, not a code change.
9589
+ *
9590
+ * `note` is the exception: it is ours, not the pack's, and it is Chinese on
9591
+ * purpose. The user asked for each card to state in Chinese how much of that
9592
+ * vendor's model usage is actually free, because the roster they were reading
9593
+ * said "每日免费额度" eleven times over — a phrase that names the existence of a
9594
+ * free allowance without ever saying what it is. Each line below names the
9595
+ * models on the free line and, where the vendor publishes a figure, the figure
9596
+ * itself. Where no figure is published, the line says so rather than inventing
9597
+ * a number: a quota we guessed would be the one number on the card a user would
9598
+ * plan their day around.
9599
+ */
9600
+ /**
9601
+ * The roster lives in `channel-roster.ts`, which has no imports.
9602
+ *
9603
+ * It moved because the card needs the same names before the host answers, and the card runs in
9604
+ * the browser: importing them from here — a module that reads the filesystem to find the pack —
9605
+ * put `node:fs` in the client bundle, which does not load at all.
9606
+ */
9607
+ const REGISTERED_CHANNELS = REGISTERED_CHANNELS$1;
8241
9608
  /**
8242
9609
  * The two channels this plugin already serves from its own account pool.
8243
9610
  *
@@ -15720,15 +17087,18 @@ const POOL_PROVIDER_BY_REGION = {
15720
17087
  global: XDPOOL_GLOBAL_PROVIDER
15721
17088
  };
15722
17089
  /**
15723
- * Display name each region registers under, so the picker can group them.
17090
+ * The name each pool region shows in the model picker.
17091
+ *
17092
+ * It is the CHANNEL's name, not the plugin's.
15724
17093
  *
15725
- * "XD Pool" rather than the old "WorkBuddy XD Pool": the picker row is the only
15726
- * place this string surfaces, and the brand the user asked for is XD Pool. The
15727
- * REGION suffix stays because both lanes register real providers under different
15728
- * ids — dropping it would leave two identically-named groups in the dropdown.
17094
+ * Every account in these two pools arrived through a scan sign-in on the channel card, so the
17095
+ * reader who picked a model here was working with "WorkBuddy 国内版" a moment earlier. Calling
17096
+ * the group "XD Pool" asked them to learn a second name for the same accounts — and, because
17097
+ * the vendored pack registers the same two pools under its own ids, it produced FOUR groups
17098
+ * where two belonged.
15729
17099
  *
15730
- * Display name only. The provider ids above are what the host matches on when it
15731
- * persists a selection, so renaming a group must never touch them.
17100
+ * The provider IDS are untouched: the host persists a selection by id, so renaming a group
17101
+ * must never move it. Only what the reader sees changes.
15732
17102
  */
15733
17103
  const POOL_NAME_BY_REGION = {
15734
17104
  cn: "XD Pool(国内版)",
@@ -17150,7 +18520,7 @@ function mintRequestId(timestamp = Date.now()) {
17150
18520
  const value = BigInt(timestamp) * 4096n + 1n;
17151
18521
  let hex = "";
17152
18522
  for (let i = 0; i < 6; i += 1) hex += (value >> BigInt(40 - 8 * i) & 255n).toString(16).padStart(2, "0");
17153
- return `msg_${hex}${base62From(crypto.randomBytes(14))}`;
18523
+ return `msg_${hex}${base62From(crypto$1.randomBytes(14))}`;
17154
18524
  }
17155
18525
  /** Does `id` already look like a v2-canonical session (shape *and* descending counter)? */
17156
18526
  function isCanonicalSession(id) {
@@ -17183,7 +18553,7 @@ function sessionFromSeed(seed) {
17183
18553
  const offset = h & 2147483647n;
17184
18554
  const ts = SESSION_EPOCH + offset % (30n * 24n * 3600n * 1000n);
17185
18555
  const seq = Number(h >> 31n & 63n) + 1;
17186
- return `ses_${canonicalPrefix(ts, seq > 63 ? 63 : seq)}${base62From(crypto.createHash("sha256").update(`xdpool-free-suffix\0${seed}`, "utf8").digest().subarray(0, 14))}`;
18556
+ return `ses_${canonicalPrefix(ts, seq > 63 ? 63 : seq)}${base62From(crypto$1.createHash("sha256").update(`xdpool-free-suffix\0${seed}`, "utf8").digest().subarray(0, 14))}`;
17187
18557
  }
17188
18558
  /** Return `id` if already canonical; otherwise derive a deterministic canonical session from it. */
17189
18559
  function canonicalizeSession(id) {
@@ -17212,7 +18582,7 @@ function sessionForConversation(sessionId) {
17212
18582
  */
17213
18583
  function requestIdFor(sessionId, turnSeed) {
17214
18584
  if (text$1(turnSeed) === "") return mintRequestId();
17215
- const digest = crypto.createHash("sha256").update(`xdpool-free-req\0${sessionId}\0${turnSeed}`, "utf8").digest();
18585
+ const digest = crypto$1.createHash("sha256").update(`xdpool-free-req\0${sessionId}\0${turnSeed}`, "utf8").digest();
17216
18586
  const id = `msg_${digest.subarray(0, 6).toString("hex")}${base62From(digest.subarray(6, 20))}`;
17217
18587
  return REQUEST_RE.test(id) ? id : mintRequestId();
17218
18588
  }
@@ -18199,14 +19569,14 @@ function conversationKeyOf$1(body) {
18199
19569
  for (const raw of messages) {
18200
19570
  if (!isRecord(raw) || text(raw.role) !== "user") continue;
18201
19571
  const content = typeof raw.content === "string" ? raw.content : JSON.stringify(raw.content ?? "");
18202
- return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 32);
19572
+ return crypto$1.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 32);
18203
19573
  }
18204
- return crypto.createHash("sha256").update("xdpool-free-conversation", "utf8").digest("hex").slice(0, 32);
19574
+ return crypto$1.createHash("sha256").update("xdpool-free-conversation", "utf8").digest("hex").slice(0, 32);
18205
19575
  }
18206
19576
  /** The envelope one chat chunk carries, so frames from different lanes match. */
18207
19577
  function chatChunk(model, delta, finishReason) {
18208
19578
  return JSON.stringify({
18209
- id: `chatcmpl-${crypto.randomBytes(8).toString("hex")}`,
19579
+ id: `chatcmpl-${crypto$1.randomBytes(8).toString("hex")}`,
18210
19580
  object: "chat.completion.chunk",
18211
19581
  created: Math.floor(Date.now() / 1e3),
18212
19582
  model,
@@ -18239,7 +19609,7 @@ function createFreeLaneSource(catalog, logger, usageRecorder) {
18239
19609
  const plan = applyFingerprint(payload, wire);
18240
19610
  if (warnings.length > 0) logger?.warn?.(`free lane: ${warnings.length} image block(s) could not be forwarded; they were dropped`);
18241
19611
  const tracker = new StreamTracker(Date.now());
18242
- const turnId = `free-${crypto.randomBytes(8).toString("hex")}`;
19612
+ const turnId = `free-${crypto$1.randomBytes(8).toString("hex")}`;
18243
19613
  let ok = false;
18244
19614
  let recordedUsage = void 0;
18245
19615
  try {
@@ -25993,6 +27363,16 @@ function apply(ctx, config = {}) {
25993
27363
  if (stored !== void 0) adoptDoubaoSession(stored);
25994
27364
  });
25995
27365
  const doubaoLlm = createDoubaoLlm({ session: () => doubaoSession });
27366
+ /**
27367
+ * Doubao's credit automation.
27368
+ *
27369
+ * Created beside the lane because both read the same session: a sign-in that lands while the
27370
+ * automation is armed must be picked up on the next pass without anything being re-wired.
27371
+ */
27372
+ const doubaoAutomation = createDoubaoAutomation({
27373
+ session: () => doubaoSession,
27374
+ logger: ctx.logger
27375
+ });
25996
27376
  /** The ids Doubao's catalogue knows, so `stream` can tell its models from the host's. */
25997
27377
  const doubaoModelIds = new Set(DOUBAO_MODELS$1.map((model) => model.id));
25998
27378
  const hostLlm = ctx.llm;
@@ -26107,6 +27487,7 @@ function apply(ctx, config = {}) {
26107
27487
  shims.cn.close();
26108
27488
  shims.global.close();
26109
27489
  core.scheduler.stop();
27490
+ doubaoAutomation.stop();
26110
27491
  });
26111
27492
  relay.ready.catch((error) => {
26112
27493
  ctx.logger.warn(`xdpool relay: startup failed — ${String(error)}`);
@@ -26202,7 +27583,8 @@ function apply(ctx, config = {}) {
26202
27583
  clear: () => {
26203
27584
  adoptDoubaoSession(void 0);
26204
27585
  removeStoredSession();
26205
- }
27586
+ },
27587
+ automation: () => doubaoAutomation
26206
27588
  });
26207
27589
  return registerPoolStatusRoute(webCtx, {
26208
27590
  pool: core.pool,
@@ -26522,12 +27904,45 @@ function apply(ctx, config = {}) {
26522
27904
  let releaseAdapterGlobal;
26523
27905
  let releaseAdapterAggregate;
26524
27906
  let releaseAdapterFree;
27907
+ let releaseAdapterDoubao;
26525
27908
  let releaseDirectory;
26526
27909
  try {
26527
- releaseAdapterCn = ctx.llm.registerAdapter([POOL_PROVIDER_BY_REGION.cn], adaptersByRegion.cn.adapter);
26528
- releaseAdapterGlobal = ctx.llm.registerAdapter([POOL_PROVIDER_BY_REGION.global], adaptersByRegion.global.adapter);
27910
+ /**
27911
+ * The two region adapters are NOT registered — issue #148.
27912
+ *
27913
+ * `buddy` and `workbuddy` are what the scan-login lanes are called in the picker, and
27914
+ * they reach the same accounts through the same endpoint. Registering these two as
27915
+ * well put FOUR groups in the model picker for two account pools: "XD Pool 国内版" /
27916
+ * "WorkBuddy 国内版" and the same pair for the international side, all describing one
27917
+ * set of sign-ins.
27918
+ *
27919
+ * The accounts themselves are untouched: the pool document, the card, the balance
27920
+ * panel and the credit dot all read `core.pool` through the status route, none of
27921
+ * which involves an adapter. What changes is only which groups the PICKER lists.
27922
+ *
27923
+ * The adapters are still BUILT above — the loopback shims serve their traffic — so a
27924
+ * request that arrives on the pool's own path still works; it is the duplicate
27925
+ * listing entry that goes.
27926
+ */
27927
+ /**
27928
+ * A handle that does nothing, in the shape the caller disposes.
27929
+ *
27930
+ * `AdapterHandle` is a disposer FUNCTION carrying a `replace` method, so an empty
27931
+ * object would not typecheck and would also break the dispose path.
27932
+ */
27933
+ const detached = Object.assign(() => {}, { replace: () => {} });
27934
+ releaseAdapterCn = detached;
27935
+ releaseAdapterGlobal = detached;
26529
27936
  releaseAdapterAggregate = ctx.llm.registerAdapter([XDPOOL_AGGREGATE_PROVIDER], adaptersByRegion.aggregate.adapter);
26530
27937
  releaseAdapterFree = ctx.llm.registerAdapter([XDPOOL_FREE_PROVIDER], adaptersByRegion.free.adapter);
27938
+ /**
27939
+ * Doubao, registered the same way every other channel is.
27940
+ *
27941
+ * The lane over HTTP is not enough: the model PICKER reads the host's adapter
27942
+ * registry, so a signed-in Doubao account with ten models enabled appeared nowhere in
27943
+ * the list. This is the registration the pack performs for each of its own channels.
27944
+ */
27945
+ releaseAdapterDoubao = ctx.llm.registerAdapter([DOUBAO_PROVIDER_ID], new DoubaoHostAdapter({ session: () => doubaoSession }));
26531
27946
  } catch (error) {
26532
27947
  ctx.logger.error("dsh-xdpool: adapter registration failed", error);
26533
27948
  recordStartupNote(`adapters REJECTED: ${describeError(error)}`);
@@ -26535,6 +27950,7 @@ function apply(ctx, config = {}) {
26535
27950
  releaseAdapterGlobal?.();
26536
27951
  releaseAdapterAggregate?.();
26537
27952
  releaseAdapterFree?.();
27953
+ releaseAdapterDoubao?.();
26538
27954
  return;
26539
27955
  }
26540
27956
  try {
@@ -26605,6 +28021,7 @@ function apply(ctx, config = {}) {
26605
28021
  releaseAdapterGlobal?.();
26606
28022
  releaseAdapterAggregate?.();
26607
28023
  releaseAdapterFree?.();
28024
+ releaseAdapterDoubao?.();
26608
28025
  releaseDirectory?.();
26609
28026
  };
26610
28027
  try {