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/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-xdpool",
3
3
  "displayName": "DSH XD Pool",
4
4
  "description": "One DSH model pool for every free quota you have: merge all locally signed-in WorkBuddy accounts with auto-failover, sign in to 13 vendors by QR/web, aggregate 76 vendors' free tiers, plus a usage dashboard, model routing, a local OpenAI-compatible gateway and a points-automation suite.",
5
- "version": "2.7.0",
5
+ "version": "2.7.2",
6
6
  "license": "MIT",
7
7
  "author": "XDTrees",
8
8
  "homepage": "https://github.com/XDTrees/dsh-xdpool#readme",
@@ -30066,7 +30066,76 @@ var AccountPool = class {
30066
30066
  /** 读取账号列表(进程内权威副本)。 */
30067
30067
  readAccounts() {
30068
30068
  this.ensureLoaded();
30069
- return this.cache;
30069
+ /**
30070
+ * [xdpool-local] Bring in accounts the CREDENTIAL STORE knows and the pool document does
30071
+ * not — the missing half of the four-group report (#148).
30072
+ *
30073
+ * A scan login writes `<PREFIX>_ACCOUNT_<hash>` into the host's credentials. The pool
30074
+ * document is written separately, and the two can drift: a reinstall, a pool reset, or an
30075
+ * account created by a DIFFERENT plugin that shares the prefix leaves a live credential with
30076
+ * no pool row. `readAccounts` then answers "no accounts", the catalogue gate hides the
30077
+ * provider, and the card shows hard-coded fallbacks while a valid session sits unused.
30078
+ *
30079
+ * The merge is lazy and cached: the credential file is read once per load, and an account is
30080
+ * only synthesised when its ref is not already present. Nothing is persisted — the pool
30081
+ * document stays the source of truth for anything the user changed (enabled, limits, names),
30082
+ * and a synthesised row exists only to make the credential reachable.
30083
+ */
30084
+ if (this.orphanCache === void 0) {
30085
+ this.orphanCache = this.collectOrphanAccounts();
30086
+ }
30087
+ return this.orphanCache.length === 0 ? this.cache : [...this.cache, ...this.orphanCache];
30088
+ }
30089
+ /** Cached result of {@link collectOrphanAccounts}; `undefined` means "not computed yet". */
30090
+ orphanCache = void 0;
30091
+ /**
30092
+ * Accounts that exist as credentials but not as pool rows.
30093
+ *
30094
+ * Runs synchronously because `readAccounts` is called from synchronous paths all over the
30095
+ * adapter code; the credential file is small and this happens once per load.
30096
+ */
30097
+ collectOrphanAccounts() {
30098
+ var out = [];
30099
+ try {
30100
+ var fs = require("node:fs");
30101
+ var os = require("node:os");
30102
+ var path = require("node:path");
30103
+ var home = process.env.DSH_HOME ?? path.join(os.homedir(), ".dsh");
30104
+ var file = path.join(home, ".credentials.yaml");
30105
+ var text;
30106
+ try {
30107
+ text = fs.readFileSync(file, "utf8");
30108
+ } catch {
30109
+ return out;
30110
+ }
30111
+ var seen = new Set(this.cache.map((a) => a.credentialRef).filter(Boolean));
30112
+ var providers = /* @__PURE__ */ new Set(this.cache.map((a) => a.provider));
30113
+ var lines = text.split(String.fromCharCode(10));
30114
+ for (var i = 0; i < lines.length; i += 1) {
30115
+ var match = /^\s{0,4}([A-Z][A-Z0-9_]*):/u.exec(lines[i]);
30116
+ if (match === null) continue;
30117
+ var ref = match[1];
30118
+ var at = ref.indexOf("_ACCOUNT_");
30119
+ if (at <= 0 || seen.has(ref)) continue;
30120
+ var provider = ref.slice(0, at).toLowerCase();
30121
+ // Only for providers this pool already knows about: a ref for a vendor the pack has no
30122
+ // adapter for would produce a row nothing can serve.
30123
+ if (!providers.has(provider)) continue;
30124
+ seen.add(ref);
30125
+ out.push({
30126
+ id: "cred-" + ref.slice(at + 9).toLowerCase(),
30127
+ provider,
30128
+ credentialRef: ref,
30129
+ enabled: true,
30130
+ refreshable: false,
30131
+ nickname: provider + " account",
30132
+ createdAt: 0
30133
+ });
30134
+ }
30135
+ } catch {
30136
+ return out;
30137
+ }
30138
+ return out;
30070
30139
  }
30071
30140
  /**
30072
30141
  * 串行化状态文档的落盘,并在**轮到本次时**重新取一次快照。
@@ -30757,8 +30826,62 @@ var AccountPool = class {
30757
30826
  const credential = await this.resolveCredentialByRef(entry.credentialRef);
30758
30827
  if (credential !== void 0) return true;
30759
30828
  }
30829
+ /**
30830
+ * [xdpool-local] A signed-in account may exist as a CREDENTIAL without a pool entry.
30831
+ *
30832
+ * A scan login writes `<PREFIX>_ACCOUNT_<hash>` into the host's credential store and tells
30833
+ * the pack about it through `account.create`. When the pool document and the credential
30834
+ * store disagree — the case after a pool reset, a plugin reinstall, or an account created by
30835
+ * a DIFFERENT plugin that shares the prefix — this method answered "not logged in", and the
30836
+ * gate above answered it by hiding the whole provider: the card showed five hard-coded
30837
+ * fallback models while eighteen real ones sat behind a session that was perfectly valid.
30838
+ *
30839
+ * So the credential store is consulted too, by prefix. Anything that resolves counts: the
30840
+ * question this answers is "may the catalogue be shown", and one usable credential is
30841
+ * enough for that.
30842
+ */
30843
+ const prefix = `${provider.toUpperCase().replace(/[^A-Z0-9]/gu, '_')}_ACCOUNT_`;
30844
+ for (const ref of await this.credentialRefsWithPrefix?.(prefix) ?? []) {
30845
+ const credential = await this.resolveCredentialByRef(ref);
30846
+ if (credential !== void 0) return true;
30847
+ }
30760
30848
  return false;
30761
30849
  }
