dsh-xdpool 3.0.0 → 3.0.1

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
@@ -3170,6 +3170,15 @@ const POOL_AGGREGATE_DISCOVER_PATH = "/plugins/dsh-xdpool/aggregate/discover";
3170
3170
  */
3171
3171
  const POOL_CHANNELS_PATH = "/plugins/dsh-xdpool/channels";
3172
3172
  /**
3173
+ * Per-channel usage order.
3174
+ *
3175
+ * `GET` answers every channel's effective strategy (its own override, or the pool-wide default);
3176
+ * `POST { channel, strategy }` writes one. The channel page has no settings scope of its own, so
3177
+ * this route is how it reads and writes — the alternative is a page that cannot change a control
3178
+ * it displays.
3179
+ */
3180
+ const POOL_CHANNEL_USAGE_PATH = "/plugins/dsh-xdpool/channels/usage";
3181
+ /**
3173
3182
  * The Doubao lane's session.
3174
3183
  *
3175
3184
  * POST starts an interactive browser sign-in and answers once it lands;
@@ -4251,7 +4260,7 @@ let cachedFailureAt = 0;
4251
4260
  //#endregion
4252
4261
  //#region src/doubao-routes.ts
4253
4262
  /** Read a JSON body, or an empty object when there is none. */
4254
- async function readJson(req) {
4263
+ async function readJson$1(req) {
4255
4264
  const chunks = [];
4256
4265
  for await (const chunk of req) chunks.push(chunk);
4257
4266
  if (chunks.length === 0) return {};
@@ -4263,7 +4272,7 @@ async function readJson(req) {
4263
4272
  }
4264
4273
  }
4265
4274
  /** Write a JSON response. */
4266
- function json$8(res, status, body) {
4275
+ function json$9(res, status, body) {
4267
4276
  res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
4268
4277
  res.end(JSON.stringify(body));
4269
4278
  }
@@ -4279,12 +4288,12 @@ function registerDoubaoRoutes(ctx, deps) {
4279
4288
  kind: "exact",
4280
4289
  path: POOL_DOUBAO_SESSION_PATH,
4281
4290
  handler: async (req, res) => {
4282
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4291
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4283
4292
  try {
4284
4293
  if (req.method === "DELETE") {
4285
4294
  deps.clear();
4286
4295
  setDoubaoSession(void 0);
4287
- return json$8(res, 200, {
4296
+ return json$9(res, 200, {
4288
4297
  ok: true,
4289
4298
  signedIn: false
4290
4299
  });
@@ -4298,20 +4307,20 @@ function registerDoubaoRoutes(ctx, deps) {
4298
4307
  * broken to anyone who was simply slower than the timer.
4299
4308
  */
4300
4309
  const result = await browserLogin$1();
4301
- if (!result.ok || result.session === void 0) return json$8(res, 200, {
4310
+ if (!result.ok || result.session === void 0) return json$9(res, 200, {
4302
4311
  ok: false,
4303
4312
  signedIn: false,
4304
4313
  message: result.reason ?? "登录失败"
4305
4314
  });
4306
4315
  deps.save(result.session);
4307
4316
  setDoubaoSession(result.session);
4308
- return json$8(res, 200, {
4317
+ return json$9(res, 200, {
4309
4318
  ok: true,
4310
4319
  signedIn: true,
4311
4320
  message: "登录成功,会话已保存"
4312
4321
  });
4313
4322
  }
4314
- if (req.method !== "GET") return json$8(res, 405, { error: "method not allowed" });
4323
+ if (req.method !== "GET") return json$9(res, 405, { error: "method not allowed" });
4315
4324
  /**
4316
4325
  * A read is not passive: the sign-in browser may be open and already signed into,
4317
4326
  * and the card asks every couple of seconds while the user finishes. Harvesting on
@@ -4322,7 +4331,7 @@ function registerDoubaoRoutes(ctx, deps) {
4322
4331
  if (live !== void 0) {
4323
4332
  deps.save(live);
4324
4333
  setDoubaoSession(live);
4325
- return json$8(res, 200, {
4334
+ return json$9(res, 200, {
4326
4335
  ok: true,
4327
4336
  signedIn: true,
4328
4337
  savedAt: live.savedAt
@@ -4338,12 +4347,12 @@ function registerDoubaoRoutes(ctx, deps) {
4338
4347
  const accounts = await readStoredAccounts();
4339
4348
  const active = deps.session();
4340
4349
  if (accounts.length === 0) {
4341
- if (!sessionUsable(active)) return json$8(res, 200, {
4350
+ if (!sessionUsable(active)) return json$9(res, 200, {
4342
4351
  ok: true,
4343
4352
  signedIn: false
4344
4353
  });
4345
4354
  const name = await fetchAccountName(active);
4346
- return json$8(res, 200, {
4355
+ return json$9(res, 200, {
4347
4356
  ok: true,
4348
4357
  signedIn: true,
4349
4358
  accounts: [{
@@ -4377,13 +4386,13 @@ function registerDoubaoRoutes(ctx, deps) {
4377
4386
  active: isActive
4378
4387
  });
4379
4388
  }
4380
- return json$8(res, 200, {
4389
+ return json$9(res, 200, {
4381
4390
  ok: true,
4382
4391
  signedIn: true,
4383
4392
  accounts: rows
4384
4393
  });
4385
4394
  } catch (error) {
4386
- return json$8(res, 500, { error: error instanceof Error ? error.message : String(error) });
4395
+ return json$9(res, 500, { error: error instanceof Error ? error.message : String(error) });
4387
4396
  }
4388
4397
  }
4389
4398
  });
@@ -4391,10 +4400,10 @@ function registerDoubaoRoutes(ctx, deps) {
4391
4400
  kind: "exact",
4392
4401
  path: POOL_DOUBAO_QUOTA_PATH,
4393
4402
  handler: async (req, res) => {
4394
- if (req.method !== "GET") return json$8(res, 405, { error: "method not allowed" });
4395
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4403
+ if (req.method !== "GET") return json$9(res, 405, { error: "method not allowed" });
4404
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4396
4405
  const session = deps.session();
4397
- if (session === void 0 || !sessionUsable(session)) return json$8(res, 200, {
4406
+ if (session === void 0 || !sessionUsable(session)) return json$9(res, 200, {
4398
4407
  ok: false,
4399
4408
  signedIn: false,
4400
4409
  windows: []
@@ -4402,7 +4411,7 @@ function registerDoubaoRoutes(ctx, deps) {
4402
4411
  try {
4403
4412
  setDoubaoSession(session);
4404
4413
  const quota = await fetchQuota({ force: true });
4405
- return json$8(res, 200, {
4414
+ return json$9(res, 200, {
4406
4415
  ok: quota.error === void 0,
4407
4416
  signedIn: true,
4408
4417
  exhausted: quota.exhausted,
@@ -4410,7 +4419,7 @@ function registerDoubaoRoutes(ctx, deps) {
4410
4419
  windows: quota.windows
4411
4420
  });
4412
4421
  } catch (error) {
4413
- return json$8(res, 200, {
4422
+ return json$9(res, 200, {
4414
4423
  ok: false,
4415
4424
  signedIn: true,
4416
4425
  windows: [],
@@ -4423,8 +4432,43 @@ function registerDoubaoRoutes(ctx, deps) {
4423
4432
  kind: "exact",
4424
4433
  path: POOL_DOUBAO_MODELS_PATH,
4425
4434
  handler: async (req, res) => {
4426
- if (req.method !== "GET") return json$8(res, 405, { error: "method not allowed" });
4427
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4435
+ if (req.method !== "GET" && req.method !== "POST") return json$9(res, 405, { error: "method not allowed" });
4436
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4437
+ /**
4438
+ * POST stores the card's disable-list — issue #196.
4439
+ *
4440
+ * The picker is built in this process and cannot read the card's
4441
+ * localStorage, so without this mirror it kept publishing every model the
4442
+ * account owns while the card said "4/16".
4443
+ *
4444
+ * Validation is strict on purpose: a body with one non-string entry would
4445
+ * otherwise be stored verbatim and silently hide nothing (or hide the
4446
+ * wrong things), and a half-written list is indistinguishable from a
4447
+ * deliberate one afterwards. A malformed body is refused whole.
4448
+ *
4449
+ * An EMPTY array is a real state — "nothing is switched off, show the whole
4450
+ * roster" — and is stored as such. It is also what every install starts
4451
+ * with, which is why the adapter reads it as "no restriction".
4452
+ */
4453
+ if (req.method === "POST") {
4454
+ if (deps.saveDoubaoSelection === void 0) return json$9(res, 503, { error: "settings service unavailable; doubao selection cannot be saved" });
4455
+ const raw = (await readJson$1(req))["disabledModelIds"];
4456
+ if (!Array.isArray(raw)) return json$9(res, 400, { error: "disabledModelIds must be an array" });
4457
+ const ids = [];
4458
+ for (const entry of raw) {
4459
+ if (typeof entry !== "string" || entry === "") return json$9(res, 400, { error: "disabledModelIds must contain non-empty strings" });
4460
+ if (!ids.includes(entry)) ids.push(entry);
4461
+ }
4462
+ try {
4463
+ await deps.saveDoubaoSelection(ids);
4464
+ return json$9(res, 200, {
4465
+ ok: true,
4466
+ disabledModelIds: ids
4467
+ });
4468
+ } catch (error) {
4469
+ return json$9(res, 500, { error: error instanceof Error ? error.message : String(error) });
4470
+ }
4471
+ }
4428
4472
  /**
4429
4473
  * The same list the picker gets.
4430
4474
  *
@@ -4433,12 +4477,12 @@ function registerDoubaoRoutes(ctx, deps) {
4433
4477
  * answer.
4434
4478
  */
4435
4479
  try {
4436
- return json$8(res, 200, {
4480
+ return json$9(res, 200, {
4437
4481
  ok: true,
4438
4482
  models: await fetchLiveModels(deps.session())
4439
4483
  });
4440
4484
  } catch (error) {
4441
- return json$8(res, 200, {
4485
+ return json$9(res, 200, {
4442
4486
  ok: false,
4443
4487
  models: [],
4444
4488
  error: error instanceof Error ? error.message : String(error)
@@ -4450,11 +4494,11 @@ function registerDoubaoRoutes(ctx, deps) {
4450
4494
  kind: "exact",
4451
4495
  path: POOL_DOUBAO_CAMPAIGN_PATH,
4452
4496
  handler: async (req, res) => {
4453
- if (req.method !== "GET") return json$8(res, 405, { error: "method not allowed" });
4454
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4497
+ if (req.method !== "GET") return json$9(res, 405, { error: "method not allowed" });
4498
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4455
4499
  const session = deps.session();
4456
4500
  const campaign = await fetchCampaign(session);
4457
- return json$8(res, 200, {
4501
+ return json$9(res, 200, {
4458
4502
  ok: campaign.error === void 0,
4459
4503
  signedIn: session !== void 0,
4460
4504
  ...campaign
@@ -4465,10 +4509,10 @@ function registerDoubaoRoutes(ctx, deps) {
4465
4509
  kind: "exact",
4466
4510
  path: POOL_DOUBAO_CLAIM_PATH,
4467
4511
  handler: async (req, res) => {
4468
- if (req.method !== "POST") return json$8(res, 405, { error: "method not allowed" });
4469
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4512
+ if (req.method !== "POST") return json$9(res, 405, { error: "method not allowed" });
4513
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4470
4514
  const result = await claimTasks(deps.session());
4471
- return json$8(res, 200, {
4515
+ return json$9(res, 200, {
4472
4516
  ok: result.failed === 0,
4473
4517
  ...result
4474
4518
  });
@@ -4478,7 +4522,7 @@ function registerDoubaoRoutes(ctx, deps) {
4478
4522
  kind: "exact",
4479
4523
  path: POOL_DOUBAO_AUTOMATION_PATH,
4480
4524
  handler: async (req, res) => {
4481
- if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4525
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$9(res, 403, { error: "origin-not-trusted" });
4482
4526
  const automation = deps.automation();
4483
4527
  try {
4484
4528
  if (req.method === "POST") {
@@ -4488,26 +4532,26 @@ function registerDoubaoRoutes(ctx, deps) {
4488
4532
  * Two actions, one route, because they are one concept to the card: the pane's
4489
4533
  * checkbox and its "run now" button both mean "make the automation do its job".
4490
4534
  */
4491
- const body = await readJson(req);
4535
+ const body = await readJson$1(req);
4492
4536
  if (typeof body["enabled"] === "boolean") {
4493
4537
  automation.setEnabled(body["enabled"]);
4494
- return json$8(res, 200, {
4538
+ return json$9(res, 200, {
4495
4539
  ok: true,
4496
4540
  ...automation.state()
4497
4541
  });
4498
4542
  }
4499
- return json$8(res, 200, {
4543
+ return json$9(res, 200, {
4500
4544
  ok: true,
4501
4545
  ...await automation.runOnce()
4502
4546
  });
4503
4547
  }
4504
- if (req.method !== "GET") return json$8(res, 405, { error: "method not allowed" });
4505
- return json$8(res, 200, {
4548
+ if (req.method !== "GET") return json$9(res, 405, { error: "method not allowed" });
4549
+ return json$9(res, 200, {
4506
4550
  ok: true,
4507
4551
  ...automation.state()
4508
4552
  });
4509
4553
  } catch (error) {
4510
- return json$8(res, 500, { error: error instanceof Error ? error.message : String(error) });
4554
+ return json$9(res, 500, { error: error instanceof Error ? error.message : String(error) });
4511
4555
  }
4512
4556
  }
4513
4557
  });
@@ -4522,6 +4566,161 @@ function registerDoubaoRoutes(ctx, deps) {
4522
4566
  });
4523
4567
  }
4524
4568
  //#endregion
4569
+ //#region src/channel-usage.ts
4570
+ /**
4571
+ * Per-channel usage order.
4572
+ *
4573
+ * WHY A FILE OF ITS OWN
4574
+ *
4575
+ * The pool-wide `distribution` setting covers the two WorkBuddy lanes, where every account is
4576
+ * one vendor's and one strategy suits them all. A channel with two or three accounts of its own
4577
+ * is a different decision — draining one CodeArts account first is not the same choice as
4578
+ * draining one WorkBuddy account first — so each channel needs its own answer.
4579
+ *
4580
+ * The host's settings document is not available for it: a plugin's write path there accepts
4581
+ * only the section's own `{auto}` toggle, and the settings UI would fight a second writer. This
4582
+ * plugin already keeps `accounts.json` beside its other state, so the overrides go there.
4583
+ *
4584
+ * ABSENT MEANS "FOLLOW THE POOL"
4585
+ *
4586
+ * A channel with no entry uses the pool-wide strategy. That is why clearing an override deletes
4587
+ * the key instead of storing the pool's current value: a stored copy would freeze, and a later
4588
+ * change to the pool default would silently not reach that channel.
4589
+ *
4590
+ * @module dsh-xdpool/channel-usage
4591
+ */
4592
+ /** The five strategies, in the order the UI offers them. */
4593
+ const USAGE_STRATEGIES = [
4594
+ "priority",
4595
+ "round-robin",
4596
+ "balanced",
4597
+ "sticky",
4598
+ "expiry"
4599
+ ];
4600
+ /** Whether a value is a strategy this build understands. */
4601
+ function isUsageStrategy(value) {
4602
+ return typeof value === "string" && USAGE_STRATEGIES.includes(value);
4603
+ }
4604
+ /** The file the overrides live in. */
4605
+ const FILE$6 = "channel-usage.json";
4606
+ /** Absolute path of the override file. */
4607
+ function usagePath() {
4608
+ return join(pluginDataDir(), FILE$6);
4609
+ }
4610
+ /**
4611
+ * The stored overrides.
4612
+ *
4613
+ * Read on every call rather than cached: the file is small, the route is not hot, and a cache
4614
+ * would need invalidating from the write path for no gain. A malformed file answers with an
4615
+ * empty map — "every channel follows the pool" is a state the caller already handles.
4616
+ */
4617
+ function readChannelUsage() {
4618
+ try {
4619
+ const text = readFileSync(usagePath(), "utf8");
4620
+ const parsed = JSON.parse(text);
4621
+ if (parsed === null || typeof parsed !== "object") return {};
4622
+ const out = {};
4623
+ for (const [channel, strategy] of Object.entries(parsed)) if (isUsageStrategy(strategy)) out[channel] = strategy;
4624
+ return out;
4625
+ } catch {
4626
+ return {};
4627
+ }
4628
+ }
4629
+ /**
4630
+ * Hand the stored strategies to the pack.
4631
+ *
4632
+ * The pack reads them from the environment on each call, so this is the bridge between the file
4633
+ * the pane writes and the selection it affects. Called at mount and after every write — a value
4634
+ * that only took effect on restart would make the pane look broken.
4635
+ */
4636
+ function publishChannelUsage() {
4637
+ const overrides = readChannelUsage();
4638
+ if (Object.keys(overrides).length === 0) {
4639
+ delete process.env["DSH_XDPOOL_CHANNEL_USAGE"];
4640
+ return;
4641
+ }
4642
+ process.env["DSH_XDPOOL_CHANNEL_USAGE"] = JSON.stringify(overrides);
4643
+ }
4644
+ /**
4645
+ * Set one channel's strategy, or clear it.
4646
+ *
4647
+ * `undefined` removes the key, so the channel goes back to following the pool default. Writing
4648
+ * is atomic: a half-written file would be read back as "no overrides at all", silently resetting
4649
+ * every channel the user had configured.
4650
+ */
4651
+ function writeChannelUsage(channel, strategy) {
4652
+ const current = { ...readChannelUsage() };
4653
+ if (strategy === void 0) delete current[channel];
4654
+ else current[channel] = strategy;
4655
+ try {
4656
+ const target = usagePath();
4657
+ mkdirSync(dirname(target), { recursive: true });
4658
+ const temporary = `${target}.tmp`;
4659
+ writeFileSync(temporary, `${JSON.stringify(current, null, 2)}\n`, "utf8");
4660
+ renameSync(temporary, target);
4661
+ publishChannelUsage();
4662
+ } catch {}
4663
+ }
4664
+ //#endregion
4665
+ //#region src/channel-usage-route.ts
4666
+ /** Write one JSON answer. */
4667
+ function json$8(res, status, body) {
4668
+ const text = JSON.stringify(body);
4669
+ res.writeHead(status, {
4670
+ "Content-Type": "application/json; charset=utf-8",
4671
+ "Content-Length": Buffer.byteLength(text),
4672
+ "Cache-Control": "no-store"
4673
+ });
4674
+ res.end(text);
4675
+ }
4676
+ /** Read a JSON body, or an empty object when there is none. */
4677
+ async function readJson(req) {
4678
+ const chunks = [];
4679
+ for await (const chunk of req) chunks.push(chunk);
4680
+ if (chunks.length === 0) return {};
4681
+ try {
4682
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
4683
+ return parsed !== null && typeof parsed === "object" ? parsed : {};
4684
+ } catch {
4685
+ return {};
4686
+ }
4687
+ }
4688
+ /** Register `GET`/`POST /plugins/dsh-xdpool/channels/usage`. */
4689
+ function registerChannelUsageRoute(ctx, deps) {
4690
+ const state = () => ({
4691
+ pool: deps.pool(),
4692
+ channels: readChannelUsage()
4693
+ });
4694
+ ctx.effect(() => ctx.webServer.register({
4695
+ kind: "exact",
4696
+ path: POOL_CHANNEL_USAGE_PATH,
4697
+ handler: async (req, res) => {
4698
+ if (req.method !== "GET" && req.method !== "POST") return json$8(res, 405, { error: "method not allowed" });
4699
+ if (!originTrusted(req, deps.trustedHosts?.() ?? [])) return json$8(res, 403, { error: "origin-not-trusted" });
4700
+ if (req.method === "GET") return json$8(res, 200, state());
4701
+ const body = await readJson(req);
4702
+ const channel = body["channel"];
4703
+ if (typeof channel !== "string" || channel.trim() === "") return json$8(res, 400, { error: "channel must be a non-empty string" });
4704
+ /**
4705
+ * `strategy` absent (or `''`) CLEARS the override.
4706
+ *
4707
+ * Clearing is a real operation — the channel goes back to following the
4708
+ * pool default — and the card offers it, so refusing an empty value would
4709
+ * make "follow the pool" unreachable from the UI.
4710
+ *
4711
+ * Anything else must be one of the five this build understands: an unknown
4712
+ * string stored here would be silently ignored at request time, which reads
4713
+ * as "the click did nothing" — the exact complaint this route exists for.
4714
+ */
4715
+ const raw = body["strategy"];
4716
+ const strategy = raw === void 0 || raw === null || raw === "" ? void 0 : raw;
4717
+ if (strategy !== void 0 && !isUsageStrategy(strategy)) return json$8(res, 400, { error: "strategy must be one of priority/round-robin/balanced/sticky/expiry" });
4718
+ writeChannelUsage(channel.trim(), strategy);
4719
+ return json$8(res, 200, state());
4720
+ }
4721
+ }));
4722
+ }
4723
+ //#endregion
4525
4724
  //#region src/doubao-automation.ts
4526
4725
  /**
4527
4726
  * Doubao's credit automation.
@@ -4641,102 +4840,6 @@ function createDoubaoAutomation(options) {
4641
4840
  };
4642
4841
  }
4643
4842
  //#endregion
4644
- //#region src/channel-usage.ts
4645
- /**
4646
- * Per-channel usage order.
4647
- *
4648
- * WHY A FILE OF ITS OWN
4649
- *
4650
- * The pool-wide `distribution` setting covers the two WorkBuddy lanes, where every account is
4651
- * one vendor's and one strategy suits them all. A channel with two or three accounts of its own
4652
- * is a different decision — draining one CodeArts account first is not the same choice as
4653
- * draining one WorkBuddy account first — so each channel needs its own answer.
4654
- *
4655
- * The host's settings document is not available for it: a plugin's write path there accepts
4656
- * only the section's own `{auto}` toggle, and the settings UI would fight a second writer. This
4657
- * plugin already keeps `accounts.json` beside its other state, so the overrides go there.
4658
- *
4659
- * ABSENT MEANS "FOLLOW THE POOL"
4660
- *
4661
- * A channel with no entry uses the pool-wide strategy. That is why clearing an override deletes
4662
- * the key instead of storing the pool's current value: a stored copy would freeze, and a later
4663
- * change to the pool default would silently not reach that channel.
4664
- *
4665
- * @module dsh-xdpool/channel-usage
4666
- */
4667
- /** The five strategies, in the order the UI offers them. */
4668
- const USAGE_STRATEGIES = [
4669
- "priority",
4670
- "round-robin",
4671
- "balanced",
4672
- "sticky",
4673
- "expiry"
4674
- ];
4675
- /** Whether a value is a strategy this build understands. */
4676
- function isUsageStrategy(value) {
4677
- return typeof value === "string" && USAGE_STRATEGIES.includes(value);
4678
- }
4679
- /** The file the overrides live in. */
4680
- const FILE$6 = "channel-usage.json";
4681
- /** Absolute path of the override file. */
4682
- function usagePath() {
4683
- return join(pluginDataDir(), FILE$6);
4684
- }
4685
- /**
4686
- * The stored overrides.
4687
- *
4688
- * Read on every call rather than cached: the file is small, the route is not hot, and a cache
4689
- * would need invalidating from the write path for no gain. A malformed file answers with an
4690
- * empty map — "every channel follows the pool" is a state the caller already handles.
4691
- */
4692
- function readChannelUsage() {
4693
- try {
4694
- const text = readFileSync(usagePath(), "utf8");
4695
- const parsed = JSON.parse(text);
4696
- if (parsed === null || typeof parsed !== "object") return {};
4697
- const out = {};
4698
- for (const [channel, strategy] of Object.entries(parsed)) if (isUsageStrategy(strategy)) out[channel] = strategy;
4699
- return out;
4700
- } catch {
4701
- return {};
4702
- }
4703
- }
4704
- /**
4705
- * Hand the stored strategies to the pack.
4706
- *
4707
- * The pack reads them from the environment on each call, so this is the bridge between the file
4708
- * the pane writes and the selection it affects. Called at mount and after every write — a value
4709
- * that only took effect on restart would make the pane look broken.
4710
- */
4711
- function publishChannelUsage() {
4712
- const overrides = readChannelUsage();
4713
- if (Object.keys(overrides).length === 0) {
4714
- delete process.env["DSH_XDPOOL_CHANNEL_USAGE"];
4715
- return;
4716
- }
4717
- process.env["DSH_XDPOOL_CHANNEL_USAGE"] = JSON.stringify(overrides);
4718
- }
4719
- /**
4720
- * Set one channel's strategy, or clear it.
4721
- *
4722
- * `undefined` removes the key, so the channel goes back to following the pool default. Writing
4723
- * is atomic: a half-written file would be read back as "no overrides at all", silently resetting
4724
- * every channel the user had configured.
4725
- */
4726
- function writeChannelUsage(channel, strategy) {
4727
- const current = { ...readChannelUsage() };
4728
- if (strategy === void 0) delete current[channel];
4729
- else current[channel] = strategy;
4730
- try {
4731
- const target = usagePath();
4732
- mkdirSync(dirname(target), { recursive: true });
4733
- const temporary = `${target}.tmp`;
4734
- writeFileSync(temporary, `${JSON.stringify(current, null, 2)}\n`, "utf8");
4735
- renameSync(temporary, target);
4736
- publishChannelUsage();
4737
- } catch {}
4738
- }
4739
- //#endregion
4740
4843
  //#region src/doubao-host-adapter.ts
4741
4844
  /**
4742
4845
  * Doubao as a host adapter.
@@ -4794,6 +4897,24 @@ function bareName(name) {
4794
4897
  return name.replace(/\s*[·・]\s*(?:x\s*[\d.]+(?:\s*→\s*x?[\d.]+)?|免费|限时免费|正式版.*)$/iu, "").trim();
4795
4898
  }
4796
4899
  /**
4900
+ * Shrink a roster by the ids the user switched off — issue #196.
4901
+ *
4902
+ * Exported because it is the entire rule, and the rule is where this lane went
4903
+ * wrong: `listModels` published the whole live roster while the card showed
4904
+ * "4/16", so the picker offered twelve models the user had deliberately hidden.
4905
+ * A pure function keeps that rule testable without a session or a network read.
4906
+ *
4907
+ * `undefined` and `[]` both mean "nothing switched off". They are not
4908
+ * distinguished because the settings document cannot distinguish them (see the
4909
+ * note on `disabled` above), and an empty disable-list is the safe reading:
4910
+ * show everything, recoverable in one click.
4911
+ */
4912
+ function visibleDoubaoModels(models, disabled) {
4913
+ if (disabled === void 0 || disabled.length === 0) return models;
4914
+ const hidden = new Set(disabled);
4915
+ return models.filter((model) => !hidden.has(model.id));
4916
+ }
4917
+ /**
4797
4918
  * The adapter.
4798
4919
  *
4799
4920
  * `listModels` reads the account's live roster through `fetchLiveModels`, which merges the
@@ -4833,11 +4954,19 @@ var DoubaoHostAdapter = class extends LlmAdapter {
4833
4954
  return [];
4834
4955
  }
4835
4956
  const models = await fetchLiveModels(session);
4957
+ /**
4958
+ * `cached` keeps the FULL roster on purpose — issue #196.
4959
+ *
4960
+ * An unchecked model must stay resolvable: a chain, a routing rule or an
4961
+ * agent's pinned default may still name it, and the tick list governs what
4962
+ * the picker OFFERS, never what the lane can serve. Filtering the cache
4963
+ * would turn "hidden" into "broken" the next time one of those names it.
4964
+ */
4836
4965
  this.cached = {
4837
4966
  at: Date.now(),
4838
4967
  models
4839
4968
  };
4840
- return models.map((model) => this.describe(model));
4969
+ return visibleDoubaoModels(models, this.options.disabled?.()).map((model) => this.describe(model));
4841
4970
  }
4842
4971
  async resolveModel(provider, model, _signal) {
4843
4972
  const known = this.cached?.models.find((entry) => entry.id === model) ?? DOUBAO_MODELS.find((entry) => entry.id === model);
@@ -29091,7 +29220,7 @@ function parseBody(body) {
29091
29220
  *
29092
29221
  * @module dsh-xdpool/version
29093
29222
  */
29094
- const POOL_VERSION = "3.0.0";
29223
+ const POOL_VERSION = "3.0.1";
29095
29224
  //#endregion
29096
29225
  //#region src/update-check.ts
29097
29226
  /**
@@ -34059,6 +34188,28 @@ function createChannelLane(options) {
34059
34188
  })
34060
34189
  };
34061
34190
  }
34191
+ /** The roles the host understands; anything else is a user turn. */
34192
+ const KNOWN_ROLES = /* @__PURE__ */ new Set([
34193
+ "system",
34194
+ "user",
34195
+ "assistant",
34196
+ "tool"
34197
+ ]);
34198
+ /**
34199
+ * Normalise one OpenAI role — issue #195, third defect.
34200
+ *
34201
+ * The converters below used exact, case-sensitive comparisons (`role ===
34202
+ * 'assistant'`), so `Assistant` / `ASSISTANT` / `assistant ` fell through to
34203
+ * the catch-all branch and went upstream as USER turns. The reporter's control
34204
+ * experiment read that as "the uppercase spelling works" — it did not; the model
34205
+ * was being told its own history was the user talking, and tool results lost
34206
+ * their pairing. One normalisation here fixes every downstream comparison.
34207
+ */
34208
+ function normalizeRole(value) {
34209
+ if (typeof value !== "string") return "user";
34210
+ const role = value.trim().toLowerCase();
34211
+ return KNOWN_ROLES.has(role) ? role : "user";
34212
+ }
34062
34213
  /**
34063
34214
  * Forward one OpenAI message as the host's typed content blocks.
34064
34215
  *
@@ -34070,7 +34221,7 @@ function createChannelLane(options) {
34070
34221
  * note on why `{ type: 'image', url }` was the wrong answer.
34071
34222
  */
34072
34223
  async function toHostMessage(message, attachments) {
34073
- const role = typeof message.role === "string" ? message.role : "user";
34224
+ const role = normalizeRole(message.role);
34074
34225
  const content = message.content;
34075
34226
  if (typeof content === "string") return {
34076
34227
  role,
@@ -34115,14 +34266,44 @@ async function toHostMessage(message, attachments) {
34115
34266
  content: blocks
34116
34267
  };
34117
34268
  }
34118
- /** The host's finish reason, in the OpenAI spelling. */
34269
+ /**
34270
+ * The host's finish reason, in the OpenAI spelling — or undefined for a failure.
34271
+ *
34272
+ * `undefined` is not "unknown": it means the host ended the turn with an ERROR,
34273
+ * and the caller must answer with an error rather than a completion — issue #195.
34274
+ * This function used to end with `return 'stop'`, which folded `kind:'error'`
34275
+ * into a successful empty answer; the host then reported `EMPTY_RESPONSE` (a
34276
+ * retryable code), retried until backoff ran out, and the user saw "the model
34277
+ * said nothing" instead of the upstream's own message.
34278
+ */
34119
34279
  function mapFinishReason(reason) {
34120
34280
  const kind = typeof reason === "object" && reason !== null ? reason.kind : reason;
34121
34281
  if (kind === "toolUse" || kind === "tool_use") return "tool_calls";
34122
34282
  if (kind === "length") return "length";
34123
34283
  if (kind === "aborted") return "abort";
34284
+ if (kind === "error" || kind === "failed") return void 0;
34124
34285
  return "stop";
34125
34286
  }
34287
+ /**
34288
+ * The message and status a host error carries, for the client.
34289
+ *
34290
+ * The host's `finish` reason for a failure is `{ kind: 'error', error?: … }`,
34291
+ * with the detail in one of a few shapes depending on where it was raised
34292
+ * (`LlmError` carries code/status, a raw rejection carries only a message).
34293
+ * Reading it here keeps `toChannelEvent` free of that branching, and it is
34294
+ * deliberately lossless-ish: whatever text the host produced is what the client
34295
+ * gets, because a failure the user cannot read is the bug being fixed.
34296
+ */
34297
+ function failureOf(reason) {
34298
+ const record = typeof reason === "object" && reason !== null ? reason : {};
34299
+ const inner = typeof record.error === "object" && record.error !== null ? record.error : record;
34300
+ const message = typeof inner.message === "string" && inner.message !== "" ? inner.message : typeof record.message === "string" && record.message !== "" ? record.message : "the channel reported a failure without a message";
34301
+ const rawStatus = inner.status ?? inner.code ?? record.status;
34302
+ return {
34303
+ message,
34304
+ status: typeof rawStatus === "number" && Number.isFinite(rawStatus) ? rawStatus : void 0
34305
+ };
34306
+ }
34126
34307
  /** Fold host chunks into OpenAI delta objects. */
34127
34308
  function toChannelEvent(chunk) {
34128
34309
  switch (chunk.type) {
@@ -34163,10 +34344,17 @@ function toChannelEvent(chunk) {
34163
34344
  }
34164
34345
  };
34165
34346
  }
34166
- case "finish": return {
34167
- kind: "done",
34168
- finishReason: mapFinishReason(chunk.reason)
34169
- };
34347
+ case "finish": {
34348
+ const finishReason = mapFinishReason(chunk.reason);
34349
+ if (finishReason === void 0) return {
34350
+ kind: "failed",
34351
+ ...failureOf(chunk.reason)
34352
+ };
34353
+ return {
34354
+ kind: "done",
34355
+ finishReason
34356
+ };
34357
+ }
34170
34358
  default: return;
34171
34359
  }
34172
34360
  }
@@ -34175,7 +34363,33 @@ async function* runTurn(input) {
34175
34363
  const { llm, channel, modelId, body, signal, attachments } = input;
34176
34364
  const incoming = Array.isArray(body.messages) ? body.messages : [];
34177
34365
  const converted = [];
34178
- for (const message of incoming) converted.push(await toHostMessage(message, attachments));
34366
+ for (const message of incoming) {
34367
+ const host = await toHostMessage(message, attachments);
34368
+ /**
34369
+ * Give an assistant turn a `source` — issue #195.
34370
+ *
34371
+ * The host's `LlmRuntime.forAdapter` does `const source = message.source;
34372
+ * if (source.replayState === void 0) …` with no null check, so a bare OpenAI
34373
+ * history — which is exactly what comes in over this gateway — throws
34374
+ * `TypeError: Cannot read properties of undefined (reading 'replayState')`
34375
+ * on the second turn of every conversation (the first has no assistant
34376
+ * message to walk). The throw lands inside the adapter stream's try and
34377
+ * surfaces as a failure with no content.
34378
+ *
34379
+ * `kind: 'model'` without `replayState` is the honest answer for a message
34380
+ * this plugin never produced: "this came from a model, and there is no
34381
+ * replay state for it". The host's own next line then leaves the message
34382
+ * alone, which is what a multi-turn history needs.
34383
+ */
34384
+ converted.push(host.role === "assistant" ? {
34385
+ ...host,
34386
+ source: {
34387
+ kind: "model",
34388
+ provider: channel,
34389
+ model: modelId
34390
+ }
34391
+ } : host);
34392
+ }
34179
34393
  const system = converted.filter((message) => message.role === "system");
34180
34394
  const options = {
34181
34395
  provider: channel,
@@ -34715,6 +34929,32 @@ function createWorkBuddyShim(options) {
34715
34929
  finish = event.finishReason;
34716
34930
  continue;
34717
34931
  }
34932
+ /**
34933
+ * The channel reported a failure — issue #195.
34934
+ *
34935
+ * This is the difference between "the model said nothing" and "the
34936
+ * upstream refused". Answering `finish_reason:"stop"` with empty content
34937
+ * made the host classify a real failure as `EMPTY_RESPONSE`, which is in
34938
+ * `DEFAULT_RETRYABLE_CODES`: it retried until backoff ran out and the
34939
+ * user never learned why. The status the host reported travels through
34940
+ * when it has one; 502 is the honest default for "a channel in this
34941
+ * deployment failed".
34942
+ */
34943
+ if (event.kind === "failed") {
34944
+ const status = event.status !== void 0 && event.status >= 400 && event.status < 600 ? event.status : 502;
34945
+ const message = `channel ${target.channel}: ${event.message}`;
34946
+ if (started) {
34947
+ res.write(`data: ${JSON.stringify({ error: {
34948
+ message,
34949
+ type: "channel_upstream_error"
34950
+ } })}\n\n`);
34951
+ res.write("data: [DONE]\n\n");
34952
+ res.end();
34953
+ return;
34954
+ }
34955
+ writeOpenAIError(res, status, "channel_upstream_error", message);
34956
+ return;
34957
+ }
34718
34958
  const delta = event.delta;
34719
34959
  if (typeof delta.content === "string") text += delta.content;
34720
34960
  if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
@@ -35137,7 +35377,18 @@ function createWorkBuddyShim(options) {
35137
35377
  signal: memberSignal
35138
35378
  })) if (event.kind === "usage") {} else if (event.kind === "done") {
35139
35379
  if (typeof event.finishReason === "string" && event.finishReason !== "") finishReason = event.finishReason;
35140
- } else {
35380
+ } else if (event.kind === "failed")
35381
+ /**
35382
+ * A member that failed is not a member that answered — issue #195.
35383
+ *
35384
+ * Throwing here is what routes it into the `catch` below, which
35385
+ * records the member as failed and lets the chain try the next one.
35386
+ * Treating it as an empty-but-successful answer (the old behaviour,
35387
+ * via `finish_reason:"stop"`) stopped the chain on the member that
35388
+ * could not answer and reported success.
35389
+ */
35390
+ throw new Error(event.message);
35391
+ else {
35141
35392
  const delta = event.delta;
35142
35393
  if (delta["content"] !== void 0 || delta["reasoning_content"] !== void 0 || Array.isArray(delta["tool_calls"])) {}
35143
35394
  hostFrames.push(frameOf(delta, null));
@@ -37551,7 +37802,15 @@ const Config = z.object({
37551
37802
  * govern (it is not an aggregate provider), leaving no way to remove it
37552
37803
  * without editing a file. Reported as "关不掉,应该默认是关闭的".
37553
37804
  */
37554
- freeLane: asVolatile(z.boolean().default(false).description("Offer the shared 免密 free models (the \"XD Pool · 免费模型\" group). Off by default: it is a third-party endpoint with no key of your own."))
37805
+ freeLane: asVolatile(z.boolean().default(false).description("Offer the shared 免密 free models (the \"XD Pool · 免费模型\" group). Off by default: it is a third-party endpoint with no key of your own.")),
37806
+ /**
37807
+ * Doubao's disable-list, mirrored from the card (see the Config doc above).
37808
+ *
37809
+ * Empty = nothing switched off = the whole roster. `asVolatile` is what the
37810
+ * card needs (client writes, host reads without a restart); it is also why the
37811
+ * polarity matters — the default `[]` has to be the harmless answer.
37812
+ */
37813
+ doubaoDisabledModels: asVolatile(z.array(z.string()).default([]).description("Doubao model ids switched off in the picker (mirrored from the Doubao card; empty shows the whole roster)"))
37555
37814
  });
37556
37815
  /** Live API, published for the CLI. */
37557
37816
  let api;
@@ -37756,6 +38015,23 @@ function apply(ctx, config = {}) {
37756
38015
  core.catalogs.global.applySelection(modelSelectionGlobal ?? fallbackSelection("global"));
37757
38016
  applyLaneSelection(laneSelectionFrom(core.catalogs.cn.currentSelection().enabledModelIds, core.catalogs.global.currentSelection().enabledModelIds));
37758
38017
  core.scheduler.applyConfig(automationOptions(automation));
38018
+ /**
38019
+ * And finally: tell the HOST that the model list just changed.
38020
+ *
38021
+ * `applySelection` above only swaps the selection inside OUR catalogue. The
38022
+ * host's picker renders whatever its own cached provider snapshot holds, and
38023
+ * that cache is keyed by the identity of the `profiles` map (see
38024
+ * `adapter.ts/ makeProvider`). Nothing in this function rebuilds it, so a
38025
+ * save that narrowed the list left the picker showing the old one — the
38026
+ * user unticks a model, presses save, the settings file is correct, and the
38027
+ * model is still in the picker until DSH restarts or they press "refetch
38028
+ * models". That is the report this line fixes.
38029
+ *
38030
+ * It is a no-op during the very first apply (the real implementation is
38031
+ * assigned further down, once the adapters exist), which is why it is safe
38032
+ * to call unconditionally here.
38033
+ */
38034
+ invalidateCatalog();
37759
38035
  };
37760
38036
  const settingsService = ctx.settings;
37761
38037
  if (typeof settingsService.installSection === "function") settingsService.installSection(ctx, XDPOOL_SETTINGS_NS, Config, unwrapVolatileDeep(config), sectionHooks);
@@ -38225,7 +38501,30 @@ function apply(ctx, config = {}) {
38225
38501
  adoptDoubaoSession(void 0);
38226
38502
  removeStoredSession();
38227
38503
  },
38228
- automation: () => doubaoAutomation
38504
+ automation: () => doubaoAutomation,
38505
+ /**
38506
+ * Persist the card's disable-list — issue #196.
38507
+ *
38508
+ * `setSetting` re-reads and throws when the document did not change, so a
38509
+ * refused write reaches the card as a 500 instead of looking saved.
38510
+ */
38511
+ saveDoubaoSelection: async (ids) => {
38512
+ const payload = [...ids];
38513
+ await setSetting("doubaoDisabledModels", payload, payload);
38514
+ }
38515
+ });
38516
+ /**
38517
+ * The 「账号使用方式」 route — the one 3.0.0 forgot to register.
38518
+ *
38519
+ * The card and the channel pane both POST to this path; only the in-process
38520
+ * `api.channelUsage()` half existed, so every click fell through to the
38521
+ * host's catch-all and the user was told「账号使用方式没保存上:HTTP 405」.
38522
+ * Registering it here is the whole fix — the read, the atomic write and the
38523
+ * publish to the pack were already written and tested.
38524
+ */
38525
+ registerChannelUsageRoute(webCtx, {
38526
+ pool: () => current().distribution ?? "priority",
38527
+ trustedHosts
38229
38528
  });
38230
38529
  return registerPoolStatusRoute(webCtx, {
38231
38530
  pool: core.pool,
@@ -38611,7 +38910,18 @@ function apply(ctx, config = {}) {
38611
38910
  * registry, so a signed-in Doubao account with ten models enabled appeared nowhere in
38612
38911
  * the list. This is the registration the pack performs for each of its own channels.
38613
38912
  */
38614
- releaseAdapterDoubao = ctx.llm.registerAdapter([DOUBAO_PROVIDER_ID], new DoubaoHostAdapter({ session: () => doubaoSession }));
38913
+ releaseAdapterDoubao = ctx.llm.registerAdapter([DOUBAO_PROVIDER_ID], new DoubaoHostAdapter({
38914
+ session: () => doubaoSession,
38915
+ /**
38916
+ * Issue #196: the card's ticks reach the picker through this read.
38917
+ *
38918
+ * A native `LlmAdapter` is asked for its models on every catalogue
38919
+ * build (`LlmRuntime.listModels` → `adapter.listModels`), so a
38920
+ * settings change is visible without re-registering anything —
38921
+ * unlike the pi-ai lanes, which need `invalidateCatalog`.
38922
+ */
38923
+ disabled: () => current().doubaoDisabledModels
38924
+ }));
38615
38925
  /**
38616
38926
  * Marvis, the fifteenth channel.
38617
38927
  *
@@ -38731,6 +39041,22 @@ function apply(ctx, config = {}) {
38731
39041
  aggregateCatalog.onChange(() => {
38732
39042
  invalidateCatalog();
38733
39043
  });
39044
+ /**
39045
+ * The two gateway catalogues get the same treatment, which they never had.
39046
+ *
39047
+ * `applyConfigFromSource` now invalidates on every settings apply (see the
39048
+ * note there), but a catalogue can also move WITHOUT a settings write: the
39049
+ * startup seed and every "refetch models" land through
39050
+ * `updateFromUpstream`, and an account swap re-seeds it. Those paths reach
39051
+ * the host through this subscription instead of through a settings event.
39052
+ *
39053
+ * Registered through `ctx.effect` so a plugin reload disposes them: the
39054
+ * aggregate and free subscriptions above hand their disposer away, which
39055
+ * leaks one listener per reload. New subscriptions do not repeat that.
39056
+ */
39057
+ for (const catalog of [core.catalogs.cn, core.catalogs.global]) ctx.effect(() => catalog.onChange(() => {
39058
+ invalidateCatalog();
39059
+ }));
38734
39060
  freeCatalog.onChange(() => {
38735
39061
  invalidateCatalog();
38736
39062
  });