dsh-xdpool 2.6.5 → 2.6.7

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
@@ -1515,8 +1515,18 @@ var WorkBuddyUpstreamClient = class {
1515
1515
  if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
1516
1516
  return models;
1517
1517
  }
1518
- /** Read-only credits query, aggregated by package. Does not consume credits. */
1519
- async fetchCredits(credential) {
1518
+ /**
1519
+ * Read-only credits query, aggregated by package. Does not consume credits.
1520
+ *
1521
+ * `signal` is the caller's cancellation, merged with the built-in timeout
1522
+ * rather than replacing it: the pool's background warm must give up when the
1523
+ * host shuts down, and a caller that has already gone away must not leave a
1524
+ * 30 s request running. `AbortSignal.any` is already the repo's way of
1525
+ * combining these (see the pricing probe in the shim), and the timeout stays
1526
+ * in force so a signal-less caller keeps the old behaviour exactly.
1527
+ */
1528
+ async fetchCredits(credential, signal) {
1529
+ const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
1520
1530
  const now = /* @__PURE__ */ new Date();
1521
1531
  const fmt = (date) => {
1522
1532
  const p = (n) => n.toString().padStart(2, "0");
@@ -1533,7 +1543,7 @@ var WorkBuddyUpstreamClient = class {
1533
1543
  PackageEndTimeRangeBegin: fmt(now),
1534
1544
  PackageEndTimeRangeEnd: fmt(new Date(now.getTime() + 3185136e6))
1535
1545
  }),
1536
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1546
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
1537
1547
  });
1538
1548
  const envelope = await readEnvelope(response);
1539
1549
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
@@ -3731,6 +3741,13 @@ const EXHAUST_COOLDOWN_MS = 18e5;
3731
3741
  */
3732
3742
  const CREDENTIAL_DEAD_COOLDOWN_MS = 18e5;
3733
3743
  /**
3744
+ * Shortest gap between two attempts at the same account's deadline reading.
3745
+ *
3746
+ * Only failed attempts are actually throttled by this: a successful read stamps
3747
+ * the reading itself, so {@link EXPIRY_READING_TTL_MS} takes over from there.
3748
+ */
3749
+ const EXPIRY_WARM_RETRY_MS = 6e4;
3750
+ /**
3734
3751
  * Does this refresh failure prove the credential itself is dead?
3735
3752
  *
3736
3753
  * The upstream answers a revoked refresh token with `invalid_grant: Offline user
@@ -3759,6 +3776,7 @@ var WorkBuddyAccountPool = class {
3759
3776
  credentialDeadCooldownMs;
3760
3777
  client;
3761
3778
  refreshMarginMs;
3779
+ expiryReadingTtlMs;
3762
3780
  accounts = [];
3763
3781
  /**
3764
3782
  * Files the last scan could not read, with the reason.
@@ -3854,11 +3872,42 @@ var WorkBuddyAccountPool = class {
3854
3872
  * their own cycle and are therefore never urgent — which is why this is
3855
3873
  * written from the same `fetchCredits` reading that fills `creditBalances`.
3856
3874
  *
3857
- * An absent entry means "never probed, or nothing is about to expire". Both
3858
- * are the same thing to `expiry` mode: not urgent, so it sorts last.
3875
+ * A positive value is a deadline. The two other states are kept in
3876
+ * {@link creditExpiryNone} and {@link creditExpiryReadAt} rather than as a
3877
+ * missing key, because a missing key cannot tell "we never looked" from "we
3878
+ * looked and nothing has a deadline" — and only the first is worth reading
3879
+ * again. An account whose packs are all monthly reads as `none` forever, which
3880
+ * is exactly right: asking again cannot change the answer (S1).
3859
3881
  */
3860
3882
  creditExpiry = /* @__PURE__ */ new Map();
