dsh-xdpool 2.6.4 → 2.6.6

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);
@@ -5196,7 +5406,21 @@ var WorkBuddyCatalog = class {
5196
5406
  */
5197
5407
  visible() {
5198
5408
  const enabled = this.selection.enabledModelIds;
5199
- const allow = enabled === void 0 ? void 0 : new Set(enabled);
5409
+ /**
5410
+ * An EMPTY list means "nothing has been chosen yet", not "serve nothing".
5411
+ *
5412
+ * `undefined` was already treated as "all enabled", but `[]` fell through to an empty
5413
+ * allow-set and filtered out every model. A host that writes the legacy key with a
5414
+ * default `[]` — DSH 0.2.2-rc.1 does exactly that before the picker has ever been
5415
+ * used — therefore made this catalog publish ZERO models, and the picker and every
5416
+ * "test" call reported `has no configured model "<id>"` for models that were plainly
5417
+ * listed on the card (issue #122).
5418
+ *
5419
+ * The two states cannot be distinguished by intent afterwards, so the safe reading is
5420
+ * chosen: an empty selection is indistinguishable from no selection, and "everything"
5421
+ * is recoverable in one click whereas "nothing" looks like a broken install.
5422
+ */
5423
+ const allow = enabled === void 0 || enabled.length === 0 ? void 0 : new Set(enabled);
5200
5424
  const images = this.selection.imageModelIds;
5201
5425
  const imageSet = images === void 0 ? void 0 : new Set(images);
5202
5426
  const budgets = this.selection.contextBudgets;
@@ -15042,17 +15266,32 @@ function withSessionQuotaHint(error, retryAfterMs) {
15042
15266
  * and no explanation of which of its four fingerprint facts was wrong. That
15043
15267
  * reaches the caller as a bare `client` failure, and a bare 4xx is what the
15044
15268
  * host then renders in its own words: the user in #96 saw "当前请求的额度已用尽"
15045
- * for a request that had never been billed. The wording pointed at waiting,
15046
- * while the actual cause was "this build's fingerprint no longer matches, update
15047
- * the plugin" — the two need opposite responses.
15269
+ * for a request that had never been billed.
15048
15270
  *
15049
- * The lane cannot tell them apart from the outside (both look like a refusal
15050
- * with a thin body), so this does not pretend to. It names the actionable
15051
- * reading FIRST — the fingerprint, which the user can fix by updating — and
15052
- * keeps the quota possibility second, because it is the one that fixes itself.
15271
+ * ## The premise changed (verified 2026-11-12)
15053
15272
  *
15054
- * A 429 keeps its own hint ({@link withSessionQuotaHint}): that one really is
15055
- * quota, and blurring the two would lose a distinction worth keeping.
15273
+ * This used to say "the fingerprint moved, update the plugin". It no longer
15274
+ * does, because a raw call now answers:
15275
+ *
15276
+ * ```
15277
+ * {"type":"error","error":{"type":"FreeUsageLimitError",
15278
+ * "message":"Free usage limit reached. Free models work in OpenCode
15279
+ * (https://opencode.ai); subscribe to OpenCode Go to keep going…"}}
15280
+ * ```
15281
+ *
15282
+ * That is not a fingerprint rejection and not a per-conversation budget: the
15283
+ * upstream has moved free models behind the OpenCode client itself. No header,
15284
+ * UA or path change reaches it, which is why #96 could not be fixed by
15285
+ * matching the gate more exactly — the gate is gone, replaced by an account
15286
+ * metering that a third-party client cannot enter.
15287
+ *
15288
+ * So the message names the real situation FIRST and stops promising that a
15289
+ * plugin update will help. `FreeUsageLimitError` is called out by name because
15290
+ * it is the specific shape of "this lane is closed to you", and telling the
15291
+ * user to wait or retry would spend their time on something that cannot work.
15292
+ *
15293
+ * A 429 keeps its own hint ({@link withSessionQuotaHint}). The distinction is
15294
+ * worth keeping: 429 is a budget that resets, 403 is a door that closed.
15056
15295
  */
15057
15296
  function withFreeTierHint(status, refusal, retryAfterMs) {
15058
15297
  const base = classifyUpstream(status, refusal, retryAfterMs, "");
@@ -15060,7 +15299,14 @@ function withFreeTierHint(status, refusal, retryAfterMs) {
15060
15299
  const separator = base.message.indexOf(": ");
15061
15300
  const detail = separator === -1 ? "" : base.message.slice(separator + 2);
15062
15301
  const kept = detail === "" ? "" : ` (provider said: ${detail})`;
15063
- 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);
15302
+ /**
15303
+ * `FreeUsageLimitError` means the upstream has closed this lane to non-client
15304
+ * traffic. Distinguished from a generic refusal so the advice can be true:
15305
+ * updating the plugin will not help, and only a real OpenCode client (or a
15306
+ * subscription) can.
15307
+ */
15308
+ const closed = /FreeUsageLimitError|Free usage limit reached/iu.test(refusal);
15309
+ 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);
15064
15310
  }
15065
15311
  /**
15066
15312
  * POST one streaming turn and hand back chat-shaped deltas.
@@ -19210,6 +19456,218 @@ function paidAlternativeFor(model, models) {
19210
19456
  return paidSiblingOf(model, models);
19211
19457
  }
19212
19458
  //#endregion
19459
+ //#region src/non-streaming.ts
19460
+ /**
19461
+ * Reassemble a streamed turn into one `chat.completion` document.
19462
+ *
19463
+ * The pool lane (and every other lane that buffers before answering) asks the
19464
+ * upstream for SSE and forwards it; it cannot ask for JSON because
19465
+ * `prepareChatBody` forces streaming. A caller that sent `stream: false`
19466
+ * therefore used to receive `text/event-stream` anyway, and an OpenAI client
19467
+ * parsing that body as JSON failed with `Unexpected token 'd'`.
19468
+ *
19469
+ * The channel lane already honours the flag (see `serveChannelCompletion`). This
19470
+ * module gives the other lanes the same behaviour without touching their wire
19471
+ * contract when the caller did NOT ask for it: `wantsNonStreaming` is true only
19472
+ * for an explicit `stream: false`, so an absent flag keeps today's SSE reply.
19473
+ *
19474
+ * @module dsh-xdpool/non-streaming
19475
+ */
19476
+ /**
19477
+ * True only when the caller asked for JSON by saying so.
19478
+ *
19479
+ * `stream` absent must stay streaming: the Harness omits the flag and reads
19480
+ * SSE, and a missing field silently means "false" to plenty of JSON parsers —
19481
+ * honouring that reading would break every existing client.
19482
+ */
19483
+ function wantsNonStreaming(raw) {
19484
+ let body;
19485
+ try {
19486
+ body = JSON.parse(raw);
19487
+ } catch {
19488
+ return false;
19489
+ }
19490
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
19491
+ return body["stream"] === false;
19492
+ }
19493
+ function createTurnAccumulator(modelId) {
19494
+ return {
19495
+ id: `chatcmpl-xdpool-${randomBytes(6).toString("base64url")}`,
19496
+ created: Math.floor(Date.now() / 1e3),
19497
+ model: modelId ?? "",
19498
+ text: "",
19499
+ reasoning: "",
19500
+ toolCalls: [],
19501
+ usage: void 0,
19502
+ rawUsage: void 0,
19503
+ finish: "stop"
19504
+ };
19505
+ }
19506
+ /**
19507
+ * Merge one tool-call fragment into its slot.
19508
+ *
19509
+ * The upstream streams a call as an opening fragment carrying `name` and then
19510
+ * argument deltas that do NOT: a plain spread would erase the name on the
19511
+ * second fragment and leave the caller with `tool_calls[0].function.name ===
19512
+ * undefined`. An empty or missing name therefore means "no opinion here", never
19513
+ * "clear what you have".
19514
+ */
19515
+ function mergeTurnToolCall(existing, fragment) {
19516
+ const before = existing["function"] ?? {};
19517
+ const next = fragment["function"] ?? {};
19518
+ const name = typeof next["name"] === "string" && next["name"] !== "" ? next["name"] : before["name"];
19519
+ const merged = {
19520
+ ...existing,
19521
+ ...fragment,
19522
+ function: {
19523
+ ...before,
19524
+ ...next,
19525
+ ...name === void 0 ? {} : { name },
19526
+ arguments: `${String(before["arguments"] ?? "")}${String(next["arguments"] ?? "")}`
19527
+ }
19528
+ };
19529
+ if (typeof fragment["id"] === "string" && fragment["id"] !== "") merged["id"] = fragment["id"];
19530
+ else if (typeof existing["id"] === "string") merged["id"] = existing["id"];
19531
+ return merged;
19532
+ }
19533
+ /** Merge one delta/message object (content, reasoning, tool calls) into the turn. */
19534
+ function absorbDelta(turn, delta) {
19535
+ if (typeof delta["content"] === "string") turn.text += delta["content"];
19536
+ const reasoning = delta["reasoning_content"] ?? delta["reasoning"];
19537
+ if (typeof reasoning === "string") turn.reasoning += reasoning;
19538
+ const calls = delta["tool_calls"];
19539
+ if (!Array.isArray(calls)) return;
19540
+ for (const call of calls) {
19541
+ if (typeof call !== "object" || call === null) continue;
19542
+ const fragment = call;
19543
+ const index = Number(fragment["index"] ?? turn.toolCalls.length);
19544
+ const slot = Number.isInteger(index) && index >= 0 ? index : turn.toolCalls.length;
19545
+ turn.toolCalls[slot] = mergeTurnToolCall(turn.toolCalls[slot] ?? {}, fragment);
19546
+ }
19547
+ }
19548
+ /**
19549
+ * Fold one SSE `data:` payload into the accumulator.
19550
+ *
19551
+ * Reads the same three shapes the forwarding path already tolerates upstream:
19552
+ * OpenAI `choices[].delta`, a non-streaming `choices[].message`, and the
19553
+ * gateway's `data.content` wrapper.
19554
+ */
19555
+ function foldPayload(turn, payload) {
19556
+ if (payload === "" || payload === "[DONE]") return;
19557
+ let parsed;
19558
+ try {
19559
+ parsed = JSON.parse(payload);
19560
+ } catch {
19561
+ return;
19562
+ }
19563
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
19564
+ const frame = parsed;
19565
+ const usage = parseUsage(frame["usage"]);
19566
+ if (usage !== void 0) {
19567
+ turn.usage = usage;
19568
+ turn.rawUsage = frame["usage"];
19569
+ }
19570
+ const choices = frame["choices"];
19571
+ if (Array.isArray(choices) && choices.length > 0) {
19572
+ const choice = choices[0];
19573
+ if (typeof choice === "object" && choice !== null) {
19574
+ const entry = choice;
19575
+ const delta = entry["delta"];
19576
+ if (typeof delta === "object" && delta !== null) absorbDelta(turn, delta);
19577
+ const message = entry["message"];
19578
+ if (typeof message === "object" && message !== null) absorbDelta(turn, message);
19579
+ const reason = entry["finish_reason"];
19580
+ if (typeof reason === "string" && reason !== "") turn.finish = reason;
19581
+ }
19582
+ }
19583
+ const wrapper = frame["data"];
19584
+ if (typeof wrapper === "object" && wrapper !== null) {
19585
+ const content = wrapper["content"];
19586
+ if (typeof content === "string") turn.text += content;
19587
+ const reason = wrapper["finish_reason"];
19588
+ if (typeof reason === "string" && reason !== "") turn.finish = reason;
19589
+ }
19590
+ }
19591
+ /** Spell the accumulated turn as one non-streaming `chat.completion` document. */
19592
+ function turnToCompletion(turn) {
19593
+ const calls = turn.toolCalls.filter((call) => call !== void 0);
19594
+ return {
19595
+ id: turn.id,
19596
+ object: "chat.completion",
19597
+ created: turn.created,
19598
+ model: turn.model,
19599
+ choices: [{
19600
+ index: 0,
19601
+ message: {
19602
+ role: "assistant",
19603
+ content: turn.text === "" && calls.length > 0 ? null : turn.text,
19604
+ ...turn.reasoning === "" ? {} : { reasoning_content: turn.reasoning },
19605
+ ...calls.length === 0 ? {} : { tool_calls: calls }
19606
+ },
19607
+ finish_reason: turn.finish
19608
+ }],
19609
+ ...turn.rawUsage === void 0 ? {} : { usage: turn.rawUsage }
19610
+ };
19611
+ }
19612
+ /**
19613
+ * Split a growing text buffer into complete SSE `data:` payloads.
19614
+ *
19615
+ * A frame's own blank line is the only reliable boundary — JSON can contain
19616
+ * anything, but it cannot contain an unescaped newline — so nothing is parsed
19617
+ * out of a partial frame.
19618
+ */
19619
+ function drainSsePayloads(buffer) {
19620
+ const payloads = [];
19621
+ let rest = buffer;
19622
+ for (;;) {
19623
+ const span = sseFrameSpan(rest);
19624
+ if (span === void 0) break;
19625
+ const frame = rest.subarray(0, span.contentEnd).toString("utf8");
19626
+ rest = rest.subarray(span.frameEnd);
19627
+ for (const line of frame.split(/\r?\n/u)) {
19628
+ const trimmed = line.trim();
19629
+ if (!trimmed.startsWith("data:")) continue;
19630
+ payloads.push(trimmed.slice(5).trim());
19631
+ }
19632
+ }
19633
+ return {
19634
+ payloads,
19635
+ rest
19636
+ };
19637
+ }
19638
+ /**
19639
+ * Where one SSE frame ends inside a buffer.
19640
+ *
19641
+ * Both offsets come back because a frame's CONTENT ends before its SEPARATOR
19642
+ * does. This is the same rule `frameSpan` in `shim.ts` applies; it lives here
19643
+ * too so the reassembler does not have to reach into the shim's closure.
19644
+ */
19645
+ function sseFrameSpan(buf) {
19646
+ const bare = buf.indexOf("\n\n");
19647
+ const crlf = buf.indexOf("\r\n\r\n");
19648
+ if (bare === -1 && crlf === -1) return void 0;
19649
+ if (crlf !== -1 && (bare === -1 || crlf < bare)) return {
19650
+ contentEnd: crlf,
19651
+ frameEnd: crlf + 4
19652
+ };
19653
+ return {
19654
+ contentEnd: bare,
19655
+ frameEnd: bare + 2
19656
+ };
19657
+ }
19658
+ /**
19659
+ * Fold a buffered lane's frames into the one document `stream: false` asked for.
19660
+ *
19661
+ * The buffering lanes (aggregate, free/co-paid extras, chain members) already
19662
+ * hold their whole answer before writing, so honouring the flag there costs one
19663
+ * pass and no wire change for streaming callers.
19664
+ */
19665
+ function bufferedFramesToCompletion(frames, modelId) {
19666
+ const turn = createTurnAccumulator(modelId);
19667
+ for (const payload of frames) foldPayload(turn, payload);
19668
+ return turnToCompletion(turn);
19669
+ }
19670
+ //#endregion
19213
19671
  //#region src/channel-lane.ts
19214
19672
  /**
19215
19673
  * A request this lane will not serve as written, and that is the caller's to fix.
@@ -19890,6 +20348,10 @@ function createWorkBuddyShim(options) {
19890
20348
  writeOpenAIError(res, KIND_STATUS[kind], `${target.lane}_${kind}`, message);
19891
20349
  return;
19892
20350
  }
20351
+ if (wantsNonStreaming(raw)) {
20352
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
20353
+ return;
20354
+ }
19893
20355
  res.writeHead(200, {
19894
20356
  "Content-Type": "text/event-stream",
19895
20357
  "Cache-Control": "no-cache",
@@ -20101,6 +20563,10 @@ function createWorkBuddyShim(options) {
20101
20563
  writeOpenAIError(res, 500, "aggregate_internal", error instanceof Error ? error.message : String(error));
20102
20564
  return;
20103
20565
  }
20566
+ if (wantsNonStreaming(raw)) {
20567
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
20568
+ return;
20569
+ }
20104
20570
  res.writeHead(200, {
20105
20571
  "Content-Type": "text/event-stream",
20106
20572
  "Cache-Control": "no-cache",
@@ -20411,6 +20877,10 @@ function createWorkBuddyShim(options) {
20411
20877
  noteSwitch(member.modelId, kind, last.status);
20412
20878
  continue;
20413
20879
  }
20880
+ if (wantsNonStreaming(raw)) {
20881
+ writeJson$1(res, 200, bufferedFramesToCompletion(hostFrames, member.modelId));
20882
+ return;
20883
+ }
20414
20884
  res.writeHead(200, {
20415
20885
  "Content-Type": "text/event-stream",
20416
20886
  "Cache-Control": "no-cache",
@@ -20442,12 +20912,17 @@ function createWorkBuddyShim(options) {
20442
20912
  const result = await client.chatStream(account.credential, prepared, memberSignal, conversationKey);
20443
20913
  if (result.ok) {
20444
20914
  const turnId = randomBytes(8).toString("hex");
20445
- await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, usageRecorder === void 0 ? void 0 : {
20915
+ const memberUsage = usageRecorder === void 0 ? void 0 : {
20446
20916
  recorder: usageRecorder,
20447
20917
  region: region ?? "cn",
20448
20918
  model: member.modelId,
20449
20919
  turnId
20450
- });
20920
+ };
20921
+ if (wantsNonStreaming(raw)) {
20922
+ await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, memberUsage, member.modelId);
20923
+ return;
20924
+ }
20925
+ await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, memberUsage);
20451
20926
  return;
20452
20927
  }
20453
20928
  last = {
@@ -20513,6 +20988,10 @@ function createWorkBuddyShim(options) {
20513
20988
  continue;
20514
20989
  }
20515
20990
  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("; ")}`);
20991
+ if (wantsNonStreaming(raw)) {
20992
+ writeJson$1(res, 200, bufferedFramesToCompletion(frames, member.modelId));
20993
+ return;
20994
+ }
20516
20995
  res.writeHead(200, {
20517
20996
  "Content-Type": "text/event-stream",
20518
20997
  "Cache-Control": "no-cache",
@@ -20647,6 +21126,10 @@ function createWorkBuddyShim(options) {
20647
21126
  tried.push(account.label);
20648
21127
  const result = await client.chatStream(account.credential, prepared, controller.signal, conversationKey);
20649
21128
  if (result.ok) {
21129
+ if (wantsNonStreaming(raw)) {
21130
+ await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usageContext, modelId);
21131
+ return;
21132
+ }
20650
21133
  await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, usageContext);
20651
21134
  return;
20652
21135
  }
@@ -20711,6 +21194,10 @@ function createWorkBuddyShim(options) {
20711
21194
  })()
20712
21195
  });
20713
21196
  if (recovered.ok) {
21197
+ if (wantsNonStreaming(raw)) {
21198
+ await serveSuccessfulJson(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext, modelId);
21199
+ return;
21200
+ }
20714
21201
  await serveSuccessfulStream(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext);
20715
21202
  return;
20716
21203
  }
@@ -20793,6 +21280,7 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
20793
21280
  logger?.info?.(`dsh-xdpool: served by ${account.label}`);
20794
21281
  pool.noteServed(account.id);
20795
21282
  refreshBalance(account);
21283
+ if (pool.expiryReadingOf(account.id).stale) pool.warmExpiryReadingFor(account.id);
20796
21284
  res.writeHead(200, {
20797
21285
  "Content-Type": "text/event-stream",
20798
21286
  "Cache-Control": "no-cache",
@@ -20868,6 +21356,79 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
20868
21356
  body.pipe(strip).pipe(res);
20869
21357
  }
20870
21358
  /**
21359
+ * Answer one already-successful upstream stream as a single JSON document.
21360
+ *
21361
+ * The pool lane asks for SSE (`prepareChatBody` forces it), so the only way to
21362
+ * honour `stream: false` is to consume the whole body here and reassemble it.
21363
+ * Nothing is written until the body completes, which is also why a mid-flight
21364
+ * failure can still become a proper HTTP error instead of a 200 that ends in a
21365
+ * truncated answer.
21366
+ *
21367
+ * The bookkeeping deliberately mirrors `serveSuccessfulStream`: same
21368
+ * `noteServed`, same background balance refresh, same once-only usage filing —
21369
+ * a turn must not cost differently depending on how the caller asked to read it.
21370
+ */
21371
+ async function serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usage, modelId) {
21372
+ logger?.info?.(`dsh-xdpool: served by ${account.label} (non-streaming)`);
21373
+ pool.noteServed(account.id);
21374
+ refreshBalance(account);
21375
+ const tracker = new StreamTracker(Date.now());
21376
+ const turn = createTurnAccumulator(modelId);
21377
+ let recorded = false;
21378
+ const finish = (ok) => {
21379
+ if (recorded) return;
21380
+ recorded = true;
21381
+ if (usage?.recorder === void 0) return;
21382
+ usage.recorder.record({
21383
+ channel: "workbuddy",
21384
+ region: usage.region,
21385
+ model: usage.model,
21386
+ account: account.label,
21387
+ turnId: usage.turnId,
21388
+ at: Date.now(),
21389
+ ok,
21390
+ ...tracker.ttftMs === void 0 ? {} : { ttftMs: tracker.ttftMs },
21391
+ ...tracker.decodeMs === void 0 ? {} : { decodeMs: tracker.decodeMs },
21392
+ ...tracker.usage === void 0 ? {} : { usage: tracker.usage }
21393
+ });
21394
+ };
21395
+ /**
21396
+ * Explicitly `Buffer<ArrayBufferLike>`: `Buffer.alloc(0)` infers
21397
+ * `Buffer<ArrayBuffer>`, and `Buffer.concat` widens to `ArrayBufferLike`, so the
21398
+ * assignment back into `buffer` fails under strict lib types. Annotating the accumulator
21399
+ * once is clearer than casting at each of the two assignments.
21400
+ */
21401
+ let buffer = Buffer.alloc(0);
21402
+ let failure;
21403
+ try {
21404
+ for await (const chunk of Readable.fromWeb(result.response.body)) {
21405
+ tracker.markFirstByte(Date.now());
21406
+ buffer = buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([buffer, chunk]);
21407
+ const drained = drainSsePayloads(buffer);
21408
+ buffer = drained.rest;
21409
+ for (const payload of drained.payloads) foldPayload(turn, payload);
21410
+ }
21411
+ if (buffer.length > 0) for (const line of buffer.toString("utf8").split(/\r?\n/u)) {
21412
+ const trimmed = line.trim();
21413
+ if (trimmed.startsWith("data:")) foldPayload(turn, trimmed.slice(5).trim());
21414
+ }
21415
+ tracker.finish(Date.now());
21416
+ if (turn.usage !== void 0) tracker.usage = turn.usage;
21417
+ } catch (error) {
21418
+ failure = error;
21419
+ logger?.warn("dsh-xdpool: non-streaming reassembly failed mid-flight", error);
21420
+ }
21421
+ if (failure !== void 0) {
21422
+ finish(false);
21423
+ if (!res.headersSent) writeOpenAIError(res, 502, "upstream_stream_error", `the upstream stream broke before the answer completed: ${failure instanceof Error ? failure.message : String(failure)}`);
21424
+ else if (res.writable) res.end();
21425
+ return;
21426
+ }
21427
+ finish(true);
21428
+ if (!res.headersSent) writeJson$1(res, 200, turnToCompletion(turn));
21429
+ else if (res.writable) res.end();
21430
+ }
21431
+ /**
20871
21432
  * Compact an over-long conversation and retry it once.
20872
21433
  *
20873
21434
  * Strategy, in order:
@@ -22696,7 +23257,17 @@ function apply(ctx, config = {}) {
22696
23257
  ...contextBudgets === void 0 ? {} : { contextBudgets }
22697
23258
  };
22698
23259
  const fallbackSelection = (region) => {
22699
- return legacySelection.enabledModelIds === void 0 && legacySelection.imageModelIds === void 0 && legacySelection.contextBudgets === void 0 ? core.catalogs[region].currentSelection() : legacySelection;
23260
+ /**
23261
+ * An empty ARRAY counts as absent here too.
23262
+ *
23263
+ * The legacy keys may be present but empty: a host that initialises
23264
+ * `enabledModelIds: []` before the picker is first used (DSH 0.2.2-rc.1 does) makes
23265
+ * "the key exists" a very different statement from "the user chose models". Reading
23266
+ * `[]` as a real selection narrowed the catalog to zero models — the `has no
23267
+ * configured model "<id>"` report in issue #122.
23268
+ */
23269
+ const list = legacySelection.enabledModelIds;
23270
+ return (list === void 0 || list.length === 0) && legacySelection.imageModelIds === void 0 && legacySelection.contextBudgets === void 0 ? core.catalogs[region].currentSelection() : legacySelection;
22700
23271
  };
22701
23272
  core.catalogs.cn.applySelection(modelSelectionCn ?? fallbackSelection("cn"));
22702
23273
  core.catalogs.global.applySelection(modelSelectionGlobal ?? fallbackSelection("global"));