30850
+ /**
30851
+ * Credential refs that start with `prefix`.
30852
+ *
30853
+ * The host's credential service resolves by EXACT ref and does not enumerate, so the store
30854
+ * file is read directly. Absent or unreadable means "no evidence either way" — the caller
30855
+ * then answers from the pool alone, which is the old behaviour.
30856
+ */
30857
+ async credentialRefsWithPrefix(prefix) {
30858
+ try {
30859
+ const { readFile } = await import("node:fs/promises");
30860
+ const { join } = await import("node:path");
30861
+ const { homedir } = await import("node:os");
30862
+ const candidates = [
30863
+ join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), ".credentials.yaml"),
30864
+ join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), ".credentials.json")
30865
+ ];
30866
+ for (const file of candidates) {
30867
+ let text;
30868
+ try {
30869
+ text = await readFile(file, "utf8");
30870
+ } catch {
30871
+ continue;
30872
+ }
30873
+ const matches = [];
30874
+ for (const line of text.split(String.fromCharCode(10))) {
30875
+ const match = /^\s{0,4}([A-Z][A-Z0-9_]*):/u.exec(line);
30876
+ if (match !== null && match[1].startsWith(prefix)) matches.push(match[1]);
30877
+ }
30878
+ if (matches.length > 0) return [...new Set(matches)];
30879
+ }
30880
+ return [];
30881
+ } catch {
30882
+ return [];
30883
+ }
30884
+ }
30762
30885
  /**
30763
30886
  * 按账号 id 解析凭据(**不检查 enabled**)。
30764
30887
  *
@@ -37771,6 +37894,59 @@ function buildQoderInferPayload(ask, requestId = crypto.randomUUID()) {
37771
37894
  };
37772
37895
  }
37773
37896
  var gluePromise = null;
37897
+ /**
37898
+ * [xdpool-local] Keep a Qoder payload inside the WASM's memory budget — issue #155.
37899
+ *
37900
+ * WHAT IS CUT, AND IN WHICH ORDER
37901
+ *
37902
+ * Oldest conversation turns go first: they are the least likely to matter for the next reply,
37903
+ * and dropping one whole turn keeps the message list valid (a lone tool result without its
37904
+ * call is what makes a request *invalid* rather than merely shorter). Tool schemas are never
37905
+ * cut — a call without its schema is worse than a shorter history — but the largest ones are
37906
+ * trimmed of their `description`, which is prose the model can do without.
37907
+ *
37908
+ * The budget is deliberately below the ceiling: serialisation produces several copies at
37909
+ * once, so a payload that merely FITS is not enough.
37910
+ */
37911
+ const QODER_PAYLOAD_BYTE_BUDGET = 700 * 1024;
37912
+
37913
+ function shrinkQoderPayload(payload) {
37914
+ const measure = (value) => {
37915
+ try {
37916
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
37917
+ } catch {
37918
+ return Number.MAX_SAFE_INTEGER;
37919
+ }
37920
+ };
37921
+ if (measure(payload) <= QODER_PAYLOAD_BYTE_BUDGET) return payload;
37922
+ const out = { ...payload, messages: Array.isArray(payload.messages) ? [...payload.messages] : [] };
37923
+ // Oldest first, but never the last message: that is the actual question.
37924
+ while (out.messages.length > 2 && measure(out) > QODER_PAYLOAD_BYTE_BUDGET) {
37925
+ out.messages.shift();
37926
+ }
37927
+ // Still too big: drop tool descriptions, which are prose rather than contract.
37928
+ if (measure(out) > QODER_PAYLOAD_BYTE_BUDGET && Array.isArray(out.tools)) {
37929
+ out.tools = out.tools.map((tool) => {
37930
+ const fn = tool && typeof tool === "object" ? tool.function : void 0;
37931
+ if (!fn || typeof fn !== "object" || typeof fn.description !== "string") return tool;
37932
+ return { ...tool, function: { ...fn, description: "" } };
37933
+ });
37934
+ }
37935
+ // Last resort: trim the longest message bodies from the front of the list.
37936
+ let guard = 0;
37937
+ while (measure(out) > QODER_PAYLOAD_BYTE_BUDGET && out.messages.length > 1 && guard < 64) {
37938
+ guard += 1;
37939
+ const first = out.messages[0];
37940
+ if (first && typeof first === "object" && typeof first.content === "string" && first.content.length > 2000) {
37941
+ out.messages[0] = { ...first, content: `${first.content.slice(0, 2000)}
37942
+ …(已截断)` };
37943
+ continue;
37944
+ }
37945
+ out.messages.shift();
37946
+ }
37947
+ return out;
37948
+ }
37949
+
37774
37950
  async function getGlue() {
37775
37951
  gluePromise ??= createGlue();
37776
37952
  return gluePromise;
@@ -37990,7 +38166,22 @@ var QoderEncryptedInfer = class _QoderEncryptedInfer {
37990
38166
  const result = g.callPointer((stack) => {
37991
38167
  const host = g.writeString(this.host);
37992
38168
  const hostLen = g.lastLength();
37993
- const body = g.writeString(JSON.stringify(payload));
38169
+ /**
38170
+ * [xdpool-local] Shrink the payload before it reaches the WASM — issue #155.
38171
+ *
38172
+ * The encrypted-infer glue declares ~1 MB of linear memory, and the whole request is
38173
+ * written into it as UTF-8: the plaintext JSON string, its encoded copy and the WASM
38174
+ * copy all exist at once. A body approaching that ceiling makes `__wbindgen_export2`
38175
+ * fail to allocate, the Rust side panics, and the panic surfaces to DSH as the bare
38176
+ * word `unreachable` — which reads like a network fault and is an out-of-memory abort.
38177
+ *
38178
+ * At a Chinese ratio of ~1.6–2 char/token, 1 MB is ~240k–330k tokens, which is why the
38179
+ * failure was reported as "breaks around 256k context": the limit is BYTES, not the
38180
+ * model's advertised window. Trimming here keeps the request sendable; the caller's
38181
+ * context budget is untouched, so nothing else has to know.
38182
+ */
38183
+ const shrunk = shrinkQoderPayload(payload);
38184
+ const body = g.writeString(JSON.stringify(shrunk));
37994
38185
  const bodyLen = g.lastLength();
37995
38186
  const key = g.writeString(ask.modelKey);
37996
38187
  const keyLen = g.lastLength();
@@ -46791,6 +46982,29 @@ var TraeAuth = class _TraeAuth extends Service5 {
46791
46982
  if (pool) {
46792
46983
  const available2 = await pool.getAvailableAccount(this.product.id, "").catch(() => void 0);
46793
46984
  if (available2) credential = available2.credential;
46985
+ /**
46986
+ * [xdpool-local] Fall back to ANY account the pool holds — issue #154.
46987
+ *
46988
+ * `getAvailableAccount` skips accounts that are cooling down, disabled, or simply not
46989
+ * the current pick. When it answers nothing, the code below resolved
46990
+ * `TRAE_ACCESS_TOKEN`, a ref that only exists on the single-credential path — a scan
46991
+ * login writes `TRAE_ACCOUNT_<hash>` instead, so the resolve was always undefined for
46992
+ * anyone who signed in through the card.
46993
+ *
46994
+ * The result was an empty list, `ensureRemoteModels` silently giving up, and
46995
+ * `listModels` returning the 28 hard-coded fallback rows — models the account does not
46996
+ * have, under names the vendor never published. Re-signing in could not help, because
46997
+ * the ref it wrote was never the one being read.
46998
+ *
46999
+ * Listing one turn does not need a usable account, only a real credential: the model
47000
+ * catalogue is the same for every account of this vendor.
47001
+ */
47002
+ if (credential === void 0) {
47003
+ const all = pool.listAccountsByProvider(this.product.id) ?? [];
47004
+ for (const entry of all) {
47005
+ if (entry.credential !== void 0) { credential = entry.credential; break }
47006
+ }
47007
+ }
46794
47008
  }
46795
47009
  if (credential === void 0) {
46796
47010
  const resolved = await this.ctx.credentials.resolve(credentialRef6(this.credentialRefName));