3861
3883
  /**
3884
+ * Accounts whose last reading found NO one-off deadline (all monthly packs, or
3885
+ * none at all). Written instead of deleting the key, so the account stops
3886
+ * being a candidate for re-reading.
3887
+ */
3888
+ creditExpiryNone = /* @__PURE__ */ new Set();
3889
+ /** When each account's deadline reading was taken, epoch ms. */
3890
+ creditExpiryReadAt = /* @__PURE__ */ new Map();
3891
+ /**
3892
+ * Accounts whose deadline reading is being fetched right now.
3893
+ *
3894
+ * Same de-duplication idea as {@link refreshInflight}, for the same reason: a
3895
+ * scan-triggered warm and a request-triggered top-up must not both spend a
3896
+ * billing round trip on the same account. A Set rather than a Map of promises
3897
+ * because no caller ever awaits the warm — the point is only that a second
3898
+ * pass skips it.
3899
+ */
3900
+ expiryWarmInflight = /* @__PURE__ */ new Set();
3901
+ /**
3902
+ * Last time the pool tried to warm an account's deadline reading, epoch ms.
3903
+ *
3904
+ * The TTL is the success gate, not a retry gate: a failed read writes nothing,
3905
+ * so without this a permanently failing billing endpoint would be hit on every
3906
+ * scan and every served request. One attempt per account per minute is cheap
3907
+ * and still recovers quickly from a transient failure.
3908
+ */
3909
+ expiryWarmAttemptAt = /* @__PURE__ */ new Map();
3910
+ /**
3862
3911
  * Last time each account served a request, epoch ms. Drives the idle term
3863
3912
  * of the priority-mode weighting below: an account that just served loses to
3864
3913
  * one that has been idle, so a small pool stops hammering a single account.
@@ -3903,6 +3952,7 @@ var WorkBuddyAccountPool = class {
3903
3952
  this.credentialDeadCooldownMs = options.credentialDeadCooldownMs ?? CREDENTIAL_DEAD_COOLDOWN_MS;
3904
3953
  this.client = options.client;
3905
3954
  this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
3955
+ this.expiryReadingTtlMs = options.expiryReadingTtlMs ?? 36e5;
3906
3956
  this.distribution = options.distribution ?? "priority";
3907
3957
  this.persistent = options.persistent ?? false;
3908
3958
  this.storePath = accountStorePath();
@@ -4117,6 +4167,7 @@ var WorkBuddyAccountPool = class {
4117
4167
  ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
4118
4168
  this.accounts = ordered;
4119
4169
  this.lastScanAtMs = Date.now();
4170
+ this.warmExpiryReadings();
4120
4171
  if (this.persistent) try {
4121
4172
  const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
4122
4173
  if (leaving.length > 0) this.logger?.warn?.(`dsh-xdpool: ${String(leaving.length)} account(s) are no longer in the pool after a rescan and were removed from the store: ${leaving.join(", ")}. Their credentials are gone unless they are signed in again.`);
@@ -4127,6 +4178,76 @@ var WorkBuddyAccountPool = class {
4127
4178
  }
4128
4179
  return this.accounts;
4129
4180
  }
4181
+ /**
4182
+ * Warm the deadline readings that `expiry` mode sorts on.
4183
+ *
4184
+ * Fire-and-forget on purpose, from `scan()`: the pool's first request arrives
4185
+ * before any reading exists, and the honest answer to that is the documented
4186
+ * fallback plus a log line, not a stalled request. Everything about the call
4187
+ * is chosen to be unable to make things worse:
4188
+ *
4189
+ * - `this.client` may not exist (a host that wired only token refresh), in
4190
+ * which case there is nothing to read with and the pass is a no-op — the
4191
+ * same guard `ensureFresh` uses;
4192
+ * - a dead sign-in is skipped, and a successful read NEVER calls
4193
+ * `clearCredentialDead`. That is the difference between this and
4194
+ * `reviveBenched`: the billing endpoint answers 200 for a banned account
4195
+ * (observed on 11140), so treating a read as proof of health is what got a
4196
+ * banned account revived six times in a day (S2). Only a token refresh or a
4197
+ * fresh sign-in may clear that mark;
4198
+ * - accounts whose reading is fresh enough are skipped, and so are accounts
4199
+ * already being read (S10's de-duplication, mirroring `refreshInflight`);
4200
+ * - a failed read writes nothing and only warns, so the next pass tries
4201
+ * again without the failure being mistaken for a reading.
4202
+ */
4203
+ warmExpiryReadings() {
4204
+ if (this.client?.fetchCredits === void 0) return;
4205
+ for (const account of this.accounts) this.warmExpiryReadingFor(account.id);
4206
+ }
4207
+ /** One account's warm read; see {@link warmExpiryReadings} for the rules. */
4208
+ async warmOneExpiryReading(account, client) {
4209
+ this.expiryWarmInflight.add(account.id);
4210
+ this.expiryWarmAttemptAt.set(account.id, Date.now());
4211
+ try {
4212
+ const credits = await client.fetchCredits(account.credential);
4213
+ this.noteExpiryOnly(account.id, credits.nearestExpiryMs);
4214
+ } catch (error) {
4215
+ this.logger?.warn?.(`dsh-xdpool: could not read credit deadlines for ${account.label} (read failed); expiry mode keeps falling back for it until a read succeeds`, error);
4216
+ } finally {
4217
+ this.expiryWarmInflight.delete(account.id);
4218
+ }
4219
+ }
4220
+ /**
4221
+ * Top up one account's deadline reading, from wherever the pool notices it is
4222
+ * missing or stale.
4223
+ *
4224
+ * The request path is the second caller (after `scan()`), because a reading
4225
+ * ages out while the pool is busy too: the shim calls this for the account that
4226
+ * just served a request, which is the one whose spend is most likely to have
4227
+ * moved its deadline. No timer is created — the existing balance refresh is
4228
+ * already the natural heartbeat, and this rides on it.
4229
+ *
4230
+ * Every gate lives here rather than in the callers, so both paths obey exactly
4231
+ * the same rules: no client, no account, a rejected sign-in, an already-running
4232
+ * read, a finished "nothing expires" answer, a fresh reading, or an attempt
4233
+ * made within the last minute all mean "do nothing".
4234
+ */
4235
+ warmExpiryReadingFor(accountId) {
4236
+ if (this.distribution !== "expiry") return;
4237
+ const client = this.client;
4238
+ if (client?.fetchCredits === void 0) return;
4239
+ const account = this.accounts.find((item) => item.id === accountId);
4240
+ if (account === void 0) return;
4241
+ const now = Date.now();
4242
+ if ((account.credentialDeadUntilMs ?? 0) > now) return;
4243
+ if (this.expiryWarmInflight.has(accountId)) return;
4244
+ const reading = this.expiryReadingOf(accountId, now);
4245
+ if (reading.state === "none") return;
4246
+ if (reading.state === "at" && !reading.stale) return;
4247
+ const lastAttempt = this.expiryWarmAttemptAt.get(accountId) ?? 0;
4248
+ if (lastAttempt > (reading.readAtMs ?? 0) && now - lastAttempt < EXPIRY_WARM_RETRY_MS) return;
4249
+ this.warmOneExpiryReading(account, client);
4250
+ }
4130
4251
  /** All accounts, cooldown state included. */
