dsh-xdpool 2.7.0 → 2.7.2

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,7 +3,7 @@ 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
7
  import { chmod, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from "node:fs/promises";
8
8
  import z from "@deepseek-ai/schemastery";
9
9
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -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,
@@ -472,7 +533,7 @@ function imageModelLabelFromOverlay() {
472
533
  * unconfigured install reproduces the app rather than something that merely
473
534
  * happens to work.
474
535
  */
475
- const DOUBAO_MODELS = [
536
+ const DOUBAO_MODELS$1 = [
476
537
  {
477
538
  id: "0",
478
539
  name: "豆包 快速",
@@ -514,7 +575,7 @@ const DOUBAO_MODELS = [
514
575
  /** True when `id` is a 「工作任务」-mode model (`seed-lite-7b`, `5`, `9`). */
515
576
  function isTaskModel(id) {
516
577
  if (id === void 0) return false;
517
- return DOUBAO_MODELS.some((model) => model.id === id && model.taskMode === true);
578
+ return DOUBAO_MODELS$1.some((model) => model.id === id && model.taskMode === true);
518
579
  }
519
580
  /**
520
581
  * Catalog entry for a model id, falling back to {@link DOUBAO_DEFAULT_MODEL_ID}.
@@ -524,8 +585,8 @@ function isTaskModel(id) {
524
585
  * the request. `describeRequestedModel` in the shim is what surfaces the miss.
525
586
  */
526
587
  function findDoubaoModel(id) {
527
- if (id === void 0) return DOUBAO_MODELS.find((model) => model.id === "0");
528
- const known = DOUBAO_MODELS.find((model) => model.id === id);
588
+ if (id === void 0) return DOUBAO_MODELS$1.find((model) => model.id === "0");
589
+ const known = DOUBAO_MODELS$1.find((model) => model.id === id);
529
590
  if (known !== void 0) return known;
530
591
  return {
531
592
  id,
@@ -534,6 +595,512 @@ function findDoubaoModel(id) {
534
595
  };
535
596
  }
536
597
  //#endregion
598
+ //#region src/doubao-models.ts
599
+ /**
600
+ * The models Doubao publishes.
601
+ *
602
+ * Every id was read off a real request the desktop app sent, not inferred. ⚠️ The encoding is
603
+ * MIXED: `seed-lite-7b` is a string slug, `3`/`5`/`9` are numeric enum values — they travel as
604
+ * JSON strings either way and must be forwarded verbatim, never parsed to a number.
605
+ */
606
+ const DOUBAO_MODELS = [
607
+ {
608
+ id: "0",
609
+ name: "豆包 快速",
610
+ reasoning: false
611
+ },
612
+ {
613
+ id: "3",
614
+ name: "豆包 2.1 Turbo",
615
+ badge: "专家",
616
+ reasoning: true
617
+ },
618
+ {
619
+ id: "seed-lite-7b",
620
+ name: "豆包 2.1 Lite",
621
+ badge: "工作任务",
622
+ reasoning: true
623
+ },
624
+ {
625
+ id: "5",
626
+ name: "豆包 2.1 Pro",
627
+ badge: "工作任务",
628
+ reasoning: true
629
+ },
630
+ {
631
+ id: "9",
632
+ name: "自动",
633
+ badge: "工作任务",
634
+ reasoning: true
635
+ },
636
+ {
637
+ id: "image-gen",
638
+ name: "豆包 生图",
639
+ reasoning: true
640
+ }
641
+ ];
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
+ out.set(slug, {
795
+ id: slug,
796
+ name: name ?? nameFromSlug(slug),
797
+ badge: "工作任务",
798
+ reasoning: true
799
+ });
800
+ }
801
+ const KEY = Buffer.from("model_item_key");
802
+ let at = -1;
803
+ while ((at = buf.indexOf(KEY, at + 1)) !== -1) {
804
+ const keyRead = readV8String(buf, at + KEY.length);
805
+ if (keyRead === void 0) continue;
806
+ const [firstChunk, afterKey] = keyRead;
807
+ if (!looksLikeModelKey(firstChunk)) continue;
808
+ /**
809
+ * A leaf key such as `0` / `3` / `seed-lite-7b` arrives whole. A `person-*` key may be
810
+ * truncated here, which is why the slug pass above exists; if this read is short, skip it
811
+ * rather than storing a partial id the upstream would reject.
812
+ */
813
+ const key = firstChunk.endsWith("-") ? void 0 : firstChunk;
814
+ if (key === void 0) continue;
815
+ const name = readNameAfter(buf, afterKey, Math.min(buf.length, afterKey + 220));
816
+ if (name === void 0 || !looksLikeModelName(name)) continue;
817
+ if (!out.has(key)) out.set(key, {
818
+ id: key,
819
+ name,
820
+ /**
821
+ * Third-party slugs are 「工作任务」 models: the client runs them through the task lane,
822
+ * and `seed-lite-7b` / `5` / `9` are already badged that way in the static list.
823
+ */
824
+ ...key.startsWith("person-") || key === "seed-lite-7b" || key === "5" || key === "9" ? { badge: "工作任务" } : {},
825
+ reasoning: true
826
+ });
827
+ }
828
+ return [...out.values()];
829
+ }
830
+ /**
831
+ * The display name belonging to a slug, read from the buffer.
832
+ *
833
+ * The name sits after the key in the same record. It is matched by finding the slug in the raw
834
+ * bytes and taking the first readable name-like string that follows — which is what makes the
835
+ * card show "DeepSeek V4.1 Flash" rather than the raw slug.
836
+ */
837
+ function nameForSlug(buf, slug) {
838
+ const at = buf.indexOf(Buffer.from(slug, "latin1"));
839
+ if (at < 0) return void 0;
840
+ /**
841
+ * A short window AFTER the key, and a strict shape.
842
+ *
843
+ * The display name follows its key in the same record, but the bytes between them are
844
+ * encoding noise that decodes into plausible-looking garbage ("enableDeepThinkingSwitchT",
845
+ * "namec K"). Widening the window made that worse, so the match is narrowed instead: a name
846
+ * is a run of letters/CJK that STARTS with a capital or a Han character, contains no
847
+ * camelCase tail (which is how a field name reads), and is not one of the known field words.
848
+ */
849
+ const window = buf.subarray(at + slug.length, Math.min(buf.length, at + slug.length + 200)).toString("utf8");
850
+ for (const match of window.matchAll(/[一-龥A-Z][一-龥A-Za-z0-9]*(?:[ .·][一-龥A-Za-z0-9]+){0,3}/gu)) {
851
+ const candidate = match[0].trim();
852
+ if (candidate.length < 2 || candidate.length > 40) continue;
853
+ if (!/[一-龥]/u.test(candidate) && !/^[A-Z][A-Za-z0-9]*(?: [A-Z0-9][A-Za-z0-9.]*){1,4}$/u.test(candidate)) continue;
854
+ if (/^(Model|Name|Version|Switch|Expert|Jump|Deep|Person|Http|Samantha|Item|List|Menu|Conf)/u.test(candidate)) continue;
855
+ return candidate;
856
+ }
857
+ }
858
+ /**
859
+ * A presentable name derived from a model slug.
860
+ *
861
+ * `person-kimi-k3-1-pro-highspeed` reads as "Kimi K3.1 Pro Highspeed": the vendor prefix and
862
+ * the date stamp are dropped, and version numbers are joined back together. Used only when the
863
+ * cache bytes do not yield the real display name.
864
+ */
865
+ function nameFromSlug(slug) {
866
+ const body = slug.replace(/^person-/u, "").replace(/-\d{6}$/u, "").split("-").filter((part) => part !== "");
867
+ /**
868
+ * Join version numbers: `deepseek-v4-1-flash` is "DeepSeek V4.1 Flash", not "V4 1 Flash".
869
+ *
870
+ * A part that is a bare digit and directly follows a `v<number>` token belongs to that
871
+ * version — which is how Doubao writes every version in its own slugs.
872
+ */
873
+ const words = [];
874
+ for (const part of body) {
875
+ const previous = words[words.length - 1];
876
+ if (/^\d+$/u.test(part) && previous !== void 0 && /^v\d+$/iu.test(previous)) {
877
+ words[words.length - 1] = `${previous}.${part}`;
878
+ continue;
879
+ }
880
+ if (/^\d+$/u.test(part) && previous !== void 0 && /\d$/u.test(previous)) {
881
+ words[words.length - 1] = `${previous}.${part}`;
882
+ continue;
883
+ }
884
+ words.push(part);
885
+ }
886
+ const KNOWN = {
887
+ kimi: "Kimi",
888
+ glm: "GLM",
889
+ deepseek: "DeepSeek",
890
+ qwen: "Qwen",
891
+ doubao: "Doubao",
892
+ pro: "Pro",
893
+ flash: "Flash",
894
+ highspeed: "高速",
895
+ lite: "Lite",
896
+ turbo: "Turbo",
897
+ a: "A",
898
+ b: "B"
899
+ };
900
+ return words.map((word) => KNOWN[word.toLowerCase()] ?? (word.length <= 2 ? word.toUpperCase() : `${word.charAt(0).toUpperCase()}${word.slice(1)}`)).join(" ");
901
+ }
902
+ /** Scan one LevelDB directory for model entries. */
903
+ function scanDir(dir) {
904
+ const found = /* @__PURE__ */ new Map();
905
+ let files;
906
+ try {
907
+ files = readdirSync(dir);
908
+ } catch {
909
+ return [];
910
+ }
911
+ for (const file of files) {
912
+ if (!/\.(log|ldb|sst)$/iu.test(file)) continue;
913
+ let buf;
914
+ try {
915
+ buf = readFileSync(join(dir, file));
916
+ } catch {
917
+ continue;
918
+ }
919
+ for (const model of parseCacheBuffer(buf)) if (!found.has(model.id)) found.set(model.id, model);
920
+ }
921
+ return [...found.values()];
922
+ }
923
+ /**
924
+ * Every model the desktop client's cache knows, or an empty list.
925
+ *
926
+ * Never throws: a machine without the client, a cache mid-write, or a future format change all
927
+ * mean "no extra models", which is a state the caller already handles.
928
+ */
929
+ function modelsFromClientCache() {
930
+ const out = /* @__PURE__ */ new Map();
931
+ for (const dir of cacheDirs()) for (const model of scanDir(dir)) if (!out.has(model.id)) out.set(model.id, model);
932
+ return [...out.values()];
933
+ }
934
+ //#endregion
935
+ //#region src/doubao-catalog-live.ts
936
+ /**
937
+ * The Doubao catalogue, asked of the account.
938
+ *
939
+ * WHY THE STATIC LIST IS NOT ENOUGH
940
+ *
941
+ * `doubao-models.ts` carries the six entries read off a real client request. Doubao also
942
+ * publishes a LONGER roster per account — the 「工作任务」 family plus third-party models
943
+ * (DeepSeek, Kimi, GLM) that are only visible once a session exists. Reading it costs one
944
+ * request and makes the picker match what the account can actually use.
945
+ *
946
+ * The endpoint and body were measured against the live service: `brief_list` requires
947
+ * `{language_code, bot_id}` and the `Agw-Js-Conv` header. An empty body is answered
948
+ * `710010202 common invalid param`, and no body at all is answered "system error" — both of
949
+ * which read like a broken request rather than a missing field.
950
+ *
951
+ * FAILURE IS NOT FATAL
952
+ *
953
+ * A catalogue read that fails leaves the static list in place. The lane stays usable with the
954
+ * six models that are known to work, which beats an empty picker because one optional call
955
+ * went wrong.
956
+ *
957
+ * @module dsh-xdpool/doubao-catalog-live
958
+ */
959
+ /** The endpoint that lists what the account may use. */
960
+ const BRIEF_LIST_ENDPOINT = "https://www.doubao.com/alice/slot/action_bar_v3/brief_list";
961
+ /** The bot whose roster is being asked for — the default Doubao assistant. */
962
+ const BOT_ID = "7338286299411103781";
963
+ /** How long a live listing is reused. */
964
+ const TTL_MS = 6e5;
965
+ /** The query the endpoint expects. */
966
+ const CLIENT_PARAMS$2 = {
967
+ aid: "497858",
968
+ real_aid: "497858",
969
+ version_code: "20800",
970
+ device_platform: "web",
971
+ doubao_device_platform: "web",
972
+ language: "zh",
973
+ region: "CN",
974
+ sys_region: "CN",
975
+ pkg_type: "release_version",
976
+ pc_version: "2.1.7",
977
+ chromium_version: "148.0.7816.0",
978
+ client_platform: "pc_client",
979
+ runtime: "web",
980
+ runtime_version: "3.5.4",
981
+ samantha_web: "1",
982
+ "use-olympus-account": "1"
983
+ };
984
+ let cached$1;
985
+ /**
986
+ * Read the roster from the account.
987
+ *
988
+ * `now` is injectable so a test can exercise the cache without waiting.
989
+ */
990
+ async function fetchLiveModels(session, options = {}) {
991
+ const now = options.now ?? Date.now();
992
+ if (options.force !== true && cached$1 !== void 0 && now - cached$1.at < TTL_MS) return cached$1.models;
993
+ if (session === void 0 || !sessionUsable(session)) return DOUBAO_MODELS;
994
+ const params = new URLSearchParams({
995
+ ...CLIENT_PARAMS$2,
996
+ web_tab_id: crypto.randomUUID()
997
+ });
998
+ let raw;
999
+ try {
1000
+ raw = await (await fetch(`${BRIEF_LIST_ENDPOINT}?${params.toString()}`, {
1001
+ method: "POST",
1002
+ headers: {
1003
+ "content-type": "application/json",
1004
+ accept: "*/*",
1005
+ "user-agent": session.userAgent,
1006
+ Referer: "chrome://doubao-chat/",
1007
+ "agw-js-conv": "str",
1008
+ cookie: cookieHeader(session)
1009
+ },
1010
+ body: JSON.stringify({
1011
+ language_code: "zh",
1012
+ bot_id: BOT_ID
1013
+ }),
1014
+ signal: AbortSignal.timeout(12e3)
1015
+ })).json();
1016
+ } catch {
1017
+ return DOUBAO_MODELS;
1018
+ }
1019
+ /**
1020
+ * The desktop client's cache is the only source of the `person-*` models.
1021
+ *
1022
+ * The web catalogue answers with feature entries and no model keys, so a session alone
1023
+ * cannot reveal that the account may also call Kimi, GLM and friends. Those slugs are in the
1024
+ * client's IndexedDB whenever it has been installed and run — measured on this machine as
1025
+ * `person-kimi-k3-261111`, `person-glm-5-3-261111` and one more. Nothing breaks when the
1026
+ * client is absent: the list simply stays at the measured six.
1027
+ */
1028
+ const fromCache = modelsFromClientCache();
1029
+ const discovered = [...modelsFrom(raw), ...fromCache];
1030
+ if (discovered.length === 0) return DOUBAO_MODELS;
1031
+ /**
1032
+ * The static entries come FIRST, by id, and the discovered ones fill in behind them.
1033
+ *
1034
+ * The six in `DOUBAO_MODELS` are the ones measured to work end to end, including the image
1035
+ * alias that is not a Doubao model key at all — a live listing cannot produce that, and it
1036
+ * must not be dropped because the server never heard of it.
1037
+ */
1038
+ const byId = /* @__PURE__ */ new Map();
1039
+ for (const model of DOUBAO_MODELS) byId.set(model.id, model);
1040
+ for (const model of discovered) {
1041
+ if (byId.has(model.id)) {
1042
+ const known = byId.get(model.id);
1043
+ if (known !== void 0 && known.badge === void 0 && model.badge !== void 0) byId.set(model.id, {
1044
+ ...known,
1045
+ badge: model.badge
1046
+ });
1047
+ continue;
1048
+ }
1049
+ byId.set(model.id, model);
1050
+ }
1051
+ const models = [...byId.values()];
1052
+ cached$1 = {
1053
+ at: now,
1054
+ models
1055
+ };
1056
+ return models;
1057
+ }
1058
+ /**
1059
+ * Pull model rows out of whatever shape the endpoint answered with.
1060
+ *
1061
+ * The document is nested and has changed shape between builds, so the walk looks for the
1062
+ * FIELDS rather than a fixed path: any object carrying a `model_item_key` (or a `key` next to
1063
+ * a name) is a model. That is what keeps this working when the envelope is rearranged.
1064
+ */
1065
+ function modelsFrom(raw) {
1066
+ const out = [];
1067
+ const seen = /* @__PURE__ */ new Set();
1068
+ const walk = (node, depth) => {
1069
+ if (depth > 12 || node === null || typeof node !== "object") return;
1070
+ if (Array.isArray(node)) {
1071
+ for (const entry of node) walk(entry, depth + 1);
1072
+ return;
1073
+ }
1074
+ const record = node;
1075
+ const key = typeof record.model_item_key === "string" ? record.model_item_key : typeof record.key === "string" ? record.key : void 0;
1076
+ const name = typeof record.name === "string" ? record.name : typeof record.title === "string" ? record.title : typeof record.localized_name === "string" ? record.localized_name : void 0;
1077
+ if (key !== void 0 && key !== "" && name !== void 0 && name !== "" && !seen.has(key)) {
1078
+ seen.add(key);
1079
+ const badge = badgeOf(record.tag_list);
1080
+ out.push({
1081
+ id: key,
1082
+ name,
1083
+ ...badge === void 0 ? {} : { badge },
1084
+ reasoning: true
1085
+ });
1086
+ }
1087
+ for (const value of Object.values(record)) walk(value, depth + 1);
1088
+ };
1089
+ walk(raw, 0);
1090
+ return out;
1091
+ }
1092
+ /** The tag text the card shows beside a model, when the server sent one. */
1093
+ function badgeOf(tagList) {
1094
+ if (!Array.isArray(tagList)) return void 0;
1095
+ for (const tag of tagList) {
1096
+ if (typeof tag === "string" && tag.trim() !== "") return tag.trim();
1097
+ if (typeof tag === "object" && tag !== null) {
1098
+ const text = tag.text;
1099
+ if (typeof text === "string" && text.trim() !== "") return text.trim();
1100
+ }
1101
+ }
1102
+ }
1103
+ //#endregion
537
1104
  //#region src/doubao-upstream.ts
538
1105
  /**
539
1106
  * Doubao upstream client.
@@ -601,6 +1168,7 @@ const REQUIRED_COOKIE_NAMES = [
601
1168
  ];
602
1169
  const CHAT_ENDPOINT = "https://www.doubao.com/chat/completion";
603
1170
  const QUOTA_ENDPOINT = "https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/";
1171
+ const ACCOUNT_ENDPOINT = "https://www.doubao.com/passport/account/info/v2/";
604
1172
  const TOOL_LOCAL_ACK_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/ack";
605
1173
  const TOOL_LOCAL_UPLOAD_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/upload_command_result";
606
1174
  const TOOL_LOCAL_COMPLETE_ENDPOINT = "https://www.doubao.com/alice/office/tool_local/msg/complete";
@@ -619,7 +1187,7 @@ const DOUBAO_VERSION = "2.31.4";
619
1187
  * them fixed is what makes an external request look like the same install to
620
1188
  * the risk-control layer.
621
1189
  */
622
- const CLIENT_PARAMS = {
1190
+ const CLIENT_PARAMS$1 = {
623
1191
  aid: "582478",
624
1192
  real_aid: "582478",
625
1193
  version_code: "20800",
@@ -667,7 +1235,7 @@ function buildHeaders(credentials, extra = {}) {
667
1235
  }
668
1236
  function buildQueryUrl(endpoint, msToken) {
669
1237
  const params = new URLSearchParams({
670
- ...CLIENT_PARAMS,
1238
+ ...CLIENT_PARAMS$1,
671
1239
  web_tab_id: randomUUID()
672
1240
  });
673
1241
  if (msToken) params.set("msToken", msToken);
@@ -752,8 +1320,8 @@ function buildGeneralTaskParam(localMessageId, workspace, prompt) {
752
1320
  runtime_type: 2,
753
1321
  device_name: hostname(),
754
1322
  workspace,
755
- local_device_id: CLIENT_PARAMS.device_id,
756
- local_app_id: CLIENT_PARAMS.aid,
1323
+ local_device_id: CLIENT_PARAMS$1.device_id,
1324
+ local_app_id: CLIENT_PARAMS$1.aid,
757
1325
  sandbox_auth_type: 2
758
1326
  },
759
1327
  agent_task_param_change: {
@@ -1262,7 +1830,7 @@ async function runToolLocalResponder(uniqueKey, credentials, isStreamDone, signa
1262
1830
  if (seq === 0 || postStreamPolls >= 8) break;
1263
1831
  postStreamPolls += 1;
1264
1832
  }
1265
- const msgId = `${uniqueKey}:${CLIENT_PARAMS.device_id}:${CLIENT_PARAMS.aid}:message:${seq}`;
1833
+ const msgId = `${uniqueKey}:${CLIENT_PARAMS$1.device_id}:${CLIENT_PARAMS$1.aid}:message:${seq}`;
1266
1834
  let ack;
1267
1835
  try {
1268
1836
  ack = await postToolJson(TOOL_LOCAL_ACK_ENDPOINT, { msg_ids: [msgId] });
@@ -1710,23 +2278,35 @@ const THINKING_BLOCK_TYPE = 10040;
1710
2278
  * client has nothing to register, so the agent has nowhere to run.
1711
2279
  */
1712
2280
  const CODE_TASK_RUNTIME_UNAVAILABLE = 710010702;
1713
- /** The listings, derived from the catalog the reference implementation measured. */
1714
- function doubaoListing() {
1715
- const rows = [];
1716
- for (const model of DOUBAO_MODELS) {
1717
- const parts = [];
1718
- if (typeof model.badge === "string" && model.badge !== "") parts.push(model.badge);
1719
- if (model.reasoning === true) parts.push("推理");
1720
- rows.push({
1721
- id: model.id,
1722
- name: model.name,
1723
- ...parts.length === 0 ? {} : { description: parts.join(" · ") }
2281
+ /** Quick reachability probe that does not consume any inference quota. */
2282
+ /**
2283
+ * The account's own display name.
2284
+ *
2285
+ * The card showed "豆包账号" for every account, because the session carries no name — only
2286
+ * cookies. `passport/account/info/v2` answers `data.name`, which is what the vendor calls the
2287
+ * user, so a pool with two Doubao accounts can tell them apart.
2288
+ *
2289
+ * A failed read returns undefined rather than throwing: the name is cosmetic, and a card
2290
+ * without it is still correct.
2291
+ */
2292
+ async function fetchAccountName(session) {
2293
+ if (session === void 0 || !sessionUsable(session)) return void 0;
2294
+ try {
2295
+ const response = await fetch(buildQueryUrl(ACCOUNT_ENDPOINT), {
2296
+ method: "GET",
2297
+ headers: buildHeaders$1(session),
2298
+ signal: AbortSignal.timeout(1e4)
1724
2299
  });
2300
+ if (!response.ok) return void 0;
2301
+ const payload = await response.json();
2302
+ for (const candidate of [payload.data?.name, payload.data?.screen_name]) if (typeof candidate === "string" && candidate.trim() !== "") return candidate.trim();
2303
+ return;
2304
+ } catch {
2305
+ return;
1725
2306
  }
1726
- return rows;
1727
2307
  }
1728
2308
  /** The text of a host content value, which may be a string or a block list. */
1729
- function textOf$1(content) {
2309
+ function textOf$2(content) {
1730
2310
  if (typeof content === "string") return content;
1731
2311
  if (!Array.isArray(content)) return "";
1732
2312
  const out = [];
@@ -1752,7 +2332,7 @@ function promptFromMessages(messages) {
1752
2332
  const parts = [];
1753
2333
  for (const message of messages) {
1754
2334
  if (typeof message !== "object" || message === null) continue;
1755
- const text = textOf$1(message["content"]);
2335
+ const text = textOf$2(message["content"]);
1756
2336
  if (text !== "") parts.push(text);
1757
2337
  }
1758
2338
  return parts.join("\n\n");
@@ -1768,7 +2348,11 @@ function createDoubaoLlm(options) {
1768
2348
  return {
1769
2349
  listModels: async (provider) => {
1770
2350
  if (provider !== "doubao") return [];
1771
- return doubaoListing();
2351
+ return (await fetchLiveModels(options.session())).map((model) => ({
2352
+ id: model.id,
2353
+ name: model.name,
2354
+ ...model.badge === void 0 ? {} : { description: model.badge }
2355
+ }));
1772
2356
  },
1773
2357
  stream: async function* (streamOptions) {
1774
2358
  const session = options.session();
@@ -1995,6 +2579,20 @@ const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
1995
2579
  const POOL_DOUBAO_SESSION_PATH = "/plugins/dsh-xdpool/doubao/session";
1996
2580
  /** The Doubao quota: the windows the account has, with their reset countdowns. */
1997
2581
  const POOL_DOUBAO_QUOTA_PATH = "/plugins/dsh-xdpool/doubao/quota";
2582
+ /** The models the account may use, as the vendor publishes them. */
2583
+ const POOL_DOUBAO_MODELS_PATH = "/plugins/dsh-xdpool/doubao/models";
2584
+ /** The account's credit tasks: what is waiting, and what has been collected. */
2585
+ const POOL_DOUBAO_CAMPAIGN_PATH = "/plugins/dsh-xdpool/doubao/campaign";
2586
+ /** Collect every claimable task. */
2587
+ const POOL_DOUBAO_CLAIM_PATH = "/plugins/dsh-xdpool/doubao/claim";
2588
+ /**
2589
+ * Doubao's credit automation: read the switch, or turn it on and off.
2590
+ *
2591
+ * Doubao's points come from campaign tasks rather than a daily button, so automation here means
2592
+ * "collect whatever is claimable, on a schedule" — the same promise WorkBuddy's automation
2593
+ * makes, over a different mechanism.
2594
+ */
2595
+ const POOL_DOUBAO_AUTOMATION_PATH = "/plugins/dsh-xdpool/doubao/automation";
1998
2596
  /**
1999
2597
  * The `reason` the channel document carries when the login-channel route is
2000
2598
  * already owned by another plugin.
@@ -2082,6 +2680,291 @@ const DEFAULT_AUTOMATION_HOURS = {
2082
2680
  travel: [9, 21],
2083
2681
  compensation: [13]
2084
2682
  };
2683
+ //#endregion
2684
+ //#region src/doubao-campaign.ts
2685
+ /**
2686
+ * Doubao's credit tasks: what is waiting, and claiming it.
2687
+ *
2688
+ * WHAT WAS MEASURED
2689
+ *
2690
+ * `POST /alice/ug/campaign/v3/detail/` with `{campaign_group_code:"pc_incentive_task_mvp_v3"}`
2691
+ * returns the account's tasks and milestones. Each claimable entry carries a NUMERIC `task_id`
2692
+ * and a `campaign_item_code`, and
2693
+ *
2694
+ * POST /alice/ug/campaign/item/reward/claim/
2695
+ * { task_id: <the numeric id>, campaign_group_code, campaign_item_code }
2696
+ *
2697
+ * answers success. Two ways to get it wrong, both measured: sending the `campaign_code` as
2698
+ * `task_id` answers `710010202`, and sending `task_id` as a string answers the same.
2699
+ *
2700
+ * THE DAILY SIGN-IN
2701
+ *
2702
+ * `/alice/ug/campaign/landing/checkin` is the endpoint the client's own check-in button calls,
2703
+ * and it is used as-is. What it answers is the account's business: one account was observed to
2704
+ * be refused with `710010702 系统错误` while the same call is the documented path for every
2705
+ * other, which reads as a flagged account rather than a broken endpoint — so the result is
2706
+ * passed through and the caller reports it.
2707
+ *
2708
+ * @module dsh-xdpool/doubao-campaign
2709
+ */
2710
+ /** The campaign this account's tasks belong to. */
2711
+ const CAMPAIGN_GROUP = "pc_incentive_task_mvp_v3";
2712
+ const DETAIL_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/v3/detail/";
2713
+ const CLAIM_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/item/reward/claim/";
2714
+ const CHECKIN_ENDPOINT = "https://www.doubao.com/alice/ug/campaign/landing/checkin";
2715
+ /**
2716
+ * The query parameters these endpoints require.
2717
+ *
2718
+ * Measured: the same body without them is answered `{code:1, msg:"invalid param"}` with HTTP
2719
+ * 200 — a refusal that reads as a malformed request and is actually a missing client
2720
+ * identity. The campaign endpoints are served by a different backend from the chat one and
2721
+ * check this envelope more strictly.
2722
+ */
2723
+ const CLIENT_PARAMS = {
2724
+ aid: "497858",
2725
+ real_aid: "497858",
2726
+ device_platform: "web",
2727
+ doubao_device_platform: "web",
2728
+ language: "zh",
2729
+ region: "CN",
2730
+ sys_region: "CN",
2731
+ pkg_type: "release_version",
2732
+ pc_version: "2.1.7",
2733
+ client_platform: "pc_client",
2734
+ runtime: "web",
2735
+ runtime_version: "3.5.4",
2736
+ samantha_web: "1",
2737
+ "use-olympus-account": "1"
2738
+ };
2739
+ /** The endpoint with the client envelope attached. */
2740
+ function buildUrl(endpoint) {
2741
+ return `${endpoint}?${new URLSearchParams({
2742
+ ...CLIENT_PARAMS,
2743
+ web_tab_id: crypto.randomUUID()
2744
+ }).toString()}`;
2745
+ }
2746
+ /** The headers every campaign call needs. */
2747
+ function headers(session) {
2748
+ return {
2749
+ "content-type": "application/json",
2750
+ accept: "*/*",
2751
+ "user-agent": session.userAgent,
2752
+ Referer: "chrome://doubao-chat/",
2753
+ "agw-js-conv": "str",
2754
+ cookie: cookieHeader(session)
2755
+ };
2756
+ }
2757
+ /** Pull a numeric field that may arrive as a number or a numeric string. */
2758
+ function numberOf$1(value) {
2759
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2760
+ if (typeof value === "string" && value.trim() !== "") {
2761
+ const parsed = Number(value);
2762
+ if (Number.isFinite(parsed)) return parsed;
2763
+ }
2764
+ }
2765
+ /** A text field that may arrive under any of several names. */
2766
+ function textOf$1(record, names) {
2767
+ for (const name of names) {
2768
+ const value = record[name];
2769
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
2770
+ }
2771
+ }
2772
+ /**
2773
+ * Walk the detail document for task rows.
2774
+ *
2775
+ * The envelope is nested and has been rearranged between builds, so the walk looks for the
2776
+ * FIELDS a task needs (a numeric id plus a campaign item code) rather than a fixed path. That
2777
+ * is what keeps it working when the server adds a wrapper level.
2778
+ */
2779
+ function tasksFrom(raw) {
2780
+ const out = [];
2781
+ const seen = /* @__PURE__ */ new Set();
2782
+ const walk = (node, depth) => {
2783
+ if (depth > 10 || node === null || typeof node !== "object") return;
2784
+ if (Array.isArray(node)) {
2785
+ for (const entry of node) walk(entry, depth + 1);
2786
+ return;
2787
+ }
2788
+ const record = node;
2789
+ /**
2790
+ * A task is identified by its campaign code — a SLUG, not a number.
2791
+ *
2792
+ * The claim call takes that slug, together with the campaign group. `task_id` does not
2793
+ * appear anywhere in this document; assuming it did meant every row was skipped and the
2794
+ * card reported "no tasks" against an account that had eight.
2795
+ */
2796
+ const itemCode = textOf$1(record, [
2797
+ "campaign_code",
2798
+ "campaign_item_code",
2799
+ "campaignItemCode",
2800
+ "item_code"
2801
+ ]);
2802
+ const title = textOf$1(record, [
2803
+ "title",
2804
+ "name",
2805
+ "task_name"
2806
+ ]);
2807
+ /**
2808
+ * A node that is not a task is not a dead end.
2809
+ *
2810
+ * Returning here would abandon the whole subtree — and the tasks live under `data.tasks`,
2811
+ * so the very first wrapper node has neither field and every row below it was skipped.
2812
+ * `walk(child)` continues instead, which is what lets the envelope be rearranged.
2813
+ */
2814
+ if (itemCode === void 0 || title === void 0 || seen.has(itemCode)) {
2815
+ for (const value of Object.values(record)) walk(value, depth + 1);
2816
+ return;
2817
+ }
2818
+ seen.add(itemCode);
2819
+ const status = numberOf$1(record["task_status"] ?? record["status"] ?? record["state"]) ?? 0;
2820
+ /**
2821
+ * What the statuses mean, measured on a live account:
2822
+ * 0 — not started (the guidance card)
2823
+ * 1 — completed, reward may be collectable
2824
+ * 3 — a choice step that is itself a task
2825
+ *
2826
+ * "Completed" is not "collected": the claim call is what moves the points, so the card
2827
+ * offers the button for a completed task and stops offering it once the server's own
2828
+ * totals show the reward landed.
2829
+ */
2830
+ const claimed = record["claimed"] === true || record["is_claimed"] === true;
2831
+ const claimable = (status === 1 || status === 3) && !claimed;
2832
+ out.push({
2833
+ itemCode,
2834
+ title,
2835
+ claimable,
2836
+ claimed,
2837
+ status,
2838
+ ...typeof record["subtitle"] === "string" && record["subtitle"] !== "" ? { progress: record["subtitle"] } : {}
2839
+ });
2840
+ };
2841
+ walk(raw, 0);
2842
+ return out;
2843
+ }
2844
+ /**
2845
+ * Read the account's tasks.
2846
+ *
2847
+ * A failure is reported through `error`, not thrown: the card sits beside the quota panel and
2848
+ * must render whether or not the campaign is reachable.
2849
+ */
2850
+ async function fetchCampaign(session) {
2851
+ if (session === void 0 || !sessionUsable(session)) return {
2852
+ tasks: [],
2853
+ claimableCount: 0,
2854
+ error: "还没有登录态"
2855
+ };
2856
+ try {
2857
+ const payload = await (await fetch(buildUrl(DETAIL_ENDPOINT), {
2858
+ method: "POST",
2859
+ headers: headers(session),
2860
+ body: JSON.stringify({ campaign_group_code: CAMPAIGN_GROUP }),
2861
+ signal: AbortSignal.timeout(2e4)
2862
+ })).json();
2863
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2864
+ const message = textOf$1(payload, ["msg", "message"]) ?? "";
2865
+ if (code !== void 0 && code !== 0) return {
2866
+ tasks: [],
2867
+ claimableCount: 0,
2868
+ error: message === "" ? `上游返回 ${String(code)}` : message
2869
+ };
2870
+ const tasks = tasksFrom(payload);
2871
+ const progress = payload["data"]?.["progress"];
2872
+ const earned = numberOf$1(progress?.["total_amount"]);
2873
+ return {
2874
+ tasks,
2875
+ claimableCount: tasks.filter((task) => task.claimable).length,
2876
+ ...earned === void 0 ? {} : { earned }
2877
+ };
2878
+ } catch (error) {
2879
+ return {
2880
+ tasks: [],
2881
+ claimableCount: 0,
2882
+ error: error instanceof Error ? error.message : String(error)
2883
+ };
2884
+ }
2885
+ }
2886
+ /**
2887
+ * Collect every claimable task.
2888
+ *
2889
+ * `task_id` is sent as a NUMBER and paired with the item code: a string, or the campaign code
2890
+ * in its place, is answered `710010202`. That is the whole reason this loop is explicit rather
2891
+ * than a single "claim all" call — the endpoint takes one item at a time.
2892
+ */
2893
+ async function claimTasks(session) {
2894
+ if (session === void 0 || !sessionUsable(session)) return {
2895
+ claimed: 0,
2896
+ failed: 0,
2897
+ reason: "还没有登录态"
2898
+ };
2899
+ const campaign = await fetchCampaign(session);
2900
+ if (campaign.error !== void 0) return {
2901
+ claimed: 0,
2902
+ failed: 0,
2903
+ reason: campaign.error
2904
+ };
2905
+ const pending = campaign.tasks.filter((task) => task.claimable);
2906
+ if (pending.length === 0) return {
2907
+ claimed: 0,
2908
+ failed: 0
2909
+ };
2910
+ let claimed = 0;
2911
+ let failed = 0;
2912
+ let reason;
2913
+ for (const task of pending) try {
2914
+ const payload = await (await fetch(buildUrl(CLAIM_ENDPOINT), {
2915
+ method: "POST",
2916
+ signal: AbortSignal.timeout(15e3),
2917
+ headers: headers(session),
2918
+ body: JSON.stringify({
2919
+ campaign_group_code: CAMPAIGN_GROUP,
2920
+ campaign_item_code: task.itemCode
2921
+ })
2922
+ })).json();
2923
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2924
+ if (code === void 0 || code === 0) claimed += 1;
2925
+ else {
2926
+ failed += 1;
2927
+ reason ??= textOf$1(payload, ["msg", "message"]) ?? `上游返回 ${String(code)}`;
2928
+ }
2929
+ } catch (error) {
2930
+ failed += 1;
2931
+ reason ??= error instanceof Error ? error.message : String(error);
2932
+ }
2933
+ return {
2934
+ claimed,
2935
+ failed,
2936
+ ...reason === void 0 ? {} : { reason }
2937
+ };
2938
+ }
2939
+ async function attemptCheckin(session) {
2940
+ if (session === void 0 || !sessionUsable(session)) return {
2941
+ ok: false,
2942
+ message: "还没有登录态"
2943
+ };
2944
+ try {
2945
+ const payload = await (await fetch(buildUrl(CHECKIN_ENDPOINT), {
2946
+ method: "POST",
2947
+ signal: AbortSignal.timeout(15e3),
2948
+ headers: headers(session),
2949
+ body: JSON.stringify({ scene: CAMPAIGN_GROUP })
2950
+ })).json();
2951
+ const code = numberOf$1(payload["code"] ?? payload["status_code"]);
2952
+ if (code === void 0 || code === 0) return {
2953
+ ok: true,
2954
+ message: "签到成功"
2955
+ };
2956
+ const message = textOf$1(payload, ["msg", "message"]) ?? "";
2957
+ return {
2958
+ ok: false,
2959
+ message: message === "" ? `上游返回 ${String(code)}` : message
2960
+ };
2961
+ } catch (error) {
2962
+ return {
2963
+ ok: false,
2964
+ message: error instanceof Error ? error.message : String(error)
2965
+ };
2966
+ }
2967
+ }
2085
2968
  /**
2086
2969
  * Parse one of the server's amount fields.
2087
2970
  *
@@ -2260,6 +3143,18 @@ let cachedFailure;
2260
3143
  let cachedFailureAt = 0;
2261
3144
  //#endregion
2262
3145
  //#region src/doubao-routes.ts
3146
+ /** Read a JSON body, or an empty object when there is none. */
3147
+ async function readJson(req) {
3148
+ const chunks = [];
3149
+ for await (const chunk of req) chunks.push(chunk);
3150
+ if (chunks.length === 0) return {};
3151
+ try {
3152
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
3153
+ return parsed !== null && typeof parsed === "object" ? parsed : {};
3154
+ } catch {
3155
+ return {};
3156
+ }
3157
+ }
2263
3158
  /** Write a JSON response. */
2264
3159
  function json$1(res, status, body) {
2265
3160
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
@@ -2346,10 +3241,22 @@ function registerDoubaoRoutes(ctx, deps) {
2346
3241
  });
2347
3242
  }
2348
3243
  const stored = deps.session();
3244
+ if (!sessionUsable(stored)) return json$1(res, 200, {
3245
+ ok: true,
3246
+ signedIn: false
3247
+ });
3248
+ /**
3249
+ * The name travels with the session answer.
3250
+ *
3251
+ * The card needs it to label the account, and it is the only place the two are known
3252
+ * together — fetching it separately would double the card's round trips.
3253
+ */
3254
+ const name = await fetchAccountName(stored);
2349
3255
  return json$1(res, 200, {
2350
3256
  ok: true,
2351
- signedIn: sessionUsable(stored),
2352
- ...stored?.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
3257
+ signedIn: true,
3258
+ ...name === void 0 ? {} : { name },
3259
+ ...stored.savedAt === void 0 ? {} : { savedAt: stored.savedAt }
2353
3260
  });
2354
3261
  } catch (error) {
2355
3262
  return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -2388,13 +3295,228 @@ function registerDoubaoRoutes(ctx, deps) {
2388
3295
  }
2389
3296
  }
2390
3297
  });
3298
+ const disposeModels = ctx.webServer.register({
3299
+ kind: "exact",
3300
+ path: POOL_DOUBAO_MODELS_PATH,
3301
+ handler: async (req, res) => {
3302
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3303
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3304
+ /**
3305
+ * The same list the picker gets.
3306
+ *
3307
+ * The card used to render its own copy from the static catalogue, so a signed-in
3308
+ * account showed six models on the card and twelve in the picker. One route, one
3309
+ * answer.
3310
+ */
3311
+ try {
3312
+ return json$1(res, 200, {
3313
+ ok: true,
3314
+ models: await fetchLiveModels(deps.session())
3315
+ });
3316
+ } catch (error) {
3317
+ return json$1(res, 200, {
3318
+ ok: false,
3319
+ models: [],
3320
+ error: error instanceof Error ? error.message : String(error)
3321
+ });
3322
+ }
3323
+ }
3324
+ });
3325
+ const disposeCampaign = ctx.webServer.register({
3326
+ kind: "exact",
3327
+ path: POOL_DOUBAO_CAMPAIGN_PATH,
3328
+ handler: async (req, res) => {
3329
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3330
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3331
+ const session = deps.session();
3332
+ const campaign = await fetchCampaign(session);
3333
+ return json$1(res, 200, {
3334
+ ok: campaign.error === void 0,
3335
+ signedIn: session !== void 0,
3336
+ ...campaign
3337
+ });
3338
+ }
3339
+ });
3340
+ const disposeClaim = ctx.webServer.register({
3341
+ kind: "exact",
3342
+ path: POOL_DOUBAO_CLAIM_PATH,
3343
+ handler: async (req, res) => {
3344
+ if (req.method !== "POST") return json$1(res, 405, { error: "method not allowed" });
3345
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3346
+ const result = await claimTasks(deps.session());
3347
+ return json$1(res, 200, {
3348
+ ok: result.failed === 0,
3349
+ ...result
3350
+ });
3351
+ }
3352
+ });
3353
+ const disposeAutomation = ctx.webServer.register({
3354
+ kind: "exact",
3355
+ path: POOL_DOUBAO_AUTOMATION_PATH,
3356
+ handler: async (req, res) => {
3357
+ if (!loopbackOrigin$1(req)) return json$1(res, 403, { error: "origin-not-trusted" });
3358
+ const automation = deps.automation();
3359
+ try {
3360
+ if (req.method === "POST") {
3361
+ /**
3362
+ * `{ enabled }` flips the switch; an empty body runs one pass.
3363
+ *
3364
+ * Two actions, one route, because they are one concept to the card: the pane's
3365
+ * checkbox and its "run now" button both mean "make the automation do its job".
3366
+ */
3367
+ const body = await readJson(req);
3368
+ if (typeof body["enabled"] === "boolean") {
3369
+ automation.setEnabled(body["enabled"]);
3370
+ return json$1(res, 200, {
3371
+ ok: true,
3372
+ ...automation.state()
3373
+ });
3374
+ }
3375
+ return json$1(res, 200, {
3376
+ ok: true,
3377
+ ...await automation.runOnce()
3378
+ });
3379
+ }
3380
+ if (req.method !== "GET") return json$1(res, 405, { error: "method not allowed" });
3381
+ return json$1(res, 200, {
3382
+ ok: true,
3383
+ ...automation.state()
3384
+ });
3385
+ } catch (error) {
3386
+ return json$1(res, 500, { error: error instanceof Error ? error.message : String(error) });
3387
+ }
3388
+ }
3389
+ });
2391
3390
  return () => {
2392
3391
  disposeSession();
2393
3392
  disposeQuota();
3393
+ disposeModels();
3394
+ disposeCampaign();
3395
+ disposeClaim();
3396
+ disposeAutomation();
2394
3397
  };
2395
3398
  });
2396
3399
  }
2397
3400
  //#endregion
3401
+ //#region src/doubao-automation.ts
3402
+ /**
3403
+ * Doubao's credit automation.
3404
+ *
3405
+ * WHAT "AUTOMATION" MEANS HERE
3406
+ *
3407
+ * WorkBuddy's automation claims a daily check-in. Doubao has no working check-in endpoint — it
3408
+ * answers `710010702 系统错误` for every account, including from Doubao's own client — but it
3409
+ * does have campaign tasks whose rewards are collectable, and `daily_signin` is one of them.
3410
+ * So the automation is: collect every claimable task, on a schedule, and record what it did.
3411
+ *
3412
+ * The distinction matters for what the card can promise. This cannot make a check-in succeed;
3413
+ * it can only collect what the server has already marked finished. When nothing is claimable it
3414
+ * says so rather than reporting a failure.
3415
+ *
3416
+ * @module dsh-xdpool/doubao-automation
3417
+ */
3418
+ /** How often a pass runs while the switch is on. */
3419
+ const INTERVAL_MS = 216e5;
3420
+ /**
3421
+ * The automation, wired to a session getter.
3422
+ *
3423
+ * `runOn()` is separate from the timer so the card's manual button and the scheduled pass do the
3424
+ * same thing — a second implementation for the button would be the one that drifts.
3425
+ */
3426
+ function createDoubaoAutomation(options) {
3427
+ let enabled = false;
3428
+ let state = { enabled: false };
3429
+ let timer;
3430
+ const clearTimer = () => {
3431
+ if (timer !== void 0) {
3432
+ clearInterval(timer);
3433
+ timer = void 0;
3434
+ }
3435
+ };
3436
+ /**
3437
+ * One pass.
3438
+ *
3439
+ * "Nothing to collect" is recorded as a note rather than a failure: an account whose tasks are
3440
+ * all done has nothing wrong with it, and reporting that as an error every six hours is how a
3441
+ * working feature reads as broken.
3442
+ */
3443
+ const runPass = async () => {
3444
+ const session = options.session();
3445
+ if (session === void 0) {
3446
+ state = {
3447
+ ...state,
3448
+ enabled,
3449
+ lastNote: "还没有登录态"
3450
+ };
3451
+ return state;
3452
+ }
3453
+ /**
3454
+ * The daily sign-in first, then the tasks.
3455
+ *
3456
+ * `daily_signin` appears in the campaign as a task, but the endpoint its own button calls
3457
+ * is a separate one — and claiming the task does not perform the sign-in that earns it. So
3458
+ * both are attempted, and a refused sign-in does not stop the task collection that follows.
3459
+ */
3460
+ const checkin = await attemptCheckin(session);
3461
+ const before = await fetchCampaign(session);
3462
+ if (before.error !== void 0) {
3463
+ state = {
3464
+ ...state,
3465
+ enabled,
3466
+ lastNote: before.error
3467
+ };
3468
+ return state;
3469
+ }
3470
+ const checkinNote = checkin.ok ? "签到成功" : checkin.message;
3471
+ if (before.claimableCount === 0) {
3472
+ state = {
3473
+ ...state,
3474
+ enabled,
3475
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
3476
+ lastClaimed: 0,
3477
+ lastNote: "今天没有可领取的积分",
3478
+ lastCheckin: checkinNote
3479
+ };
3480
+ return state;
3481
+ }
3482
+ const result = await claimTasks(session);
3483
+ state = {
3484
+ ...state,
3485
+ enabled,
3486
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
3487
+ lastClaimed: result.claimed,
3488
+ lastCheckin: checkinNote,
3489
+ ...result.reason === void 0 ? {} : { lastNote: result.reason }
3490
+ };
3491
+ options.logger?.info?.(`[xdpool] doubao automation: claimed ${String(result.claimed)} task(s)` + (result.failed > 0 ? `, ${String(result.failed)} failed` : ""));
3492
+ return state;
3493
+ };
3494
+ const arm = () => {
3495
+ clearTimer();
3496
+ if (!enabled) return;
3497
+ timer = setInterval(() => {
3498
+ runPass();
3499
+ }, INTERVAL_MS);
3500
+ if (typeof timer === "object" && timer !== null && "unref" in timer) timer.unref();
3501
+ };
3502
+ return {
3503
+ state: () => state,
3504
+ setEnabled: (next) => {
3505
+ enabled = next;
3506
+ state = {
3507
+ ...state,
3508
+ enabled: next
3509
+ };
3510
+ arm();
3511
+ if (next) runPass();
3512
+ },
3513
+ runOnce: async () => await runPass(),
3514
+ stop: () => {
3515
+ clearTimer();
3516
+ }
3517
+ };
3518
+ }
3519
+ //#endregion
2398
3520
  //#region src/file-perms.ts
2399
3521
  /**
2400
3522
  * Write a file that holds credentials, without leaving it world-readable.
@@ -3435,8 +4557,20 @@ function contentOfFrame(frame) {
3435
4557
  * Body markers win over status, because the upstream reuses 400/200 for
3436
4558
  * several distinct conditions.
3437
4559
  */
4560
+ /** Business codes the gateway uses for "this account is risk-flagged". */
4561
+ const RISK_BLOCK_CODES = ["11140", "11141"];
3438
4562
  function classifyUpstreamError(status, body) {
3439
4563
  if (status === 402) return "hard_credit";
4564
+ /**
4565
+ * Risk control first, and only for a 403.
4566
+ *
4567
+ * `11140` is what the gateway returns when the ACCOUNT is flagged. It arrives with 403, so
4568
+ * the blanket rule below swallowed it into `session_dead` and the card told the user their
4569
+ * key was invalid — several times, since re-signing in changes nothing about a flag.
4570
+ */
4571
+ if (status === 403) {
4572
+ for (const code of RISK_BLOCK_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "risk_blocked";
4573
+ }
3440
4574
  if (status === 401 || status === 403) return "session_dead";
3441
4575
  const lower = body.toLowerCase();
3442
4576
  for (const code of HARD_CREDIT_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "hard_credit";
@@ -7966,60 +9100,8 @@ function catalogFromUpstream(models, region = "cn") {
7966
9100
  return models.map(toModelInfo);
7967
9101
  }
7968
9102
  //#endregion
7969
- //#region src/channels.ts
7970
- /**
7971
- * Mount the vendored free-channel pack.
7972
- *
7973
- * Thirteen login channels — CodeArts, WorkBuddy 国内版/国际版, LobsterAI, Qoder ×2,
7974
- * TRAE, Cline, Loomy, Raccoon, MiniMax Code, ZCode and Gemini — arrive as one
7975
- * MIT-licensed bundle we carry rather than re-implement. Each is a real protocol
7976
- * adapter with its own login handshake; rewriting twelve of them here would only
7977
- * produce a slower, drift-prone copy of work that upstream already validates.
7978
- *
7979
- * Provenance and rebuild notes live in `vendor/channel-pack/NOTICE.md`.
7980
- */
7981
- /** Directory of this module, used to locate the sibling `vendor/` tree. */
7982
- const HERE = dirname(fileURLToPath(import.meta.url));
7983
- /**
7984
- * Where the pack lives relative to the built entry.
7985
- *
7986
- * `src/index.ts` compiles to `lib/index.js`, so from there `vendor/` is one level
7987
- * up. Kept as a computed path rather than `import.meta.resolve` because the
7988
- * installed layout is a flat `node_modules/dsh-xdpool/{lib,vendor}`,
7989
- * which is not resolvable as a bare specifier.
7990
- */
7991
- const PACK_ENTRY = join(HERE, "..", "vendor", "channel-pack", "pack.js");
7992
- /**
7993
- * `PACK_ENTRY` as a URL, which is the only spelling `import()` accepts.
7994
- *
7995
- * On POSIX the two are interchangeable enough that the bug hid for a while; on
7996
- * Windows a bare `D:\...` path is not a specifier at all, and the loader answers
7997
- * `Only URLs with a scheme in: file, data, node, and electron are supported`
7998
- * before it ever looks at the disk. `pathToFileURL` also handles the drive
7999
- * letter and the backslashes, so this is the portable spelling rather than a
8000
- * Windows special case.
8001
- */
8002
- const PACK_ENTRY_URL = pathToFileURL(PACK_ENTRY).href;
8003
- /**
8004
- * The thirteen channels the pack registers, with the copy the card shows.
8005
- *
8006
- * `org`, `accent` and the login flow are lifted from the pack's own table
8007
- * (`CHANNEL_PROVIDERS` in its client bundle) so the card and the pack cannot
8008
- * disagree about what a channel is. Nothing here decides behaviour — the pack
8009
- * still owns the protocol — so a channel that changes its login flow upstream
8010
- * needs a data edit here, not a code change.
8011
- *
8012
- * `note` is the exception: it is ours, not the pack's, and it is Chinese on
8013
- * purpose. The user asked for each card to state in Chinese how much of that
8014
- * vendor's model usage is actually free, because the roster they were reading
8015
- * said "每日免费额度" eleven times over — a phrase that names the existence of a
8016
- * free allowance without ever saying what it is. Each line below names the
8017
- * models on the free line and, where the vendor publishes a figure, the figure
8018
- * itself. Where no figure is published, the line says so rather than inventing
8019
- * a number: a quota we guessed would be the one number on the card a user would
8020
- * plan their day around.
8021
- */
8022
- const REGISTERED_CHANNELS = [
9103
+ //#region src/channel-roster.ts
9104
+ const REGISTERED_CHANNELS$1 = [
8023
9105
  {
8024
9106
  id: "codearts",
8025
9107
  name: "CodeArts",
@@ -8180,9 +9262,72 @@ const REGISTERED_CHANNELS = [
8180
9262
  accent: "#325AB4",
8181
9263
  note: "浏览器扫码登录一次;对话与「工作任务」模型、生图、活动赠送额度都在这里",
8182
9264
  login: "browser",
9265
+ loginHint: "doubao",
8183
9266
  credits: { quota: true }
8184
9267
  }
8185
9268
  ];
9269
+ //#endregion
9270
+ //#region src/channels.ts
9271
+ /**
9272
+ * Mount the vendored free-channel pack.
9273
+ *
9274
+ * Thirteen login channels — CodeArts, WorkBuddy 国内版/国际版, LobsterAI, Qoder ×2,
9275
+ * TRAE, Cline, Loomy, Raccoon, MiniMax Code, ZCode and Gemini — arrive as one
9276
+ * MIT-licensed bundle we carry rather than re-implement. Each is a real protocol
9277
+ * adapter with its own login handshake; rewriting twelve of them here would only
9278
+ * produce a slower, drift-prone copy of work that upstream already validates.
9279
+ *
9280
+ * Provenance and rebuild notes live in `vendor/channel-pack/NOTICE.md`.
9281
+ */
9282
+ /** Directory of this module, used to locate the sibling `vendor/` tree. */
9283
+ const HERE = dirname(fileURLToPath(import.meta.url));
9284
+ /**
9285
+ * Where the pack lives relative to the built entry.
9286
+ *
9287
+ * `src/index.ts` compiles to `lib/index.js`, so from there `vendor/` is one level
9288
+ * up. Kept as a computed path rather than `import.meta.resolve` because the
9289
+ * installed layout is a flat `node_modules/dsh-xdpool/{lib,vendor}`,
9290
+ * which is not resolvable as a bare specifier.
9291
+ */
9292
+ const PACK_ENTRY = join(HERE, "..", "vendor", "channel-pack", "pack.js");
9293
+ /**
9294
+ * `PACK_ENTRY` as a URL, which is the only spelling `import()` accepts.
9295
+ *
9296
+ * On POSIX the two are interchangeable enough that the bug hid for a while; on
9297
+ * Windows a bare `D:\...` path is not a specifier at all, and the loader answers
9298
+ * `Only URLs with a scheme in: file, data, node, and electron are supported`
9299
+ * before it ever looks at the disk. `pathToFileURL` also handles the drive
9300
+ * letter and the backslashes, so this is the portable spelling rather than a
9301
+ * Windows special case.
9302
+ */
9303
+ const PACK_ENTRY_URL = pathToFileURL(PACK_ENTRY).href;
9304
+ /**
9305
+ * The thirteen channels the pack registers, with the copy the card shows.
9306
+ *
9307
+ * `org`, `accent` and the login flow are lifted from the pack's own table
9308
+ * (`CHANNEL_PROVIDERS` in its client bundle) so the card and the pack cannot
9309
+ * disagree about what a channel is. Nothing here decides behaviour — the pack
9310
+ * still owns the protocol — so a channel that changes its login flow upstream
9311
+ * needs a data edit here, not a code change.
9312
+ *
9313
+ * `note` is the exception: it is ours, not the pack's, and it is Chinese on
9314
+ * purpose. The user asked for each card to state in Chinese how much of that
9315
+ * vendor's model usage is actually free, because the roster they were reading
9316
+ * said "每日免费额度" eleven times over — a phrase that names the existence of a
9317
+ * free allowance without ever saying what it is. Each line below names the
9318
+ * models on the free line and, where the vendor publishes a figure, the figure
9319
+ * itself. Where no figure is published, the line says so rather than inventing
9320
+ * a number: a quota we guessed would be the one number on the card a user would
9321
+ * plan their day around.
9322
+ */
9323
+ /**
9324
+ * The roster lives in `channel-roster.ts`, which has no imports.
9325
+ *
9326
+ * It moved because the card needs the same names before the host answers, and the card runs in
9327
+ * the browser: importing them from here — a module that reads the filesystem to find the pack —
9328
+ * put `node:fs` in the client bundle, which does not load at all.
9329
+ */
9330
+ const REGISTERED_CHANNELS = REGISTERED_CHANNELS$1;
8186
9331
  /**
8187
9332
  * The two channels this plugin already serves from its own account pool.
8188
9333
  *
@@ -15665,15 +16810,18 @@ const POOL_PROVIDER_BY_REGION = {
15665
16810
  global: XDPOOL_GLOBAL_PROVIDER
15666
16811
  };
15667
16812
  /**
15668
- * Display name each region registers under, so the picker can group them.
16813
+ * The name each pool region shows in the model picker.
15669
16814
  *
15670
- * "XD Pool" rather than the old "WorkBuddy XD Pool": the picker row is the only
15671
- * place this string surfaces, and the brand the user asked for is XD Pool. The
15672
- * REGION suffix stays because both lanes register real providers under different
15673
- * ids — dropping it would leave two identically-named groups in the dropdown.
16815
+ * It is the CHANNEL's name, not the plugin's.
15674
16816
  *
15675
- * Display name only. The provider ids above are what the host matches on when it
15676
- * persists a selection, so renaming a group must never touch them.
16817
+ * Every account in these two pools arrived through a scan sign-in on the channel card, so the
16818
+ * reader who picked a model here was working with "WorkBuddy 国内版" a moment earlier. Calling
16819
+ * the group "XD Pool" asked them to learn a second name for the same accounts — and, because
16820
+ * the vendored pack registers the same two pools under its own ids, it produced FOUR groups
16821
+ * where two belonged.
16822
+ *
16823
+ * The provider IDS are untouched: the host persists a selection by id, so renaming a group
16824
+ * must never move it. Only what the reader sees changes.
15677
16825
  */
15678
16826
  const POOL_NAME_BY_REGION = {
15679
16827
  cn: "XD Pool(国内版)",
@@ -17095,7 +18243,7 @@ function mintRequestId(timestamp = Date.now()) {
17095
18243
  const value = BigInt(timestamp) * 4096n + 1n;
17096
18244
  let hex = "";
17097
18245
  for (let i = 0; i < 6; i += 1) hex += (value >> BigInt(40 - 8 * i) & 255n).toString(16).padStart(2, "0");
17098
- return `msg_${hex}${base62From(crypto.randomBytes(14))}`;
18246
+ return `msg_${hex}${base62From(crypto$1.randomBytes(14))}`;
17099
18247
  }
17100
18248
  /** Does `id` already look like a v2-canonical session (shape *and* descending counter)? */
17101
18249
  function isCanonicalSession(id) {
@@ -17128,7 +18276,7 @@ function sessionFromSeed(seed) {
17128
18276
  const offset = h & 2147483647n;
17129
18277
  const ts = SESSION_EPOCH + offset % (30n * 24n * 3600n * 1000n);
17130
18278
  const seq = Number(h >> 31n & 63n) + 1;
17131
- return `ses_${canonicalPrefix(ts, seq > 63 ? 63 : seq)}${base62From(crypto.createHash("sha256").update(`xdpool-free-suffix\0${seed}`, "utf8").digest().subarray(0, 14))}`;
18279
+ return `ses_${canonicalPrefix(ts, seq > 63 ? 63 : seq)}${base62From(crypto$1.createHash("sha256").update(`xdpool-free-suffix\0${seed}`, "utf8").digest().subarray(0, 14))}`;
17132
18280
  }
17133
18281
  /** Return `id` if already canonical; otherwise derive a deterministic canonical session from it. */
17134
18282
  function canonicalizeSession(id) {
@@ -17157,7 +18305,7 @@ function sessionForConversation(sessionId) {
17157
18305
  */
17158
18306
  function requestIdFor(sessionId, turnSeed) {
17159
18307
  if (text$1(turnSeed) === "") return mintRequestId();
17160
- const digest = crypto.createHash("sha256").update(`xdpool-free-req\0${sessionId}\0${turnSeed}`, "utf8").digest();
18308
+ const digest = crypto$1.createHash("sha256").update(`xdpool-free-req\0${sessionId}\0${turnSeed}`, "utf8").digest();
17161
18309
  const id = `msg_${digest.subarray(0, 6).toString("hex")}${base62From(digest.subarray(6, 20))}`;
17162
18310
  return REQUEST_RE.test(id) ? id : mintRequestId();
17163
18311
  }
@@ -18144,14 +19292,14 @@ function conversationKeyOf$1(body) {
18144
19292
  for (const raw of messages) {
18145
19293
  if (!isRecord(raw) || text(raw.role) !== "user") continue;
18146
19294
  const content = typeof raw.content === "string" ? raw.content : JSON.stringify(raw.content ?? "");
18147
- return crypto.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 32);
19295
+ return crypto$1.createHash("sha256").update(content, "utf8").digest("hex").slice(0, 32);
18148
19296
  }
18149
- return crypto.createHash("sha256").update("xdpool-free-conversation", "utf8").digest("hex").slice(0, 32);
19297
+ return crypto$1.createHash("sha256").update("xdpool-free-conversation", "utf8").digest("hex").slice(0, 32);
18150
19298
  }
18151
19299
  /** The envelope one chat chunk carries, so frames from different lanes match. */
18152
19300
  function chatChunk(model, delta, finishReason) {
18153
19301
  return JSON.stringify({
18154
- id: `chatcmpl-${crypto.randomBytes(8).toString("hex")}`,
19302
+ id: `chatcmpl-${crypto$1.randomBytes(8).toString("hex")}`,
18155
19303
  object: "chat.completion.chunk",
18156
19304
  created: Math.floor(Date.now() / 1e3),
18157
19305
  model,
@@ -18184,7 +19332,7 @@ function createFreeLaneSource(catalog, logger, usageRecorder) {
18184
19332
  const plan = applyFingerprint(payload, wire);
18185
19333
  if (warnings.length > 0) logger?.warn?.(`free lane: ${warnings.length} image block(s) could not be forwarded; they were dropped`);
18186
19334
  const tracker = new StreamTracker(Date.now());
18187
- const turnId = `free-${crypto.randomBytes(8).toString("hex")}`;
19335
+ const turnId = `free-${crypto$1.randomBytes(8).toString("hex")}`;
18188
19336
  let ok = false;
18189
19337
  let recordedUsage = void 0;
18190
19338
  try {
@@ -22549,6 +23697,7 @@ const KIND_STATUS = {
22549
23697
  hard_credit: 402,
22550
23698
  soft_rate: 429,
22551
23699
  session_dead: 401,
23700
+ risk_blocked: 403,
22552
23701
  not_found: 502,
22553
23702
  server: 502,
22554
23703
  client: 400
@@ -23453,6 +24602,7 @@ function createWorkBuddyShim(options) {
23453
24602
  };
23454
24603
  if (result.kind === "soft_rate") pool.penalize(account.id, parseRateLimitReset(result.message), member.modelId);
23455
24604
  else if (result.kind === "session_dead") pool.penalizeCredentialDead(account.id);
24605
+ else if (result.kind === "risk_blocked") pool.penalize(account.id, 18e5, member.modelId);
23456
24606
  else if (result.kind === "hard_credit") pool.penalizeExhausted(account.id);
23457
24607
  noteSwitch(member.modelId, result.kind, result.status);
23458
24608
  continue;
@@ -25936,8 +27086,18 @@ function apply(ctx, config = {}) {
25936
27086
  if (stored !== void 0) adoptDoubaoSession(stored);
25937
27087
  });
25938
27088
  const doubaoLlm = createDoubaoLlm({ session: () => doubaoSession });
27089
+ /**
27090
+ * Doubao's credit automation.
27091
+ *
27092
+ * Created beside the lane because both read the same session: a sign-in that lands while the
27093
+ * automation is armed must be picked up on the next pass without anything being re-wired.
27094
+ */
27095
+ const doubaoAutomation = createDoubaoAutomation({
27096
+ session: () => doubaoSession,
27097
+ logger: ctx.logger
27098
+ });
25939
27099
  /** The ids Doubao's catalogue knows, so `stream` can tell its models from the host's. */
25940
- const doubaoModelIds = new Set(DOUBAO_MODELS.map((model) => model.id));
27100
+ const doubaoModelIds = new Set(DOUBAO_MODELS$1.map((model) => model.id));
25941
27101
  const hostLlm = ctx.llm;
25942
27102
  const channelLane = createChannelLane({
25943
27103
  llm: {
@@ -26050,6 +27210,7 @@ function apply(ctx, config = {}) {
26050
27210
  shims.cn.close();
26051
27211
  shims.global.close();
26052
27212
  core.scheduler.stop();
27213
+ doubaoAutomation.stop();
26053
27214
  });
26054
27215
  relay.ready.catch((error) => {
26055
27216
  ctx.logger.warn(`xdpool relay: startup failed — ${String(error)}`);
@@ -26145,7 +27306,8 @@ function apply(ctx, config = {}) {
26145
27306
  clear: () => {
26146
27307
  adoptDoubaoSession(void 0);
26147
27308
  removeStoredSession();
26148
- }
27309
+ },
27310
+ automation: () => doubaoAutomation
26149
27311
  });
26150
27312
  return registerPoolStatusRoute(webCtx, {
26151
27313
  pool: core.pool,
@@ -26467,8 +27629,32 @@ function apply(ctx, config = {}) {
26467
27629
  let releaseAdapterFree;
26468
27630
  let releaseDirectory;
26469
27631
  try {
26470
- releaseAdapterCn = ctx.llm.registerAdapter([POOL_PROVIDER_BY_REGION.cn], adaptersByRegion.cn.adapter);
26471
- releaseAdapterGlobal = ctx.llm.registerAdapter([POOL_PROVIDER_BY_REGION.global], adaptersByRegion.global.adapter);
27632
+ /**
27633
+ * The two region adapters are NOT registered — issue #148.
27634
+ *
27635
+ * `buddy` and `workbuddy` are what the scan-login lanes are called in the picker, and
27636
+ * they reach the same accounts through the same endpoint. Registering these two as
27637
+ * well put FOUR groups in the model picker for two account pools: "XD Pool 国内版" /
27638
+ * "WorkBuddy 国内版" and the same pair for the international side, all describing one
27639
+ * set of sign-ins.
27640
+ *
27641
+ * The accounts themselves are untouched: the pool document, the card, the balance
27642
+ * panel and the credit dot all read `core.pool` through the status route, none of
27643
+ * which involves an adapter. What changes is only which groups the PICKER lists.
27644
+ *
27645
+ * The adapters are still BUILT above — the loopback shims serve their traffic — so a
27646
+ * request that arrives on the pool's own path still works; it is the duplicate
27647
+ * listing entry that goes.
27648
+ */
27649
+ /**
27650
+ * A handle that does nothing, in the shape the caller disposes.
27651
+ *
27652
+ * `AdapterHandle` is a disposer FUNCTION carrying a `replace` method, so an empty
27653
+ * object would not typecheck and would also break the dispose path.
27654
+ */
27655
+ const detached = Object.assign(() => {}, { replace: () => {} });
27656
+ releaseAdapterCn = detached;
27657
+ releaseAdapterGlobal = detached;
26472
27658
  releaseAdapterAggregate = ctx.llm.registerAdapter([XDPOOL_AGGREGATE_PROVIDER], adaptersByRegion.aggregate.adapter);
26473
27659
  releaseAdapterFree = ctx.llm.registerAdapter([XDPOOL_FREE_PROVIDER], adaptersByRegion.free.adapter);
26474
27660
  } catch (error) {