4131
4252
  list(region) {
4132
4253
  if (region === void 0) return this.accounts;
@@ -4474,18 +4595,37 @@ var WorkBuddyAccountPool = class {
4474
4595
  * A pool where nobody has a known expiry therefore behaves exactly like
4475
4596
  * priority, which is the honest degradation: without a reading there is
4476
4597
  * nothing to sort by.
4598
+ *
4599
+ * What this method must NOT do is pretend. With only SOME readings in hand it
4600
+ * still has to fall back to `pool[0]`, because picking the earliest of the
4601
+ * accounts that happen to have answered would silently drop the account that
4602
+ * really dies first — the failure mode S0 in `EXPIRY-ADVERSARIAL-20261111.md`
4603
+ * called "worse than not fixing it", since the pick looks plausible and is
4604
+ * wrong. So the incomplete case is announced instead: the caller keeps the old
4605
+ * semantics and the log says which accounts were not read.
4477
4606
  */
4478
4607
  pickByExpiry(pool) {
4608
+ const now = Date.now();
4609
+ const unread = [];
4610
+ const stale = [];
4479
4611
  let best;
4480
4612
  let bestAt = Number.POSITIVE_INFINITY;
4481
4613
  for (const account of pool) {
4482
- const at = this.creditExpiry.get(account.id);
4483
- if (at === void 0) continue;
4614
+ const reading = this.expiryReadingOf(account.id, now);
4615
+ if (reading.stale) stale.push(account);
4616
+ if (reading.state === "unread" || reading.stale) {
4617
+ unread.push(account);
4618
+ continue;
4619
+ }
4620
+ if (reading.state === "none") continue;
4621
+ const at = reading.at ?? Number.POSITIVE_INFINITY;
4484
4622
  if (at < bestAt) {
4485
4623
  best = account;
4486
4624
  bestAt = at;
4487
4625
  }
4488
4626
  }
4627
+ if (stale.length > 0) this.logger?.info?.(`dsh-xdpool: expiry mode found ${stale.length} deadline reading(s) older than ${Math.round(this.expiryReadingTtlMs / 6e4)} minute(s) (${stale.map((account) => account.label).join(", ")}); they are being topped up in the background`);
4628
+ if (unread.length > 0) this.logger?.warn?.(`dsh-xdpool: expiry mode has no deadline reading for ${unread.length} of ${pool.length} account(s) (${unread.map((account) => account.label).join(", ")}); falling back to pool order for this pick, which may not be the soonest to expire. Readings are filled in the background after a scan and by the request path.`);
4489
4629
  return best ?? pool[0];
4490
4630
  }
4491
4631
  /**
@@ -4663,21 +4803,91 @@ var WorkBuddyAccountPool = class {
4663
4803
  * merged: a pack that has been spent or has died disappears from the next
4664
4804
  * reading, and keeping the stale deadline would pin the pool to an account
4665
4805
  * whose credits are already gone — the opposite of what `expiry` mode wants.
4806
+ *
4807
+ * "Nothing expires" is a real answer, not the absence of one: it is stored as
4808
+ * {@link creditExpiryNone} so the account is not read again on every pass.
4666
4809
  */
4667
4810
  noteCredits(accountId, balance, nearestExpiryMs) {
4668
4811
  if (!Number.isFinite(balance)) return;
4669
4812
  if (!this.accounts.some((account) => account.id === accountId)) return;
4670
4813
  this.creditBalances.set(accountId, balance);
4814
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4815
+ }
4816
+ /**
4817
+ * Record ONLY the deadline, never the balance.
4818
+ *
4819
+ * The scan-triggered warm exists to fill `expiry` mode's sort key. Writing the
4820
+ * balance as a side effect would change what the reserve floor decides — an
4821
+ * account could be pulled out of rotation by a background read the user never
4822
+ * asked for, which is a behaviour change outside this fix's scope (S7 in
4823
+ * `EXPIRY-ADVERSARIAL-20261111.md`; the reserve's own cold-start hole is V4,
4824
+ * fixed separately).
4825
+ */
4826
+ noteExpiryOnly(accountId, nearestExpiryMs) {
4827
+ if (!this.accounts.some((account) => account.id === accountId)) return;
4828
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4829
+ }
4830
+ /**
4831
+ * The three-state writer both entry points funnel through.
4832
+ *
4833
+ * One place, so the invariant "a finished reading always leaves a state" can be
4834
+ * read off a single function: either a deadline is stored, or the account joins
4835
+ * `creditExpiryNone`. Nothing here deletes the read stamp — that is what makes
4836
+ * "read, found nothing" distinguishable from "never read".
4837
+ */
4838
+ noteExpiryReading(accountId, nearestExpiryMs) {
4839
+ this.creditExpiryReadAt.set(accountId, Date.now());
4671
4840
  if (nearestExpiryMs === void 0 || !Number.isFinite(nearestExpiryMs)) {
4672
4841
  this.creditExpiry.delete(accountId);
4842
+ this.creditExpiryNone.add(accountId);
4673
4843
  return;
4674
4844
  }
4845
+ this.creditExpiryNone.delete(accountId);
4675
4846
  this.creditExpiry.set(accountId, nearestExpiryMs);
4676
4847
  }
4677
4848
  /** Nearest one-off pack expiry for one account, or undefined when none known. */
4678
4849
  creditExpiryOf(accountId) {
4679
4850
  return this.creditExpiry.get(accountId);
4680
4851
  }
4852
+ /**
4853
+ * The full three-state reading for one account, including staleness.
4854
+ *
4855
+ * `stale` is evaluated against {@link EXPIRY_READING_TTL_MS} here rather than
4856
+ * baked into the stored value, so the TTL stays a constant of the policy and
4857
+ * not of the data.
4858
+ *
4859
+ * Only a real deadline can go stale. "We never asked" is not a reading, and
4860
+ * "nothing here has a deadline" does not become less true with age: a monthly
4861
+ * pack does not grow an expiry date by waiting. Keeping `none` permanently
4862
+ * valid is what makes the S1 loop impossible — an account that answered once
4863
+ * is never read again by the expiry machinery, so there is no predicate that
4864
+ * can stay true forever and re-read it on every pass. If such an account does
4865
+ * gain a one-off pack later, the card refresh (which writes through
4866
+ * `noteCredits` on every poll) is what notices.
4867
+ */
4868
+ expiryReadingOf(accountId, now = Date.now()) {
4869
+ const at = this.creditExpiry.get(accountId);
4870
+ const readAtMs = this.creditExpiryReadAt.get(accountId);
4871
+ if (readAtMs === void 0) return {
4872
+ state: "unread",
4873
+ stale: false
4874
+ };
4875
+ if (at !== void 0) return {
4876
+ state: "at",
4877
+ at,
4878
+ readAtMs,
4879
+ stale: now - readAtMs > this.expiryReadingTtlMs
4880
+ };
4881
+ if (this.creditExpiryNone.has(accountId)) return {
4882
+ state: "none",
4883
+ readAtMs,
4884
+ stale: false
4885
+ };
4886
+ return {
4887
+ state: "unread",
4888
+ stale: false
4889
+ };
4890
+ }
4681
4891
  /** Last known balance for one account, or undefined when never read. */
4682
4892
  creditsOf(accountId) {
4683
4893
  return this.creditBalances.get(accountId);
@@ -10967,6 +11177,20 @@ function flattenPlatforms(platforms) {
10967
11177
  * owner is read from its shape (`workbuddy` for a bare id, the prefix otherwise)
10968
11178
  * and groups come out in first-seen order — which is the order the members were
10969
11179
  * in, so re-flattening reproduces exactly what was stored.
11180
+ *
11181
+ * ## A channel member's id is NOT `owner/model` (#141)
11182
+ *
11183
+ * A scan-login channel publishes members as `<channel>:<model>`, and the model id
11184
+ * may itself contain slashes (`cline:deepseek/deepseek-v4.1-flash-1017:batch`).
11185
+ * Splitting on the first `/` turns that into provider `cline` and model
11186
+ * `cline:deepseek/…`, so the editor showed a doubled prefix and the round-trip
11187
+ * write added one more (`trae/trae:deepseek-v4.1-flash`), at which point the
11188
+ * runtime could no longer match any member and the chain reported every one of
11189
+ * them missing.
11190
+ *
11191
+ * The colon is the discriminator: `<channel>:<model>` names a channel member as a
11192
+ * single token, while `<owner>/<model>` is how a third-party provider row is
11193
+ * written. Checked BEFORE the slash split so a channel id is never cut.
10970
11194
  */
10971
11195
  function splitPlatforms(models) {
10972
11196
  const groups = /* @__PURE__ */ new Map();
@@ -10974,9 +11198,15 @@ function splitPlatforms(models) {
10974
11198
  for (const raw of models) {
10975
11199
  const id = text$6(raw);
10976
11200
  if (id === "") continue;
10977
- const parsed = parseProviderModelId(id);
10978
- const owner = parsed === null ? POOL_OWNER : parsed.providerId;
10979
- const model = parsed === null ? id : parsed.modelId;
11201
+ /**
11202
+ * `channel:model` — keep the whole thing as the model and file it under the
11203
+ * channel. `indexOf('/') === -1` is not required: the model half may contain
11204
+ * slashes, and the colon is what marks the shape.
11205
+ */
11206
+ const channelMember = channelMemberOf(id);
11207
+ const parsed = channelMember === void 0 ? parseProviderModelId(id) : null;
11208
+ const owner = channelMember === void 0 ? parsed === null ? POOL_OWNER : parsed.providerId : channelMember.channel;
11209
+ const model = channelMember === void 0 ? parsed === null ? id : parsed.modelId : channelMember.model;
10980
11210
  let bucket = groups.get(owner);
10981
11211
  if (bucket === void 0) {
10982
11212
  bucket = [];
@@ -10990,6 +11220,26 @@ function splitPlatforms(models) {
10990
11220
  models: groups.get(owner) ?? []
10991
11221
  }));
10992
11222
  }
11223
+ /**
11224
+ * Read `<channel>:<model>` where the channel is a bare identifier.
11225
+ *
11226
+ * Returns undefined for anything else, so a provider-row id (`openai/gpt-4`) and a
11227
+ * bare pool id (`hy3`) both keep whatever handling they had. The channel half is
11228
+ * required to look like an identifier rather than a URL scheme: `https://…` has a
11229
+ * colon too, and treating that as a channel would file the row under `https`.
11230
+ */
11231
+ function channelMemberOf(id) {
11232
+ const colon = id.indexOf(":");
11233
+ if (colon <= 0) return void 0;
11234
+ const channel = id.slice(0, colon);
11235
+ const model = id.slice(colon + 1);
11236
+ if (model === "") return void 0;
11237
+ if (!/^[A-Za-z0-9_-]+$/u.test(channel)) return void 0;
11238
+ return {
11239
+ channel,
11240
+ model
11241
+ };
11242
+ }
10993
11243
  /** Windows assumed when nothing on the chain declares one. */
10994
11244
  const COMBO_DEFAULT_CONTEXT_WINDOW = 131072;
10995
11245
  /** Output ceiling assumed when nothing on the chain declares one. */
@@ -13419,7 +13669,35 @@ function createWorkBuddyAdapter(options) {
13419
13669
  const baseUrl = `${shim.baseUrl()}/v1`;
13420
13670
  if (extraRows !== void 0) return (extraRows() ?? []).map((row) => toExtraLaneModel(row, baseUrl, providerId));
13421
13671
  if (aggregateCatalog) return [...catalog.providerRows().map((row) => toAggregateModel(row, baseUrl, providerId)), ...catalog.comboRows().map((row) => toComboModel(row, baseUrl, providerId))];
13422
- return catalog.visible().map((info) => toPiModel(info, baseUrl, providerId));
13672
+ /**
13673
+ * EVERY model, with the user's selection applied where it is meaningful (#143).
13674
+ *
13675
+ * The card's tick-boxes narrow what the picker LISTS, and `visible()` is the right
13676
+ * answer for "what should be offered". It is the wrong answer for "what can this
13677
+ * provider serve": a user who types or picks a model by id — `kimi-k3.1-pro` in the
13678
+ * report — got `pi-ai provider "xdpool" has no configured model "kimi-k3.1-pro"`,
13679
+ * because that model was not in the four ticked boxes. The model existed, the account
13680
+ * could serve it, and the refusal came from a display filter.
13681
+ *
13682
+ * So the selection is applied as an ORDER and a per-model capability override, not as
13683
+ * a hard allow-list:
13684
+ *
13685
+ * - ticked models come first, in catalogue order (what the picker shows);
13686
+ * - unticked models follow, so an explicit id still resolves;
13687
+ * - the image flag and the context budget still come from `visible()`, because those
13688
+ * are the two settings where "the user said so" must win.
13689
+ *
13690
+ * `visible()` cannot express the ordering on its own — it returns a filtered list — so
13691
+ * the two are merged here, keyed by id, with the per-model overrides taken from the
13692
+ * visible row when it exists.
13693
+ */
13694
+ const withSelection = () => {
13695
+ const shown = catalog.visible();
13696
+ const shownIds = new Set(shown.map((info) => info.id));
13697
+ const rest = catalog.current().filter((info) => !shownIds.has(info.id));
13698
+ return [...shown, ...rest].map((info) => toPiModel(info, baseUrl, providerId));
13699
+ };
13700
+ return withSelection();
13423
13701
  };
13424
13702
  /**
13425
13703
  * Build a fresh provider object whose `models` array is the catalog as it
@@ -15056,17 +15334,32 @@ function withSessionQuotaHint(error, retryAfterMs) {
15056
15334
  * and no explanation of which of its four fingerprint facts was wrong. That
15057
15335
  * reaches the caller as a bare `client` failure, and a bare 4xx is what the
15058
15336
  * host then renders in its own words: the user in #96 saw "当前请求的额度已用尽"
15059
- * for a request that had never been billed. The wording pointed at waiting,
15060
- * while the actual cause was "this build's fingerprint no longer matches, update
15061
- * the plugin" — the two need opposite responses.
15337
+ * for a request that had never been billed.
15062
15338
  *
15063
- * The lane cannot tell them apart from the outside (both look like a refusal
15064
- * with a thin body), so this does not pretend to. It names the actionable
15065
- * reading FIRST — the fingerprint, which the user can fix by updating — and
15066
- * keeps the quota possibility second, because it is the one that fixes itself.
15339
+ * ## The premise changed (verified 2026-11-12)
15067
15340
  *
15068
- * A 429 keeps its own hint ({@link withSessionQuotaHint}): that one really is
15069
- * quota, and blurring the two would lose a distinction worth keeping.
15341
+ * This used to say "the fingerprint moved, update the plugin". It no longer
15342
+ * does, because a raw call now answers:
15343
+ *
15344
+ * ```
15345
+ * {"type":"error","error":{"type":"FreeUsageLimitError",
15346
+ * "message":"Free usage limit reached. Free models work in OpenCode
15347
+ * (https://opencode.ai); subscribe to OpenCode Go to keep going…"}}
15348
+ * ```
15349
+ *
15350
+ * That is not a fingerprint rejection and not a per-conversation budget: the
15351
+ * upstream has moved free models behind the OpenCode client itself. No header,
15352
+ * UA or path change reaches it, which is why #96 could not be fixed by
15353
+ * matching the gate more exactly — the gate is gone, replaced by an account
15354
+ * metering that a third-party client cannot enter.
15355
+ *
15356
+ * So the message names the real situation FIRST and stops promising that a
15357
+ * plugin update will help. `FreeUsageLimitError` is called out by name because
15358
+ * it is the specific shape of "this lane is closed to you", and telling the
15359
+ * user to wait or retry would spend their time on something that cannot work.
15360
+ *
15361
+ * A 429 keeps its own hint ({@link withSessionQuotaHint}). The distinction is
15362
+ * worth keeping: 429 is a budget that resets, 403 is a door that closed.
15070
15363
  */
15071
15364
  function withFreeTierHint(status, refusal, retryAfterMs) {
15072
15365
  const base = classifyUpstream(status, refusal, retryAfterMs, "");
@@ -15074,7 +15367,14 @@ function withFreeTierHint(status, refusal, retryAfterMs) {
15074
15367
  const separator = base.message.indexOf(": ");
15075
15368
  const detail = separator === -1 ? "" : base.message.slice(separator + 2);
15076
15369
  const kept = detail === "" ? "" : ` (provider said: ${detail})`;
15077
- return new AggregateError(base.kind, `the free lane refused this client: its request fingerprint no longer matches what opencode.ai accepts, so this is NOT an exhausted quota and waiting will not help — update dsh-xdpool and try again; if it persists, report this message. The shared free quota is also metered per conversation, so one retry in a fresh conversation covers the case where only that budget is spent${kept}`, status);
15370
+ /**
15371
+ * `FreeUsageLimitError` means the upstream has closed this lane to non-client
15372
+ * traffic. Distinguished from a generic refusal so the advice can be true:
15373
+ * updating the plugin will not help, and only a real OpenCode client (or a
15374
+ * subscription) can.
15375
+ */
15376
+ const closed = /FreeUsageLimitError|Free usage limit reached/iu.test(refusal);
15377
+ return new AggregateError(base.kind, closed ? "the free lane is closed: opencode.ai now serves free models only inside its own client, so a third-party request is refused regardless of fingerprint. Use another channel, or subscribe to OpenCode Go" + kept : `the free lane refused this client: its request fingerprint no longer matches what opencode.ai accepts, so this is NOT an exhausted quota and waiting will not help — update dsh-xdpool and try again; if it persists, report this message. The shared free quota is also metered per conversation, so one retry in a fresh conversation covers the case where only that budget is spent${kept}`, status);
15078
15378
  }
15079
15379
  /**
15080
15380
  * POST one streaming turn and hand back chat-shaped deltas.
@@ -19224,6 +19524,218 @@ function paidAlternativeFor(model, models) {
19224
19524
  return paidSiblingOf(model, models);
19225
19525
  }
19226
19526
  //#endregion
19527
+ //#region src/non-streaming.ts
19528
+ /**
19529
+ * Reassemble a streamed turn into one `chat.completion` document.
19530
+ *
19531
+ * The pool lane (and every other lane that buffers before answering) asks the
19532
+ * upstream for SSE and forwards it; it cannot ask for JSON because
19533
+ * `prepareChatBody` forces streaming. A caller that sent `stream: false`
19534
+ * therefore used to receive `text/event-stream` anyway, and an OpenAI client
19535
+ * parsing that body as JSON failed with `Unexpected token 'd'`.
19536
+ *
19537
+ * The channel lane already honours the flag (see `serveChannelCompletion`). This
19538
+ * module gives the other lanes the same behaviour without touching their wire
19539
+ * contract when the caller did NOT ask for it: `wantsNonStreaming` is true only
19540
+ * for an explicit `stream: false`, so an absent flag keeps today's SSE reply.
19541
+ *
19542
+ * @module dsh-xdpool/non-streaming
19543
+ */
19544
+ /**
19545
+ * True only when the caller asked for JSON by saying so.
19546
+ *
19547
+ * `stream` absent must stay streaming: the Harness omits the flag and reads
19548
+ * SSE, and a missing field silently means "false" to plenty of JSON parsers —
19549
+ * honouring that reading would break every existing client.
19550
+ */
19551
+ function wantsNonStreaming(raw) {
19552
+ let body;
19553
+ try {
19554
+ body = JSON.parse(raw);
19555
+ } catch {
19556
+ return false;
19557
+ }
19558
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
19559
+ return body["stream"] === false;
19560
+ }
19561
+ function createTurnAccumulator(modelId) {
19562
+ return {
19563
+ id: `chatcmpl-xdpool-${randomBytes(6).toString("base64url")}`,
19564
+ created: Math.floor(Date.now() / 1e3),
19565
+ model: modelId ?? "",
19566
+ text: "",
19567
+ reasoning: "",
19568
+ toolCalls: [],
19569
+ usage: void 0,
19570
+ rawUsage: void 0,
19571
+ finish: "stop"
19572
+ };
19573
+ }
19574
+ /**
19575
+ * Merge one tool-call fragment into its slot.
19576
+ *
19577
+ * The upstream streams a call as an opening fragment carrying `name` and then
19578
+ * argument deltas that do NOT: a plain spread would erase the name on the
19579
+ * second fragment and leave the caller with `tool_calls[0].function.name ===
19580
+ * undefined`. An empty or missing name therefore means "no opinion here", never
19581
+ * "clear what you have".
19582
+ */
19583
+ function mergeTurnToolCall(existing, fragment) {
19584
+ const before = existing["function"] ?? {};
19585
+ const next = fragment["function"] ?? {};
19586
+ const name = typeof next["name"] === "string" && next["name"] !== "" ? next["name"] : before["name"];
19587
+ const merged = {
19588
+ ...existing,
19589
+ ...fragment,
19590
+ function: {
19591
+ ...before,
19592
+ ...next,
19593
+ ...name === void 0 ? {} : { name },
19594
+ arguments: `${String(before["arguments"] ?? "")}${String(next["arguments"] ?? "")}`
19595
+ }
19596
+ };
19597
+ if (typeof fragment["id"] === "string" && fragment["id"] !== "") merged["id"] = fragment["id"];
19598
+ else if (typeof existing["id"] === "string") merged["id"] = existing["id"];
19599
+ return merged;
19600
+ }
19601
+ /** Merge one delta/message object (content, reasoning, tool calls) into the turn. */
19602
+ function absorbDelta(turn, delta) {
19603
+ if (typeof delta["content"] === "string") turn.text += delta["content"];
19604
+ const reasoning = delta["reasoning_content"] ?? delta["reasoning"];
19605
+ if (typeof reasoning === "string") turn.reasoning += reasoning;
19606
+ const calls = delta["tool_calls"];
19607
+ if (!Array.isArray(calls)) return;
19608
+ for (const call of calls) {
19609
+ if (typeof call !== "object" || call === null) continue;
19610
+ const fragment = call;
19611
+ const index = Number(fragment["index"] ?? turn.toolCalls.length);
19612
+ const slot = Number.isInteger(index) && index >= 0 ? index : turn.toolCalls.length;
19613
+ turn.toolCalls[slot] = mergeTurnToolCall(turn.toolCalls[slot] ?? {}, fragment);
19614
+ }
19615
+ }
19616
+ /**
19617
+ * Fold one SSE `data:` payload into the accumulator.
19618
+ *
19619
+ * Reads the same three shapes the forwarding path already tolerates upstream:
19620
+ * OpenAI `choices[].delta`, a non-streaming `choices[].message`, and the
19621
+ * gateway's `data.content` wrapper.
19622
+ */
19623
+ function foldPayload(turn, payload) {
19624
+ if (payload === "" || payload === "[DONE]") return;
19625
+ let parsed;
19626
+ try {
19627
+ parsed = JSON.parse(payload);
19628
+ } catch {
19629
+ return;
19630
+ }
19631
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
19632
+ const frame = parsed;
19633
+ const usage = parseUsage(frame["usage"]);
19634
+ if (usage !== void 0) {
19635
+ turn.usage = usage;
19636
+ turn.rawUsage = frame["usage"];
19637
+ }
19638
+ const choices = frame["choices"];
19639
+ if (Array.isArray(choices) && choices.length > 0) {
19640
+ const choice = choices[0];
19641
+ if (typeof choice === "object" && choice !== null) {
19642
+ const entry = choice;
19643
+ const delta = entry["delta"];
19644
+ if (typeof delta === "object" && delta !== null) absorbDelta(turn, delta);
19645
+ const message = entry["message"];
19646
+ if (typeof message === "object" && message !== null) absorbDelta(turn, message);
19647
+ const reason = entry["finish_reason"];
19648
+ if (typeof reason === "string" && reason !== "") turn.finish = reason;
19649
+ }
19650
+ }
19651
+ const wrapper = frame["data"];
19652
+ if (typeof wrapper === "object" && wrapper !== null) {
19653
+ const content = wrapper["content"];
19654
+ if (typeof content === "string") turn.text += content;
19655
+ const reason = wrapper["finish_reason"];
19656
+ if (typeof reason === "string" && reason !== "") turn.finish = reason;
19657
+ }
19658
+ }
19659
+ /** Spell the accumulated turn as one non-streaming `chat.completion` document. */
19660
+ function turnToCompletion(turn) {
19661
+ const calls = turn.toolCalls.filter((call) => call !== void 0);
19662
+ return {
19663
+ id: turn.id,
19664
+ object: "chat.completion",
19665
+ created: turn.created,
19666
+ model: turn.model,
19667
+ choices: [{
19668
+ index: 0,
19669
+ message: {
19670
+ role: "assistant",
19671
+ content: turn.text === "" && calls.length > 0 ? null : turn.text,
19672
+ ...turn.reasoning === "" ? {} : { reasoning_content: turn.reasoning },
19673
+ ...calls.length === 0 ? {} : { tool_calls: calls }
19674
+ },
19675
+ finish_reason: turn.finish
19676
+ }],
19677
+ ...turn.rawUsage === void 0 ? {} : { usage: turn.rawUsage }
19678
+ };
19679
+ }
19680
+ /**
19681
+ * Split a growing text buffer into complete SSE `data:` payloads.
19682
+ *
19683
+ * A frame's own blank line is the only reliable boundary — JSON can contain
19684
+ * anything, but it cannot contain an unescaped newline — so nothing is parsed
19685
+ * out of a partial frame.
19686
+ */
19687
+ function drainSsePayloads(buffer) {
19688
+ const payloads = [];
19689
+ let rest = buffer;
19690
+ for (;;) {
19691
+ const span = sseFrameSpan(rest);
19692
+ if (span === void 0) break;
19693
+ const frame = rest.subarray(0, span.contentEnd).toString("utf8");
19694
+ rest = rest.subarray(span.frameEnd);
19695
+ for (const line of frame.split(/\r?\n/u)) {
19696
+ const trimmed = line.trim();
19697
+ if (!trimmed.startsWith("data:")) continue;
19698
+ payloads.push(trimmed.slice(5).trim());
19699
+ }
19700
+ }
19701
+ return {
19702
+ payloads,
19703
+ rest
19704
+ };
19705
+ }
19706
+ /**
19707
+ * Where one SSE frame ends inside a buffer.
19708
+ *
19709
+ * Both offsets come back because a frame's CONTENT ends before its SEPARATOR
19710
+ * does. This is the same rule `frameSpan` in `shim.ts` applies; it lives here
19711
+ * too so the reassembler does not have to reach into the shim's closure.
19712
+ */
19713
+ function sseFrameSpan(buf) {
19714
+ const bare = buf.indexOf("\n\n");
19715
+ const crlf = buf.indexOf("\r\n\r\n");
19716
+ if (bare === -1 && crlf === -1) return void 0;
19717
+ if (crlf !== -1 && (bare === -1 || crlf < bare)) return {
19718
+ contentEnd: crlf,
19719
+ frameEnd: crlf + 4
19720
+ };
19721
+ return {
19722
+ contentEnd: bare,
19723
+ frameEnd: bare + 2
19724
+ };
19725
+ }
19726
+ /**
19727
+ * Fold a buffered lane's frames into the one document `stream: false` asked for.
19728
+ *
19729
+ * The buffering lanes (aggregate, free/co-paid extras, chain members) already
19730
+ * hold their whole answer before writing, so honouring the flag there costs one
19731
+ * pass and no wire change for streaming callers.
19732
+ */
19733
+ function bufferedFramesToCompletion(frames, modelId) {
19734
+ const turn = createTurnAccumulator(modelId);
19735
+ for (const payload of frames) foldPayload(turn, payload);
19736
+ return turnToCompletion(turn);
19737
+ }
19738
+ //#endregion
19227
19739
  //#region src/channel-lane.ts
19228
19740
  /**
19229
19741
  * A request this lane will not serve as written, and that is the caller's to fix.
@@ -19904,6 +20416,10 @@ function createWorkBuddyShim(options) {
19904
20416
  writeOpenAIError(res, KIND_STATUS[kind], `${target.lane}_${kind}`, message);
19905
20417
  return;
19906
20418
  }
20419
+ if (wantsNonStreaming(raw)) {
20420
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
20421
+ return;
20422
+ }
19907
20423
  res.writeHead(200, {
19908
20424
  "Content-Type": "text/event-stream",
19909
20425
  "Cache-Control": "no-cache",
@@ -20115,6 +20631,10 @@ function createWorkBuddyShim(options) {
20115
20631
  writeOpenAIError(res, 500, "aggregate_internal", error instanceof Error ? error.message : String(error));
20116
20632
  return;
20117
20633
  }
20634
+ if (wantsNonStreaming(raw)) {
20635
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
20636
+ return;
20637
+ }
20118
20638
  res.writeHead(200, {
20119
20639
  "Content-Type": "text/event-stream",
20120
20640
  "Cache-Control": "no-cache",
@@ -20425,6 +20945,10 @@ function createWorkBuddyShim(options) {
20425
20945
  noteSwitch(member.modelId, kind, last.status);
20426
20946
  continue;
20427
20947
  }
20948
+ if (wantsNonStreaming(raw)) {
20949
+ writeJson$1(res, 200, bufferedFramesToCompletion(hostFrames, member.modelId));
20950
+ return;
20951
+ }
20428
20952
  res.writeHead(200, {
20429
20953
  "Content-Type": "text/event-stream",
20430
20954
  "Cache-Control": "no-cache",
@@ -20456,12 +20980,17 @@ function createWorkBuddyShim(options) {
20456
20980
  const result = await client.chatStream(account.credential, prepared, memberSignal, conversationKey);
20457
20981
  if (result.ok) {
20458
20982
  const turnId = randomBytes(8).toString("hex");
20459
- await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, usageRecorder === void 0 ? void 0 : {
20983
+ const memberUsage = usageRecorder === void 0 ? void 0 : {
20460
20984
  recorder: usageRecorder,
20461
20985
  region: region ?? "cn",
20462
20986
  model: member.modelId,
20463
20987
  turnId
20464
- });
20988
+ };
20989
+ if (wantsNonStreaming(raw)) {
20990
+ await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, memberUsage, member.modelId);
20991
+ return;
20992
+ }
20993
+ await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, memberUsage);
20465
20994
  return;
20466
20995
  }
20467
20996
  last = {
@@ -20527,6 +21056,10 @@ function createWorkBuddyShim(options) {
20527
21056
  continue;
20528
21057
  }
20529
21058
  if (switches.length > 0) logger?.info?.(`dsh-xdpool: chain ${row.id} served by ${member.modelId} after skipping ${String(switches.length)}/${String(members.length)}: ${switches.join("; ")}`);
21059
+ if (wantsNonStreaming(raw)) {
21060
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, member.modelId));
21061
+ return;
21062
+ }
20530
21063
  res.writeHead(200, {
20531
21064
  "Content-Type": "text/event-stream",
20532
21065
  "Cache-Control": "no-cache",
@@ -20661,6 +21194,10 @@ function createWorkBuddyShim(options) {
20661
21194
  tried.push(account.label);
20662
21195
  const result = await client.chatStream(account.credential, prepared, controller.signal, conversationKey);
20663
21196
  if (result.ok) {
21197
+ if (wantsNonStreaming(raw)) {
21198
+ await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usageContext, modelId);
21199
+ return;
21200
+ }
20664
21201
  await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, usageContext);
20665
21202
  return;
20666
21203
  }
@@ -20725,6 +21262,10 @@ function createWorkBuddyShim(options) {
20725
21262
  })()
20726
21263
  });
20727
21264
  if (recovered.ok) {
21265
+ if (wantsNonStreaming(raw)) {
21266
+ await serveSuccessfulJson(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext, modelId);
21267
+ return;
21268
+ }
20728
21269
  await serveSuccessfulStream(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext);
20729
21270
  return;
20730
21271
  }
@@ -20807,6 +21348,7 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
20807
21348
  logger?.info?.(`dsh-xdpool: served by ${account.label}`);
20808
21349
  pool.noteServed(account.id);
20809
21350
  refreshBalance(account);
21351
+ if (pool.expiryReadingOf(account.id).stale) pool.warmExpiryReadingFor(account.id);
20810
21352
  res.writeHead(200, {
20811
21353
  "Content-Type": "text/event-stream",
20812
21354
  "Cache-Control": "no-cache",
@@ -20882,6 +21424,79 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
20882
21424
  body.pipe(strip).pipe(res);
20883
21425
  }
20884
21426
  /**
21427
+ * Answer one already-successful upstream stream as a single JSON document.
21428
+ *
21429
+ * The pool lane asks for SSE (`prepareChatBody` forces it), so the only way to
21430
+ * honour `stream: false` is to consume the whole body here and reassemble it.
21431
+ * Nothing is written until the body completes, which is also why a mid-flight
21432
+ * failure can still become a proper HTTP error instead of a 200 that ends in a
21433
+ * truncated answer.
21434
+ *
21435
+ * The bookkeeping deliberately mirrors `serveSuccessfulStream`: same
21436
+ * `noteServed`, same background balance refresh, same once-only usage filing —
21437
+ * a turn must not cost differently depending on how the caller asked to read it.
21438
+ */
21439
+ async function serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usage, modelId) {
21440
+ logger?.info?.(`dsh-xdpool: served by ${account.label} (non-streaming)`);
21441
+ pool.noteServed(account.id);
21442
+ refreshBalance(account);
21443
+ const tracker = new StreamTracker(Date.now());
21444
+ const turn = createTurnAccumulator(modelId);
21445
+ let recorded = false;
21446
+ const finish = (ok) => {
21447
+ if (recorded) return;
21448
+ recorded = true;
21449
+ if (usage?.recorder === void 0) return;
21450
+ usage.recorder.record({
21451
+ channel: "workbuddy",
21452
+ region: usage.region,
21453
+ model: usage.model,
21454
+ account: account.label,
21455
+ turnId: usage.turnId,
21456
+ at: Date.now(),
21457
+ ok,
21458
+ ...tracker.ttftMs === void 0 ? {} : { ttftMs: tracker.ttftMs },
21459
+ ...tracker.decodeMs === void 0 ? {} : { decodeMs: tracker.decodeMs },
21460
+ ...tracker.usage === void 0 ? {} : { usage: tracker.usage }
21461
+ });
21462
+ };
21463
+ /**
21464
+ * Explicitly `Buffer<ArrayBufferLike>`: `Buffer.alloc(0)` infers
21465
+ * `Buffer<ArrayBuffer>`, and `Buffer.concat` widens to `ArrayBufferLike`, so the
21466
+ * assignment back into `buffer` fails under strict lib types. Annotating the accumulator
21467
+ * once is clearer than casting at each of the two assignments.
21468
+ */
21469
+ let buffer = Buffer.alloc(0);
21470
+ let failure;
21471
+ try {
21472
+ for await (const chunk of Readable.fromWeb(result.response.body)) {
21473
+ tracker.markFirstByte(Date.now());
21474
+ buffer = buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([buffer, chunk]);
21475
+ const drained = drainSsePayloads(buffer);
21476
+ buffer = drained.rest;
21477
+ for (const payload of drained.payloads) foldPayload(turn, payload);
21478
+ }
21479
+ if (buffer.length > 0) for (const line of buffer.toString("utf8").split(/\r?\n/u)) {
21480
+ const trimmed = line.trim();
21481
+ if (trimmed.startsWith("data:")) foldPayload(turn, trimmed.slice(5).trim());
21482
+ }
21483
+ tracker.finish(Date.now());
21484
+ if (turn.usage !== void 0) tracker.usage = turn.usage;
21485
+ } catch (error) {
21486
+ failure = error;
21487
+ logger?.warn("dsh-xdpool: non-streaming reassembly failed mid-flight", error);
21488
+ }
21489
+ if (failure !== void 0) {
21490
+ finish(false);
21491
+ if (!res.headersSent) writeOpenAIError(res, 502, "upstream_stream_error", `the upstream stream broke before the answer completed: ${failure instanceof Error ? failure.message : String(failure)}`);
21492
+ else if (res.writable) res.end();
21493
+ return;
21494
+ }
21495
+ finish(true);
21496
+ if (!res.headersSent) writeJson$1(res, 200, turnToCompletion(turn));
21497
+ else if (res.writable) res.end();
21498
+ }
21499
+ /**
20885
21500
  * Compact an over-long conversation and retry it once.
20886
21501
  *
20887
21502
  * Strategy, in order: