heybash-xdpool 1.0.4 → 1.0.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/CHANGELOG.md +12 -0
- package/lib/bin.js +293 -11
- package/lib/client.js +101 -76
- package/lib/index.d.ts +190 -5
- package/lib/index.js +685 -37
- package/package.json +2 -1
- package/tools/sync-npmmirror.mjs +16 -3
- package/vendor/channel-pack/pack.js +41 -3
package/lib/index.js
CHANGED
|
@@ -1513,8 +1513,18 @@ var WorkBuddyUpstreamClient = class {
|
|
|
1513
1513
|
if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
|
|
1514
1514
|
return models;
|
|
1515
1515
|
}
|
|
1516
|
-
/**
|
|
1517
|
-
|
|
1516
|
+
/**
|
|
1517
|
+
* Read-only credits query, aggregated by package. Does not consume credits.
|
|
1518
|
+
*
|
|
1519
|
+
* `signal` is the caller's cancellation, merged with the built-in timeout
|
|
1520
|
+
* rather than replacing it: the pool's background warm must give up when the
|
|
1521
|
+
* host shuts down, and a caller that has already gone away must not leave a
|
|
1522
|
+
* 30 s request running. `AbortSignal.any` is already the repo's way of
|
|
1523
|
+
* combining these (see the pricing probe in the shim), and the timeout stays
|
|
1524
|
+
* in force so a signal-less caller keeps the old behaviour exactly.
|
|
1525
|
+
*/
|
|
1526
|
+
async fetchCredits(credential, signal) {
|
|
1527
|
+
const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
|
|
1518
1528
|
const now = /* @__PURE__ */ new Date();
|
|
1519
1529
|
const fmt = (date) => {
|
|
1520
1530
|
const p = (n) => n.toString().padStart(2, "0");
|
|
@@ -1531,7 +1541,7 @@ var WorkBuddyUpstreamClient = class {
|
|
|
1531
1541
|
PackageEndTimeRangeBegin: fmt(now),
|
|
1532
1542
|
PackageEndTimeRangeEnd: fmt(new Date(now.getTime() + 3185136e6))
|
|
1533
1543
|
}),
|
|
1534
|
-
signal: AbortSignal.timeout
|
|
1544
|
+
signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
|
|
1535
1545
|
});
|
|
1536
1546
|
const envelope = await readEnvelope(response);
|
|
1537
1547
|
if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
|
|
@@ -3724,6 +3734,13 @@ const EXHAUST_COOLDOWN_MS = 18e5;
|
|
|
3724
3734
|
*/
|
|
3725
3735
|
const CREDENTIAL_DEAD_COOLDOWN_MS = 18e5;
|
|
3726
3736
|
/**
|
|
3737
|
+
* Shortest gap between two attempts at the same account's deadline reading.
|
|
3738
|
+
*
|
|
3739
|
+
* Only failed attempts are actually throttled by this: a successful read stamps
|
|
3740
|
+
* the reading itself, so {@link EXPIRY_READING_TTL_MS} takes over from there.
|
|
3741
|
+
*/
|
|
3742
|
+
const EXPIRY_WARM_RETRY_MS = 6e4;
|
|
3743
|
+
/**
|
|
3727
3744
|
* Does this refresh failure prove the credential itself is dead?
|
|
3728
3745
|
*
|
|
3729
3746
|
* The upstream answers a revoked refresh token with `invalid_grant: Offline user
|
|
@@ -3752,6 +3769,7 @@ var WorkBuddyAccountPool = class {
|
|
|
3752
3769
|
credentialDeadCooldownMs;
|
|
3753
3770
|
client;
|
|
3754
3771
|
refreshMarginMs;
|
|
3772
|
+
expiryReadingTtlMs;
|
|
3755
3773
|
accounts = [];
|
|
3756
3774
|
/**
|
|
3757
3775
|
* Files the last scan could not read, with the reason.
|
|
@@ -3847,11 +3865,42 @@ var WorkBuddyAccountPool = class {
|
|
|
3847
3865
|
* their own cycle and are therefore never urgent — which is why this is
|
|
3848
3866
|
* written from the same `fetchCredits` reading that fills `creditBalances`.
|
|
3849
3867
|
*
|
|
3850
|
-
*
|
|
3851
|
-
*
|
|
3868
|
+
* A positive value is a deadline. The two other states are kept in
|
|
3869
|
+
* {@link creditExpiryNone} and {@link creditExpiryReadAt} rather than as a
|
|
3870
|
+
* missing key, because a missing key cannot tell "we never looked" from "we
|
|
3871
|
+
* looked and nothing has a deadline" — and only the first is worth reading
|
|
3872
|
+
* again. An account whose packs are all monthly reads as `none` forever, which
|
|
3873
|
+
* is exactly right: asking again cannot change the answer (S1).
|
|
3852
3874
|
*/
|
|
3853
3875
|
creditExpiry = /* @__PURE__ */ new Map();
|
|
3854
3876
|
/**
|
|
3877
|
+
* Accounts whose last reading found NO one-off deadline (all monthly packs, or
|
|
3878
|
+
* none at all). Written instead of deleting the key, so the account stops
|
|
3879
|
+
* being a candidate for re-reading.
|
|
3880
|
+
*/
|
|
3881
|
+
creditExpiryNone = /* @__PURE__ */ new Set();
|
|
3882
|
+
/** When each account's deadline reading was taken, epoch ms. */
|
|
3883
|
+
creditExpiryReadAt = /* @__PURE__ */ new Map();
|
|
3884
|
+
/**
|
|
3885
|
+
* Accounts whose deadline reading is being fetched right now.
|
|
3886
|
+
*
|
|
3887
|
+
* Same de-duplication idea as {@link refreshInflight}, for the same reason: a
|
|
3888
|
+
* scan-triggered warm and a request-triggered top-up must not both spend a
|
|
3889
|
+
* billing round trip on the same account. A Set rather than a Map of promises
|
|
3890
|
+
* because no caller ever awaits the warm — the point is only that a second
|
|
3891
|
+
* pass skips it.
|
|
3892
|
+
*/
|
|
3893
|
+
expiryWarmInflight = /* @__PURE__ */ new Set();
|
|
3894
|
+
/**
|
|
3895
|
+
* Last time the pool tried to warm an account's deadline reading, epoch ms.
|
|
3896
|
+
*
|
|
3897
|
+
* The TTL is the success gate, not a retry gate: a failed read writes nothing,
|
|
3898
|
+
* so without this a permanently failing billing endpoint would be hit on every
|
|
3899
|
+
* scan and every served request. One attempt per account per minute is cheap
|
|
3900
|
+
* and still recovers quickly from a transient failure.
|
|
3901
|
+
*/
|
|
3902
|
+
expiryWarmAttemptAt = /* @__PURE__ */ new Map();
|
|
3903
|
+
/**
|
|
3855
3904
|
* Last time each account served a request, epoch ms. Drives the idle term
|
|
3856
3905
|
* of the priority-mode weighting below: an account that just served loses to
|
|
3857
3906
|
* one that has been idle, so a small pool stops hammering a single account.
|
|
@@ -3896,6 +3945,7 @@ var WorkBuddyAccountPool = class {
|
|
|
3896
3945
|
this.credentialDeadCooldownMs = options.credentialDeadCooldownMs ?? CREDENTIAL_DEAD_COOLDOWN_MS;
|
|
3897
3946
|
this.client = options.client;
|
|
3898
3947
|
this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
|
|
3948
|
+
this.expiryReadingTtlMs = options.expiryReadingTtlMs ?? 36e5;
|
|
3899
3949
|
this.distribution = options.distribution ?? "priority";
|
|
3900
3950
|
this.persistent = options.persistent ?? false;
|
|
3901
3951
|
this.storePath = accountStorePath();
|
|
@@ -4110,6 +4160,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4110
4160
|
ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
|
|
4111
4161
|
this.accounts = ordered;
|
|
4112
4162
|
this.lastScanAtMs = Date.now();
|
|
4163
|
+
this.warmExpiryReadings();
|
|
4113
4164
|
if (this.persistent) try {
|
|
4114
4165
|
const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
|
|
4115
4166
|
if (leaving.length > 0) this.logger?.warn?.(`heybash-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.`);
|
|
@@ -4120,6 +4171,76 @@ var WorkBuddyAccountPool = class {
|
|
|
4120
4171
|
}
|
|
4121
4172
|
return this.accounts;
|
|
4122
4173
|
}
|
|
4174
|
+
/**
|
|
4175
|
+
* Warm the deadline readings that `expiry` mode sorts on.
|
|
4176
|
+
*
|
|
4177
|
+
* Fire-and-forget on purpose, from `scan()`: the pool's first request arrives
|
|
4178
|
+
* before any reading exists, and the honest answer to that is the documented
|
|
4179
|
+
* fallback plus a log line, not a stalled request. Everything about the call
|
|
4180
|
+
* is chosen to be unable to make things worse:
|
|
4181
|
+
*
|
|
4182
|
+
* - `this.client` may not exist (a host that wired only token refresh), in
|
|
4183
|
+
* which case there is nothing to read with and the pass is a no-op — the
|
|
4184
|
+
* same guard `ensureFresh` uses;
|
|
4185
|
+
* - a dead sign-in is skipped, and a successful read NEVER calls
|
|
4186
|
+
* `clearCredentialDead`. That is the difference between this and
|
|
4187
|
+
* `reviveBenched`: the billing endpoint answers 200 for a banned account
|
|
4188
|
+
* (observed on 11140), so treating a read as proof of health is what got a
|
|
4189
|
+
* banned account revived six times in a day (S2). Only a token refresh or a
|
|
4190
|
+
* fresh sign-in may clear that mark;
|
|
4191
|
+
* - accounts whose reading is fresh enough are skipped, and so are accounts
|
|
4192
|
+
* already being read (S10's de-duplication, mirroring `refreshInflight`);
|
|
4193
|
+
* - a failed read writes nothing and only warns, so the next pass tries
|
|
4194
|
+
* again without the failure being mistaken for a reading.
|
|
4195
|
+
*/
|
|
4196
|
+
warmExpiryReadings() {
|
|
4197
|
+
if (this.client?.fetchCredits === void 0) return;
|
|
4198
|
+
for (const account of this.accounts) this.warmExpiryReadingFor(account.id);
|
|
4199
|
+
}
|
|
4200
|
+
/** One account's warm read; see {@link warmExpiryReadings} for the rules. */
|
|
4201
|
+
async warmOneExpiryReading(account, client) {
|
|
4202
|
+
this.expiryWarmInflight.add(account.id);
|
|
4203
|
+
this.expiryWarmAttemptAt.set(account.id, Date.now());
|
|
4204
|
+
try {
|
|
4205
|
+
const credits = await client.fetchCredits(account.credential);
|
|
4206
|
+
this.noteExpiryOnly(account.id, credits.nearestExpiryMs);
|
|
4207
|
+
} catch (error) {
|
|
4208
|
+
this.logger?.warn?.(`heybash-xdpool: could not read credit deadlines for ${account.label} (read failed); expiry mode keeps falling back for it until a read succeeds`, error);
|
|
4209
|
+
} finally {
|
|
4210
|
+
this.expiryWarmInflight.delete(account.id);
|
|
4211
|
+
}
|
|
4212
|
+
}
|
|
4213
|
+
/**
|
|
4214
|
+
* Top up one account's deadline reading, from wherever the pool notices it is
|
|
4215
|
+
* missing or stale.
|
|
4216
|
+
*
|
|
4217
|
+
* The request path is the second caller (after `scan()`), because a reading
|
|
4218
|
+
* ages out while the pool is busy too: the shim calls this for the account that
|
|
4219
|
+
* just served a request, which is the one whose spend is most likely to have
|
|
4220
|
+
* moved its deadline. No timer is created — the existing balance refresh is
|
|
4221
|
+
* already the natural heartbeat, and this rides on it.
|
|
4222
|
+
*
|
|
4223
|
+
* Every gate lives here rather than in the callers, so both paths obey exactly
|
|
4224
|
+
* the same rules: no client, no account, a rejected sign-in, an already-running
|
|
4225
|
+
* read, a finished "nothing expires" answer, a fresh reading, or an attempt
|
|
4226
|
+
* made within the last minute all mean "do nothing".
|
|
4227
|
+
*/
|
|
4228
|
+
warmExpiryReadingFor(accountId) {
|
|
4229
|
+
if (this.distribution !== "expiry") return;
|
|
4230
|
+
const client = this.client;
|
|
4231
|
+
if (client?.fetchCredits === void 0) return;
|
|
4232
|
+
const account = this.accounts.find((item) => item.id === accountId);
|
|
4233
|
+
if (account === void 0) return;
|
|
4234
|
+
const now = Date.now();
|
|
4235
|
+
if ((account.credentialDeadUntilMs ?? 0) > now) return;
|
|
4236
|
+
if (this.expiryWarmInflight.has(accountId)) return;
|
|
4237
|
+
const reading = this.expiryReadingOf(accountId, now);
|
|
4238
|
+
if (reading.state === "none") return;
|
|
4239
|
+
if (reading.state === "at" && !reading.stale) return;
|
|
4240
|
+
const lastAttempt = this.expiryWarmAttemptAt.get(accountId) ?? 0;
|
|
4241
|
+
if (lastAttempt > (reading.readAtMs ?? 0) && now - lastAttempt < EXPIRY_WARM_RETRY_MS) return;
|
|
4242
|
+
this.warmOneExpiryReading(account, client);
|
|
4243
|
+
}
|
|
4123
4244
|
/** All accounts, cooldown state included. */
|
|
4124
4245
|
list(region) {
|
|
4125
4246
|
if (region === void 0) return this.accounts;
|
|
@@ -4467,18 +4588,37 @@ var WorkBuddyAccountPool = class {
|
|
|
4467
4588
|
* A pool where nobody has a known expiry therefore behaves exactly like
|
|
4468
4589
|
* priority, which is the honest degradation: without a reading there is
|
|
4469
4590
|
* nothing to sort by.
|
|
4591
|
+
*
|
|
4592
|
+
* What this method must NOT do is pretend. With only SOME readings in hand it
|
|
4593
|
+
* still has to fall back to `pool[0]`, because picking the earliest of the
|
|
4594
|
+
* accounts that happen to have answered would silently drop the account that
|
|
4595
|
+
* really dies first — the failure mode S0 in `EXPIRY-ADVERSARIAL-20261111.md`
|
|
4596
|
+
* called "worse than not fixing it", since the pick looks plausible and is
|
|
4597
|
+
* wrong. So the incomplete case is announced instead: the caller keeps the old
|
|
4598
|
+
* semantics and the log says which accounts were not read.
|
|
4470
4599
|
*/
|
|
4471
4600
|
pickByExpiry(pool) {
|
|
4601
|
+
const now = Date.now();
|
|
4602
|
+
const unread = [];
|
|
4603
|
+
const stale = [];
|
|
4472
4604
|
let best;
|
|
4473
4605
|
let bestAt = Number.POSITIVE_INFINITY;
|
|
4474
4606
|
for (const account of pool) {
|
|
4475
|
-
const
|
|
4476
|
-
if (
|
|
4607
|
+
const reading = this.expiryReadingOf(account.id, now);
|
|
4608
|
+
if (reading.stale) stale.push(account);
|
|
4609
|
+
if (reading.state === "unread" || reading.stale) {
|
|
4610
|
+
unread.push(account);
|
|
4611
|
+
continue;
|
|
4612
|
+
}
|
|
4613
|
+
if (reading.state === "none") continue;
|
|
4614
|
+
const at = reading.at ?? Number.POSITIVE_INFINITY;
|
|
4477
4615
|
if (at < bestAt) {
|
|
4478
4616
|
best = account;
|
|
4479
4617
|
bestAt = at;
|
|
4480
4618
|
}
|
|
4481
4619
|
}
|
|
4620
|
+
if (stale.length > 0) this.logger?.info?.(`heybash-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`);
|
|
4621
|
+
if (unread.length > 0) this.logger?.warn?.(`heybash-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.`);
|
|
4482
4622
|
return best ?? pool[0];
|
|
4483
4623
|
}
|
|
4484
4624
|
/**
|
|
@@ -4656,21 +4796,91 @@ var WorkBuddyAccountPool = class {
|
|
|
4656
4796
|
* merged: a pack that has been spent or has died disappears from the next
|
|
4657
4797
|
* reading, and keeping the stale deadline would pin the pool to an account
|
|
4658
4798
|
* whose credits are already gone — the opposite of what `expiry` mode wants.
|
|
4799
|
+
*
|
|
4800
|
+
* "Nothing expires" is a real answer, not the absence of one: it is stored as
|
|
4801
|
+
* {@link creditExpiryNone} so the account is not read again on every pass.
|
|
4659
4802
|
*/
|
|
4660
4803
|
noteCredits(accountId, balance, nearestExpiryMs) {
|
|
4661
4804
|
if (!Number.isFinite(balance)) return;
|
|
4662
4805
|
if (!this.accounts.some((account) => account.id === accountId)) return;
|
|
4663
4806
|
this.creditBalances.set(accountId, balance);
|
|
4807
|
+
this.noteExpiryReading(accountId, nearestExpiryMs);
|
|
4808
|
+
}
|
|
4809
|
+
/**
|
|
4810
|
+
* Record ONLY the deadline, never the balance.
|
|
4811
|
+
*
|
|
4812
|
+
* The scan-triggered warm exists to fill `expiry` mode's sort key. Writing the
|
|
4813
|
+
* balance as a side effect would change what the reserve floor decides — an
|
|
4814
|
+
* account could be pulled out of rotation by a background read the user never
|
|
4815
|
+
* asked for, which is a behaviour change outside this fix's scope (S7 in
|
|
4816
|
+
* `EXPIRY-ADVERSARIAL-20261111.md`; the reserve's own cold-start hole is V4,
|
|
4817
|
+
* fixed separately).
|
|
4818
|
+
*/
|
|
4819
|
+
noteExpiryOnly(accountId, nearestExpiryMs) {
|
|
4820
|
+
if (!this.accounts.some((account) => account.id === accountId)) return;
|
|
4821
|
+
this.noteExpiryReading(accountId, nearestExpiryMs);
|
|
4822
|
+
}
|
|
4823
|
+
/**
|
|
4824
|
+
* The three-state writer both entry points funnel through.
|
|
4825
|
+
*
|
|
4826
|
+
* One place, so the invariant "a finished reading always leaves a state" can be
|
|
4827
|
+
* read off a single function: either a deadline is stored, or the account joins
|
|
4828
|
+
* `creditExpiryNone`. Nothing here deletes the read stamp — that is what makes
|
|
4829
|
+
* "read, found nothing" distinguishable from "never read".
|
|
4830
|
+
*/
|
|
4831
|
+
noteExpiryReading(accountId, nearestExpiryMs) {
|
|
4832
|
+
this.creditExpiryReadAt.set(accountId, Date.now());
|
|
4664
4833
|
if (nearestExpiryMs === void 0 || !Number.isFinite(nearestExpiryMs)) {
|
|
4665
4834
|
this.creditExpiry.delete(accountId);
|
|
4835
|
+
this.creditExpiryNone.add(accountId);
|
|
4666
4836
|
return;
|
|
4667
4837
|
}
|
|
4838
|
+
this.creditExpiryNone.delete(accountId);
|
|
4668
4839
|
this.creditExpiry.set(accountId, nearestExpiryMs);
|
|
4669
4840
|
}
|
|
4670
4841
|
/** Nearest one-off pack expiry for one account, or undefined when none known. */
|
|
4671
4842
|
creditExpiryOf(accountId) {
|
|
4672
4843
|
return this.creditExpiry.get(accountId);
|
|
4673
4844
|
}
|
|
4845
|
+
/**
|
|
4846
|
+
* The full three-state reading for one account, including staleness.
|
|
4847
|
+
*
|
|
4848
|
+
* `stale` is evaluated against {@link EXPIRY_READING_TTL_MS} here rather than
|
|
4849
|
+
* baked into the stored value, so the TTL stays a constant of the policy and
|
|
4850
|
+
* not of the data.
|
|
4851
|
+
*
|
|
4852
|
+
* Only a real deadline can go stale. "We never asked" is not a reading, and
|
|
4853
|
+
* "nothing here has a deadline" does not become less true with age: a monthly
|
|
4854
|
+
* pack does not grow an expiry date by waiting. Keeping `none` permanently
|
|
4855
|
+
* valid is what makes the S1 loop impossible — an account that answered once
|
|
4856
|
+
* is never read again by the expiry machinery, so there is no predicate that
|
|
4857
|
+
* can stay true forever and re-read it on every pass. If such an account does
|
|
4858
|
+
* gain a one-off pack later, the card refresh (which writes through
|
|
4859
|
+
* `noteCredits` on every poll) is what notices.
|
|
4860
|
+
*/
|
|
4861
|
+
expiryReadingOf(accountId, now = Date.now()) {
|
|
4862
|
+
const at = this.creditExpiry.get(accountId);
|
|
4863
|
+
const readAtMs = this.creditExpiryReadAt.get(accountId);
|
|
4864
|
+
if (readAtMs === void 0) return {
|
|
4865
|
+
state: "unread",
|
|
4866
|
+
stale: false
|
|
4867
|
+
};
|
|
4868
|
+
if (at !== void 0) return {
|
|
4869
|
+
state: "at",
|
|
4870
|
+
at,
|
|
4871
|
+
readAtMs,
|
|
4872
|
+
stale: now - readAtMs > this.expiryReadingTtlMs
|
|
4873
|
+
};
|
|
4874
|
+
if (this.creditExpiryNone.has(accountId)) return {
|
|
4875
|
+
state: "none",
|
|
4876
|
+
readAtMs,
|
|
4877
|
+
stale: false
|
|
4878
|
+
};
|
|
4879
|
+
return {
|
|
4880
|
+
state: "unread",
|
|
4881
|
+
stale: false
|
|
4882
|
+
};
|
|
4883
|
+
}
|
|
4674
4884
|
/** Last known balance for one account, or undefined when never read. */
|
|
4675
4885
|
creditsOf(accountId) {
|
|
4676
4886
|
return this.creditBalances.get(accountId);
|
|
@@ -10910,6 +11120,32 @@ function modelsEndpoint(provider) {
|
|
|
10910
11120
|
function hasModelsListing(provider) {
|
|
10911
11121
|
return typeof provider.modelsUrl === "string" && provider.modelsUrl.trim() !== "";
|
|
10912
11122
|
}
|
|
11123
|
+
// src/member-id.ts
|
|
11124
|
+
/** A login channel member has a colon before any slash in its model id. */
|
|
11125
|
+
function channelMemberOf(id) {
|
|
11126
|
+
const colon = id.indexOf(":");
|
|
11127
|
+
if (colon <= 0) return void 0;
|
|
11128
|
+
const channel = id.slice(0, colon);
|
|
11129
|
+
const model = id.slice(colon + 1);
|
|
11130
|
+
if (!/^[A-Za-z0-9_-]+$/u.test(channel) || model === "" || model.startsWith("//")) return void 0;
|
|
11131
|
+
return {
|
|
11132
|
+
channel,
|
|
11133
|
+
model: id
|
|
11134
|
+
};
|
|
11135
|
+
}
|
|
11136
|
+
/** Remove repeated legacy slash prefixes while preserving canonical colon IDs. */
|
|
11137
|
+
function memberForOwner(owner, model) {
|
|
11138
|
+
if (owner === "workbuddy") return model;
|
|
11139
|
+
while (model.startsWith(`${owner}/`)) model = model.slice(owner.length + 1);
|
|
11140
|
+
while (model.startsWith(`${owner}:${owner}:`)) model = model.slice(owner.length + 1);
|
|
11141
|
+
return model;
|
|
11142
|
+
}
|
|
11143
|
+
/** Flatten one editor member; canonical channel IDs are already complete. */
|
|
11144
|
+
function flattenMember(owner, model) {
|
|
11145
|
+
const value = memberForOwner(owner, model);
|
|
11146
|
+
if (owner === "workbuddy" || channelMemberOf(value)?.channel === owner) return value;
|
|
11147
|
+
return `${owner}/${value}`;
|
|
11148
|
+
}
|
|
10913
11149
|
// src/reasoning.ts
|
|
10914
11150
|
/** A chain's controls are routing intent; each member resolves to its own ladder. */
|
|
10915
11151
|
const CHAIN_REASONING_EFFORTS = [
|
|
@@ -10952,8 +11188,6 @@ const COMBO_PREFIX = "combo:";
|
|
|
10952
11188
|
const COMBO_CHANNEL = "combo";
|
|
10953
11189
|
/** Chain strategies. Anything else on disk falls back to `fallback`. */
|
|
10954
11190
|
const COMBO_STRATEGIES = ["fallback", "round-robin"];
|
|
10955
|
-
/** The owner id the pool lane uses in a platform group. */
|
|
10956
|
-
const POOL_OWNER = "workbuddy";
|
|
10957
11191
|
/**
|
|
10958
11192
|
* Flatten platform groups into the member ids the router walks.
|
|
10959
11193
|
*
|
|
@@ -10975,7 +11209,7 @@ function flattenPlatforms(platforms) {
|
|
|
10975
11209
|
for (const raw of platform.models) {
|
|
10976
11210
|
const model = text$6(raw);
|
|
10977
11211
|
if (model === "" || isComboId(model)) continue;
|
|
10978
|
-
const id = owner
|
|
11212
|
+
const id = flattenMember(owner, model);
|
|
10979
11213
|
if (seen.has(id)) continue;
|
|
10980
11214
|
seen.add(id);
|
|
10981
11215
|
out.push(id);
|
|
@@ -10997,9 +11231,10 @@ function splitPlatforms(models) {
|
|
|
10997
11231
|
for (const raw of models) {
|
|
10998
11232
|
const id = text$6(raw);
|
|
10999
11233
|
if (id === "") continue;
|
|
11000
|
-
const
|
|
11001
|
-
const
|
|
11002
|
-
const
|
|
11234
|
+
const channel = channelMemberOf(id);
|
|
11235
|
+
const parsed = channel === void 0 ? parseProviderModelId(id) : null;
|
|
11236
|
+
const owner = channel?.channel ?? (parsed === null ? "workbuddy" : parsed.providerId);
|
|
11237
|
+
const model = channel?.model ?? (parsed === null ? id : parsed.modelId);
|
|
11003
11238
|
let bucket = groups.get(owner);
|
|
11004
11239
|
if (bucket === void 0) {
|
|
11005
11240
|
bucket = [];
|
|
@@ -15087,17 +15322,32 @@ function withSessionQuotaHint(error, retryAfterMs) {
|
|
|
15087
15322
|
* and no explanation of which of its four fingerprint facts was wrong. That
|
|
15088
15323
|
* reaches the caller as a bare `client` failure, and a bare 4xx is what the
|
|
15089
15324
|
* host then renders in its own words: the user in #96 saw "当前请求的额度已用尽"
|
|
15090
|
-
* for a request that had never been billed.
|
|
15091
|
-
*
|
|
15092
|
-
*
|
|
15325
|
+
* for a request that had never been billed.
|
|
15326
|
+
*
|
|
15327
|
+
* ## The premise changed (verified 2026-11-12)
|
|
15328
|
+
*
|
|
15329
|
+
* This used to say "the fingerprint moved, update the plugin". It no longer
|
|
15330
|
+
* does, because a raw call now answers:
|
|
15093
15331
|
*
|
|
15094
|
-
*
|
|
15095
|
-
*
|
|
15096
|
-
*
|
|
15097
|
-
*
|
|
15332
|
+
* ```
|
|
15333
|
+
* {"type":"error","error":{"type":"FreeUsageLimitError",
|
|
15334
|
+
* "message":"Free usage limit reached. Free models work in OpenCode
|
|
15335
|
+
* (https://opencode.ai); subscribe to OpenCode Go to keep going…"}}
|
|
15336
|
+
* ```
|
|
15098
15337
|
*
|
|
15099
|
-
*
|
|
15100
|
-
*
|
|
15338
|
+
* That is not a fingerprint rejection and not a per-conversation budget: the
|
|
15339
|
+
* upstream has moved free models behind the OpenCode client itself. No header,
|
|
15340
|
+
* UA or path change reaches it, which is why #96 could not be fixed by
|
|
15341
|
+
* matching the gate more exactly — the gate is gone, replaced by an account
|
|
15342
|
+
* metering that a third-party client cannot enter.
|
|
15343
|
+
*
|
|
15344
|
+
* So the message names the real situation FIRST and stops promising that a
|
|
15345
|
+
* plugin update will help. `FreeUsageLimitError` is called out by name because
|
|
15346
|
+
* it is the specific shape of "this lane is closed to you", and telling the
|
|
15347
|
+
* user to wait or retry would spend their time on something that cannot work.
|
|
15348
|
+
*
|
|
15349
|
+
* A 429 keeps its own hint ({@link withSessionQuotaHint}). The distinction is
|
|
15350
|
+
* worth keeping: 429 is a budget that resets, 403 is a door that closed.
|
|
15101
15351
|
*/
|
|
15102
15352
|
function withFreeTierHint(status, refusal, retryAfterMs) {
|
|
15103
15353
|
const base = classifyUpstream(status, refusal, retryAfterMs, "");
|
|
@@ -15105,7 +15355,14 @@ function withFreeTierHint(status, refusal, retryAfterMs) {
|
|
|
15105
15355
|
const separator = base.message.indexOf(": ");
|
|
15106
15356
|
const detail = separator === -1 ? "" : base.message.slice(separator + 2);
|
|
15107
15357
|
const kept = detail === "" ? "" : ` (provider said: ${detail})`;
|
|
15108
|
-
|
|
15358
|
+
/**
|
|
15359
|
+
* `FreeUsageLimitError` means the upstream has closed this lane to non-client
|
|
15360
|
+
* traffic. Distinguished from a generic refusal so the advice can be true:
|
|
15361
|
+
* updating the plugin will not help, and only a real OpenCode client (or a
|
|
15362
|
+
* subscription) can.
|
|
15363
|
+
*/
|
|
15364
|
+
const closed = /FreeUsageLimitError|Free usage limit reached/iu.test(refusal);
|
|
15365
|
+
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 heybash-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);
|
|
15109
15366
|
}
|
|
15110
15367
|
/**
|
|
15111
15368
|
* POST one streaming turn and hand back chat-shaped deltas.
|
|
@@ -16265,6 +16522,22 @@ const EVENT_CHAIN_BUILDERS = {
|
|
|
16265
16522
|
WorkBuddy_Valorant: true
|
|
16266
16523
|
};
|
|
16267
16524
|
const AUTOMATION_TICK_MS = 6e4;
|
|
16525
|
+
/**
|
|
16526
|
+
* How long after {@link WorkBuddyScheduler.start} the second kick runs.
|
|
16527
|
+
*
|
|
16528
|
+
* Long enough for the pool's first account scan to have produced credentials,
|
|
16529
|
+
* short enough that a user watching the card sees the jobs land right away.
|
|
16530
|
+
*/
|
|
16531
|
+
const AUTOMATION_START_SETTLE_MS = 5e3;
|
|
16532
|
+
/**
|
|
16533
|
+
* How long after {@link WorkBuddyScheduler.start} an extra startup pass may run.
|
|
16534
|
+
* This pass never consumes a future scheduled slot.
|
|
16535
|
+
*
|
|
16536
|
+
* Long enough to cover a slow first account scan plus the six jobs running one
|
|
16537
|
+
* after another, short enough that an app left open all day resumes its normal
|
|
16538
|
+
* schedule well before the next configured hour.
|
|
16539
|
+
*/
|
|
16540
|
+
const AUTOMATION_STARTUP_CATCHUP_MS = 12e4;
|
|
16268
16541
|
/** The jobs in the order a tick runs them: report before tasks, always. */
|
|
16269
16542
|
const AUTOMATION_JOB_KINDS = [
|
|
16270
16543
|
"checkin",
|
|
@@ -16461,6 +16734,17 @@ var WorkBuddyScheduler = class {
|
|
|
16461
16734
|
travelHours;
|
|
16462
16735
|
compensationHours;
|
|
16463
16736
|
timer;
|
|
16737
|
+
/** The one-shot kick scheduled just after `start`; cleared by `stop`. */
|
|
16738
|
+
settleTimer;
|
|
16739
|
+
/**
|
|
16740
|
+
* Deadline for the start-of-day window described in {@link dueSlot}.
|
|
16741
|
+
*
|
|
16742
|
+
* Zero until {@link start} sets it, so a manual `tick` before the loop starts
|
|
16743
|
+
* keeps the original "only past hours" behaviour.
|
|
16744
|
+
*/
|
|
16745
|
+
startupCatchUpUntilMs = 0;
|
|
16746
|
+
/** A startup pass is extra work; it never spends a future scheduled slot. */
|
|
16747
|
+
startupCompleted = /* @__PURE__ */ new Set();
|
|
16464
16748
|
running = false;
|
|
16465
16749
|
/** Guards against a slow run overlapping the next tick. */
|
|
16466
16750
|
busy = false;
|
|
@@ -16590,6 +16874,29 @@ var WorkBuddyScheduler = class {
|
|
|
16590
16874
|
if (this.timer !== void 0) return;
|
|
16591
16875
|
this.stopped = false;
|
|
16592
16876
|
this.running = true;
|
|
16877
|
+
/**
|
|
16878
|
+
* Launching DSH is itself a "run today's jobs" signal.
|
|
16879
|
+
*
|
|
16880
|
+
* `setInterval` alone delays the first pass by a whole tick, so an app
|
|
16881
|
+
* started at 17:57 ran every catch-up job at 17:58 and the card showed all
|
|
16882
|
+
* six stamped on the same minute — indistinguishable from "nothing happened
|
|
16883
|
+
* until I moved". Kicking the loop now, and once more shortly after, makes
|
|
16884
|
+
* "I started DSH" and "the automation started" the same moment.
|
|
16885
|
+
*
|
|
16886
|
+
* During this window, unrun jobs receive one extra startup pass. Past due
|
|
16887
|
+
* slots are consumed as normal; future slots remain scheduled.
|
|
16888
|
+
*
|
|
16889
|
+
* Both kicks are cheap no-ops when the pool has no accounts yet or the day
|
|
16890
|
+
* is already done: `tick` returns early on an empty pool, and `dueSlot`
|
|
16891
|
+
* finds nothing left to consume.
|
|
16892
|
+
*/
|
|
16893
|
+
this.startupCompleted.clear();
|
|
16894
|
+
this.startupCatchUpUntilMs = this.now().getTime() + AUTOMATION_STARTUP_CATCHUP_MS;
|
|
16895
|
+
this.tick();
|
|
16896
|
+
this.settleTimer = setTimeout(() => {
|
|
16897
|
+
this.tick();
|
|
16898
|
+
}, AUTOMATION_START_SETTLE_MS);
|
|
16899
|
+
this.settleTimer.unref?.();
|
|
16593
16900
|
this.timer = setInterval(() => {
|
|
16594
16901
|
this.tick();
|
|
16595
16902
|
}, AUTOMATION_TICK_MS);
|
|
@@ -16599,6 +16906,10 @@ var WorkBuddyScheduler = class {
|
|
|
16599
16906
|
stop() {
|
|
16600
16907
|
this.stopped = true;
|
|
16601
16908
|
this.running = false;
|
|
16909
|
+
if (this.settleTimer !== void 0) {
|
|
16910
|
+
clearTimeout(this.settleTimer);
|
|
16911
|
+
this.settleTimer = void 0;
|
|
16912
|
+
}
|
|
16602
16913
|
if (this.timer !== void 0) {
|
|
16603
16914
|
clearInterval(this.timer);
|
|
16604
16915
|
this.timer = void 0;
|
|
@@ -16730,6 +17041,8 @@ var WorkBuddyScheduler = class {
|
|
|
16730
17041
|
* PASSED and its slot is still unconsumed, so a laptop that slept through
|
|
16731
17042
|
* 10:00 still runs the job when it wakes, on the same day.
|
|
16732
17043
|
*
|
|
17044
|
+
* Startup runs are handled separately in tick and do not spend a future slot.
|
|
17045
|
+
*
|
|
16733
17046
|
* The EARLIEST unconsumed candidate wins, which is what keeps a two-hour job
|
|
16734
17047
|
* (`travelHours: [9, 21]`) whole: consuming the earliest due slot leaves the
|
|
16735
17048
|
* later one for its own hour.
|
|
@@ -16761,6 +17074,19 @@ var WorkBuddyScheduler = class {
|
|
|
16761
17074
|
}
|
|
16762
17075
|
async tick() {
|
|
16763
17076
|
if (!this.enabled || this.stopped || this.busy) return;
|
|
17077
|
+
/**
|
|
17078
|
+
* Never spend a slot on an empty pool.
|
|
17079
|
+
*
|
|
17080
|
+
* The kick {@link start} fires runs within milliseconds of load, which in
|
|
17081
|
+
* some launches lands BEFORE the pool's first credential scan (measured: all
|
|
17082
|
+
* six jobs reported "0 accounts ok" while the card already listed two
|
|
17083
|
+
* accounts). `runJob` treats "0 eligible accounts" as a successful pass, so
|
|
17084
|
+
* the slot was marked consumed and the day's jobs never ran again — the
|
|
17085
|
+
* opposite of what the kick is for. Returning before the ledger is touched
|
|
17086
|
+
* leaves the slot unconsumed, so the settle kick and the regular timer pick
|
|
17087
|
+
* the work up as soon as the pool is ready.
|
|
17088
|
+
*/
|
|
17089
|
+
if (this.pool.list().length === 0) return;
|
|
16764
17090
|
this.busy = true;
|
|
16765
17091
|
try {
|
|
16766
17092
|
const now = this.now();
|
|
@@ -16770,8 +17096,9 @@ var WorkBuddyScheduler = class {
|
|
|
16770
17096
|
if (this.stopped) return;
|
|
16771
17097
|
if (this.states[kind].lastFiredHour === slot) continue;
|
|
16772
17098
|
const consumed = this.dueSlot(kind, now);
|
|
16773
|
-
|
|
16774
|
-
|
|
17099
|
+
const startup = consumed === void 0 && now.getTime() <= this.startupCatchUpUntilMs && !this.startupCompleted.has(kind);
|
|
17100
|
+
if (consumed === void 0 && !startup) continue;
|
|
17101
|
+
if (await this.runJob(kind, today, consumed, startup)) this.startupCompleted.add(kind);
|
|
16775
17102
|
}
|
|
16776
17103
|
} catch (error) {
|
|
16777
17104
|
this.logger.warn?.("heybash-xdpool automation tick failed:", error);
|
|
@@ -16883,7 +17210,7 @@ var WorkBuddyScheduler = class {
|
|
|
16883
17210
|
* while claiming wants the whole pool to have been lit up first. Splitting
|
|
16884
17211
|
* them costs one shared wait instead of one wait per account.
|
|
16885
17212
|
*/
|
|
16886
|
-
async runJob(kind, today, consumedSlot) {
|
|
17213
|
+
async runJob(kind, today, consumedSlot, startup = false) {
|
|
16887
17214
|
const accountWord = kind === "report" ? "report" : kind;
|
|
16888
17215
|
let ok = 0;
|
|
16889
17216
|
let failed = 0;
|
|
@@ -16907,6 +17234,7 @@ var WorkBuddyScheduler = class {
|
|
|
16907
17234
|
this.logger.warn?.("automation: could not probe benched accounts:", error);
|
|
16908
17235
|
}
|
|
16909
17236
|
const accounts = this.accountsInOrder(kind);
|
|
17237
|
+
if (accounts.length === 0 || this.stopped) return false;
|
|
16910
17238
|
if (kind === "tasks") await this.sendEventChains(accounts);
|
|
16911
17239
|
for (let index = 0; index < accounts.length; index++) {
|
|
16912
17240
|
if (this.stopped) break;
|
|
@@ -16987,7 +17315,7 @@ var WorkBuddyScheduler = class {
|
|
|
16987
17315
|
}
|
|
16988
17316
|
const state = this.states[kind];
|
|
16989
17317
|
if (consumedSlot !== void 0) this.consumeSlot(kind, consumedSlot);
|
|
16990
|
-
state.lastFiredHour = slotKey(this.now());
|
|
17318
|
+
if (!startup) state.lastFiredHour = slotKey(this.now());
|
|
16991
17319
|
state.lastRunDate = today;
|
|
16992
17320
|
state.lastRunAtMs = this.now().getTime();
|
|
16993
17321
|
state.ok = ok;
|
|
@@ -17002,6 +17330,7 @@ var WorkBuddyScheduler = class {
|
|
|
17002
17330
|
else state.progress = progressNote;
|
|
17003
17331
|
this.logger.info?.(`automation ${accountWord}: ${state.message}`);
|
|
17004
17332
|
if (kind === "tasks" || kind === "checkin" || kind === "streak" || kind === "travel" || kind === "compensation") await this.flushEarnings();
|
|
17333
|
+
return true;
|
|
17005
17334
|
}
|
|
17006
17335
|
/** Compose the one-line summary shown on the card. */
|
|
17007
17336
|
summarise(kind, ok, failed, claimed, credit, energy) {
|
|
@@ -19311,6 +19640,217 @@ function paidAlternativeFor(model, models) {
|
|
|
19311
19640
|
if (model.multiplier !== 0) return void 0;
|
|
19312
19641
|
return paidSiblingOf(model, models);
|
|
19313
19642
|
}
|
|
19643
|
+
// src/non-streaming.ts
|
|
19644
|
+
/**
|
|
19645
|
+
* Reassemble a streamed turn into one `chat.completion` document.
|
|
19646
|
+
*
|
|
19647
|
+
* The pool lane (and every other lane that buffers before answering) asks the
|
|
19648
|
+
* upstream for SSE and forwards it; it cannot ask for JSON because
|
|
19649
|
+
* `prepareChatBody` forces streaming. A caller that sent `stream: false`
|
|
19650
|
+
* therefore used to receive `text/event-stream` anyway, and an OpenAI client
|
|
19651
|
+
* parsing that body as JSON failed with `Unexpected token 'd'`.
|
|
19652
|
+
*
|
|
19653
|
+
* The channel lane already honours the flag (see `serveChannelCompletion`). This
|
|
19654
|
+
* module gives the other lanes the same behaviour without touching their wire
|
|
19655
|
+
* contract when the caller did NOT ask for it: `wantsNonStreaming` is true only
|
|
19656
|
+
* for an explicit `stream: false`, so an absent flag keeps today's SSE reply.
|
|
19657
|
+
*
|
|
19658
|
+
* @module dsh-xdpool/non-streaming
|
|
19659
|
+
*/
|
|
19660
|
+
/**
|
|
19661
|
+
* True only when the caller asked for JSON by saying so.
|
|
19662
|
+
*
|
|
19663
|
+
* `stream` absent must stay streaming: the Harness omits the flag and reads
|
|
19664
|
+
* SSE, and a missing field silently means "false" to plenty of JSON parsers —
|
|
19665
|
+
* honouring that reading would break every existing client.
|
|
19666
|
+
*/
|
|
19667
|
+
function wantsNonStreaming(raw) {
|
|
19668
|
+
let body;
|
|
19669
|
+
try {
|
|
19670
|
+
body = JSON.parse(raw);
|
|
19671
|
+
} catch {
|
|
19672
|
+
return false;
|
|
19673
|
+
}
|
|
19674
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
|
|
19675
|
+
return body["stream"] === false;
|
|
19676
|
+
}
|
|
19677
|
+
function createTurnAccumulator(modelId) {
|
|
19678
|
+
return {
|
|
19679
|
+
id: `chatcmpl-xdpool-${randomBytes(6).toString("base64url")}`,
|
|
19680
|
+
created: Math.floor(Date.now() / 1e3),
|
|
19681
|
+
model: modelId ?? "",
|
|
19682
|
+
text: "",
|
|
19683
|
+
reasoning: "",
|
|
19684
|
+
toolCalls: [],
|
|
19685
|
+
usage: void 0,
|
|
19686
|
+
rawUsage: void 0,
|
|
19687
|
+
finish: "stop"
|
|
19688
|
+
};
|
|
19689
|
+
}
|
|
19690
|
+
/**
|
|
19691
|
+
* Merge one tool-call fragment into its slot.
|
|
19692
|
+
*
|
|
19693
|
+
* The upstream streams a call as an opening fragment carrying `name` and then
|
|
19694
|
+
* argument deltas that do NOT: a plain spread would erase the name on the
|
|
19695
|
+
* second fragment and leave the caller with `tool_calls[0].function.name ===
|
|
19696
|
+
* undefined`. An empty or missing name therefore means "no opinion here", never
|
|
19697
|
+
* "clear what you have".
|
|
19698
|
+
*/
|
|
19699
|
+
function mergeTurnToolCall(existing, fragment) {
|
|
19700
|
+
const before = existing["function"] ?? {};
|
|
19701
|
+
const next = fragment["function"] ?? {};
|
|
19702
|
+
const name = typeof next["name"] === "string" && next["name"] !== "" ? next["name"] : before["name"];
|
|
19703
|
+
const merged = {
|
|
19704
|
+
...existing,
|
|
19705
|
+
...fragment,
|
|
19706
|
+
function: {
|
|
19707
|
+
...before,
|
|
19708
|
+
...next,
|
|
19709
|
+
...name === void 0 ? {} : { name },
|
|
19710
|
+
arguments: `${String(before["arguments"] ?? "")}${String(next["arguments"] ?? "")}`
|
|
19711
|
+
}
|
|
19712
|
+
};
|
|
19713
|
+
if (typeof fragment["id"] === "string" && fragment["id"] !== "") merged["id"] = fragment["id"];
|
|
19714
|
+
else if (typeof existing["id"] === "string") merged["id"] = existing["id"];
|
|
19715
|
+
return merged;
|
|
19716
|
+
}
|
|
19717
|
+
/** Merge one delta/message object (content, reasoning, tool calls) into the turn. */
|
|
19718
|
+
function absorbDelta(turn, delta) {
|
|
19719
|
+
if (typeof delta["content"] === "string") turn.text += delta["content"];
|
|
19720
|
+
const reasoning = delta["reasoning_content"] ?? delta["reasoning"];
|
|
19721
|
+
if (typeof reasoning === "string") turn.reasoning += reasoning;
|
|
19722
|
+
const calls = delta["tool_calls"];
|
|
19723
|
+
if (!Array.isArray(calls)) return;
|
|
19724
|
+
for (const call of calls) {
|
|
19725
|
+
if (typeof call !== "object" || call === null) continue;
|
|
19726
|
+
const fragment = call;
|
|
19727
|
+
const index = Number(fragment["index"] ?? turn.toolCalls.length);
|
|
19728
|
+
const slot = Number.isInteger(index) && index >= 0 ? index : turn.toolCalls.length;
|
|
19729
|
+
turn.toolCalls[slot] = mergeTurnToolCall(turn.toolCalls[slot] ?? {}, fragment);
|
|
19730
|
+
}
|
|
19731
|
+
}
|
|
19732
|
+
/**
|
|
19733
|
+
* Fold one SSE `data:` payload into the accumulator.
|
|
19734
|
+
*
|
|
19735
|
+
* Reads the same three shapes the forwarding path already tolerates upstream:
|
|
19736
|
+
* OpenAI `choices[].delta`, a non-streaming `choices[].message`, and the
|
|
19737
|
+
* gateway's `data.content` wrapper.
|
|
19738
|
+
*/
|
|
19739
|
+
function foldPayload(turn, payload) {
|
|
19740
|
+
if (payload === "" || payload === "[DONE]") return;
|
|
19741
|
+
let parsed;
|
|
19742
|
+
try {
|
|
19743
|
+
parsed = JSON.parse(payload);
|
|
19744
|
+
} catch {
|
|
19745
|
+
return;
|
|
19746
|
+
}
|
|
19747
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
|
|
19748
|
+
const frame = parsed;
|
|
19749
|
+
const usage = parseUsage(frame["usage"]);
|
|
19750
|
+
if (usage !== void 0) {
|
|
19751
|
+
turn.usage = usage;
|
|
19752
|
+
turn.rawUsage = frame["usage"];
|
|
19753
|
+
}
|
|
19754
|
+
const choices = frame["choices"];
|
|
19755
|
+
if (Array.isArray(choices) && choices.length > 0) {
|
|
19756
|
+
const choice = choices[0];
|
|
19757
|
+
if (typeof choice === "object" && choice !== null) {
|
|
19758
|
+
const entry = choice;
|
|
19759
|
+
const delta = entry["delta"];
|
|
19760
|
+
if (typeof delta === "object" && delta !== null) absorbDelta(turn, delta);
|
|
19761
|
+
const message = entry["message"];
|
|
19762
|
+
if (typeof message === "object" && message !== null) absorbDelta(turn, message);
|
|
19763
|
+
const reason = entry["finish_reason"];
|
|
19764
|
+
if (typeof reason === "string" && reason !== "") turn.finish = reason;
|
|
19765
|
+
}
|
|
19766
|
+
}
|
|
19767
|
+
const wrapper = frame["data"];
|
|
19768
|
+
if (typeof wrapper === "object" && wrapper !== null) {
|
|
19769
|
+
const content = wrapper["content"];
|
|
19770
|
+
if (typeof content === "string") turn.text += content;
|
|
19771
|
+
const reason = wrapper["finish_reason"];
|
|
19772
|
+
if (typeof reason === "string" && reason !== "") turn.finish = reason;
|
|
19773
|
+
}
|
|
19774
|
+
}
|
|
19775
|
+
/** Spell the accumulated turn as one non-streaming `chat.completion` document. */
|
|
19776
|
+
function turnToCompletion(turn) {
|
|
19777
|
+
const calls = turn.toolCalls.filter((call) => call !== void 0);
|
|
19778
|
+
return {
|
|
19779
|
+
id: turn.id,
|
|
19780
|
+
object: "chat.completion",
|
|
19781
|
+
created: turn.created,
|
|
19782
|
+
model: turn.model,
|
|
19783
|
+
choices: [{
|
|
19784
|
+
index: 0,
|
|
19785
|
+
message: {
|
|
19786
|
+
role: "assistant",
|
|
19787
|
+
content: turn.text === "" && calls.length > 0 ? null : turn.text,
|
|
19788
|
+
...turn.reasoning === "" ? {} : { reasoning_content: turn.reasoning },
|
|
19789
|
+
...calls.length === 0 ? {} : { tool_calls: calls }
|
|
19790
|
+
},
|
|
19791
|
+
finish_reason: turn.finish
|
|
19792
|
+
}],
|
|
19793
|
+
...turn.rawUsage === void 0 ? {} : { usage: turn.rawUsage }
|
|
19794
|
+
};
|
|
19795
|
+
}
|
|
19796
|
+
/**
|
|
19797
|
+
* Split a growing text buffer into complete SSE `data:` payloads.
|
|
19798
|
+
*
|
|
19799
|
+
* A frame's own blank line is the only reliable boundary — JSON can contain
|
|
19800
|
+
* anything, but it cannot contain an unescaped newline — so nothing is parsed
|
|
19801
|
+
* out of a partial frame.
|
|
19802
|
+
*/
|
|
19803
|
+
function drainSsePayloads(buffer) {
|
|
19804
|
+
const payloads = [];
|
|
19805
|
+
let rest = buffer;
|
|
19806
|
+
for (;;) {
|
|
19807
|
+
const span = sseFrameSpan(rest);
|
|
19808
|
+
if (span === void 0) break;
|
|
19809
|
+
const frame = rest.subarray(0, span.contentEnd).toString("utf8");
|
|
19810
|
+
rest = rest.subarray(span.frameEnd);
|
|
19811
|
+
for (const line of frame.split(/\r?\n/u)) {
|
|
19812
|
+
const trimmed = line.trim();
|
|
19813
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
19814
|
+
payloads.push(trimmed.slice(5).trim());
|
|
19815
|
+
}
|
|
19816
|
+
}
|
|
19817
|
+
return {
|
|
19818
|
+
payloads,
|
|
19819
|
+
rest
|
|
19820
|
+
};
|
|
19821
|
+
}
|
|
19822
|
+
/**
|
|
19823
|
+
* Where one SSE frame ends inside a buffer.
|
|
19824
|
+
*
|
|
19825
|
+
* Both offsets come back because a frame's CONTENT ends before its SEPARATOR
|
|
19826
|
+
* does. This is the same rule `frameSpan` in `shim.ts` applies; it lives here
|
|
19827
|
+
* too so the reassembler does not have to reach into the shim's closure.
|
|
19828
|
+
*/
|
|
19829
|
+
function sseFrameSpan(buf) {
|
|
19830
|
+
const bare = buf.indexOf("\n\n");
|
|
19831
|
+
const crlf = buf.indexOf("\r\n\r\n");
|
|
19832
|
+
if (bare === -1 && crlf === -1) return void 0;
|
|
19833
|
+
if (crlf !== -1 && (bare === -1 || crlf < bare)) return {
|
|
19834
|
+
contentEnd: crlf,
|
|
19835
|
+
frameEnd: crlf + 4
|
|
19836
|
+
};
|
|
19837
|
+
return {
|
|
19838
|
+
contentEnd: bare,
|
|
19839
|
+
frameEnd: bare + 2
|
|
19840
|
+
};
|
|
19841
|
+
}
|
|
19842
|
+
/**
|
|
19843
|
+
* Fold a buffered lane's frames into the one document `stream: false` asked for.
|
|
19844
|
+
*
|
|
19845
|
+
* The buffering lanes (aggregate, free/co-paid extras, chain members) already
|
|
19846
|
+
* hold their whole answer before writing, so honouring the flag there costs one
|
|
19847
|
+
* pass and no wire change for streaming callers.
|
|
19848
|
+
*/
|
|
19849
|
+
function bufferedFramesToCompletion(frames, modelId) {
|
|
19850
|
+
const turn = createTurnAccumulator(modelId);
|
|
19851
|
+
for (const payload of frames) foldPayload(turn, payload);
|
|
19852
|
+
return turnToCompletion(turn);
|
|
19853
|
+
}
|
|
19314
19854
|
// src/channel-lane.ts
|
|
19315
19855
|
/**
|
|
19316
19856
|
* The channel lane: 扫码登录 vendors served through the host's own LLM seam.
|
|
@@ -19571,7 +20111,7 @@ function mapFinishReason(reason) {
|
|
|
19571
20111
|
return "stop";
|
|
19572
20112
|
}
|
|
19573
20113
|
/** Fold host chunks into OpenAI delta objects. */
|
|
19574
|
-
function toChannelEvent(chunk) {
|
|
20114
|
+
function toChannelEvent(chunk, toolIndex = 0) {
|
|
19575
20115
|
switch (chunk.type) {
|
|
19576
20116
|
case "text-delta": return {
|
|
19577
20117
|
kind: "delta",
|
|
@@ -19587,7 +20127,7 @@ function toChannelEvent(chunk) {
|
|
|
19587
20127
|
const fn = { arguments: String(chunk.argumentsDelta ?? "") };
|
|
19588
20128
|
if (name !== void 0 && name !== "") fn.name = name;
|
|
19589
20129
|
const call = {
|
|
19590
|
-
index:
|
|
20130
|
+
index: toolIndex,
|
|
19591
20131
|
function: fn
|
|
19592
20132
|
};
|
|
19593
20133
|
if (id !== "") call.id = id;
|
|
@@ -19643,12 +20183,20 @@ async function* runTurn(input) {
|
|
|
19643
20183
|
if (llm.resolveModelInfo !== void 0) selected = resolveMemberReasoningEffort(requested, (await llm.resolveModelInfo(channel, modelId, signal)).reasoning?.efforts.map((effort) => effort.id) ?? []) ?? "";
|
|
19644
20184
|
if (selected !== "") options.reasoningEffort = selected;
|
|
19645
20185
|
}
|
|
20186
|
+
const toolIndexes = /* @__PURE__ */ new Map();
|
|
19646
20187
|
for await (const chunk of llm.stream(options)) {
|
|
19647
20188
|
if (chunk.type === "finish" && typeof chunk.reason === "object" && chunk.reason !== null && chunk.reason.kind === "error") {
|
|
19648
20189
|
const failure = chunk.reason.failure;
|
|
19649
20190
|
throw new Error(typeof failure?.message === "string" ? failure.message : `channel ${channel} model request failed`);
|
|
19650
20191
|
}
|
|
19651
|
-
|
|
20192
|
+
let toolIndex = 0;
|
|
20193
|
+
if (chunk.type === "tool-call-delta") {
|
|
20194
|
+
const key = typeof chunk.index === "number" ? chunk.index : String(chunk.id ?? "");
|
|
20195
|
+
const existing = toolIndexes.get(key);
|
|
20196
|
+
toolIndex = existing ?? toolIndexes.size;
|
|
20197
|
+
if (existing === void 0) toolIndexes.set(key, toolIndex);
|
|
20198
|
+
}
|
|
20199
|
+
const event = toChannelEvent(chunk, toolIndex);
|
|
19652
20200
|
if (event !== void 0) yield event;
|
|
19653
20201
|
}
|
|
19654
20202
|
}
|
|
@@ -20079,6 +20627,10 @@ function createWorkBuddyShim(options) {
|
|
|
20079
20627
|
writeOpenAIError(res, KIND_STATUS[kind], `${target.lane}_${kind}`, message);
|
|
20080
20628
|
return;
|
|
20081
20629
|
}
|
|
20630
|
+
if (wantsNonStreaming(raw)) {
|
|
20631
|
+
writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
|
|
20632
|
+
return;
|
|
20633
|
+
}
|
|
20082
20634
|
res.writeHead(200, {
|
|
20083
20635
|
"Content-Type": "text/event-stream",
|
|
20084
20636
|
"Cache-Control": "no-cache",
|
|
@@ -20290,6 +20842,10 @@ function createWorkBuddyShim(options) {
|
|
|
20290
20842
|
writeOpenAIError(res, 500, "aggregate_internal", error instanceof Error ? error.message : String(error));
|
|
20291
20843
|
return;
|
|
20292
20844
|
}
|
|
20845
|
+
if (wantsNonStreaming(raw)) {
|
|
20846
|
+
writeJson$1(res, 200, bufferedFramesToCompletion(frames, modelId));
|
|
20847
|
+
return;
|
|
20848
|
+
}
|
|
20293
20849
|
res.writeHead(200, {
|
|
20294
20850
|
"Content-Type": "text/event-stream",
|
|
20295
20851
|
"Cache-Control": "no-cache",
|
|
@@ -20618,6 +21174,10 @@ function createWorkBuddyShim(options) {
|
|
|
20618
21174
|
noteSwitch(member.modelId, kind, last.status);
|
|
20619
21175
|
continue;
|
|
20620
21176
|
}
|
|
21177
|
+
if (wantsNonStreaming(raw)) {
|
|
21178
|
+
writeJson$1(res, 200, bufferedFramesToCompletion(hostFrames, member.modelId));
|
|
21179
|
+
return;
|
|
21180
|
+
}
|
|
20621
21181
|
res.writeHead(200, {
|
|
20622
21182
|
"Content-Type": "text/event-stream",
|
|
20623
21183
|
"Cache-Control": "no-cache",
|
|
@@ -20649,12 +21209,17 @@ function createWorkBuddyShim(options) {
|
|
|
20649
21209
|
const result = await client.chatStream(account.credential, prepared, memberSignal, conversationKey);
|
|
20650
21210
|
if (result.ok) {
|
|
20651
21211
|
const turnId = randomBytes(8).toString("hex");
|
|
20652
|
-
|
|
21212
|
+
const memberUsage = usageRecorder === void 0 ? void 0 : {
|
|
20653
21213
|
recorder: usageRecorder,
|
|
20654
21214
|
region: region ?? "cn",
|
|
20655
21215
|
model: member.modelId,
|
|
20656
21216
|
turnId
|
|
20657
|
-
}
|
|
21217
|
+
};
|
|
21218
|
+
if (wantsNonStreaming(raw)) {
|
|
21219
|
+
await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, memberUsage, member.modelId);
|
|
21220
|
+
return;
|
|
21221
|
+
}
|
|
21222
|
+
await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, memberUsage);
|
|
20658
21223
|
return;
|
|
20659
21224
|
}
|
|
20660
21225
|
last = {
|
|
@@ -20720,6 +21285,10 @@ function createWorkBuddyShim(options) {
|
|
|
20720
21285
|
continue;
|
|
20721
21286
|
}
|
|
20722
21287
|
if (switches.length > 0) logger?.info?.(`heybash-xdpool: chain ${row.id} served by ${member.modelId} after skipping ${String(switches.length)}/${String(members.length)}: ${switches.join("; ")}`);
|
|
21288
|
+
if (wantsNonStreaming(raw)) {
|
|
21289
|
+
writeJson$1(res, 200, bufferedFramesToCompletion(frames, member.modelId));
|
|
21290
|
+
return;
|
|
21291
|
+
}
|
|
20723
21292
|
res.writeHead(200, {
|
|
20724
21293
|
"Content-Type": "text/event-stream",
|
|
20725
21294
|
"Cache-Control": "no-cache",
|
|
@@ -20854,6 +21423,10 @@ function createWorkBuddyShim(options) {
|
|
|
20854
21423
|
tried.push(account.label);
|
|
20855
21424
|
const result = await client.chatStream(account.credential, prepared, controller.signal, conversationKey);
|
|
20856
21425
|
if (result.ok) {
|
|
21426
|
+
if (wantsNonStreaming(raw)) {
|
|
21427
|
+
await serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usageContext, modelId);
|
|
21428
|
+
return;
|
|
21429
|
+
}
|
|
20857
21430
|
await serveSuccessfulStream(res, account, result, logger, refreshBalance, pool, usageContext);
|
|
20858
21431
|
return;
|
|
20859
21432
|
}
|
|
@@ -20918,6 +21491,10 @@ function createWorkBuddyShim(options) {
|
|
|
20918
21491
|
})()
|
|
20919
21492
|
});
|
|
20920
21493
|
if (recovered.ok) {
|
|
21494
|
+
if (wantsNonStreaming(raw)) {
|
|
21495
|
+
await serveSuccessfulJson(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext, modelId);
|
|
21496
|
+
return;
|
|
21497
|
+
}
|
|
20921
21498
|
await serveSuccessfulStream(res, recovered.account, recovered.result, logger, refreshBalance, pool, usageContext);
|
|
20922
21499
|
return;
|
|
20923
21500
|
}
|
|
@@ -21000,6 +21577,7 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
|
|
|
21000
21577
|
logger?.info?.(`heybash-xdpool: served by ${account.label}`);
|
|
21001
21578
|
pool.noteServed(account.id);
|
|
21002
21579
|
refreshBalance(account);
|
|
21580
|
+
if (pool.expiryReadingOf(account.id).stale) pool.warmExpiryReadingFor(account.id);
|
|
21003
21581
|
res.writeHead(200, {
|
|
21004
21582
|
"Content-Type": "text/event-stream",
|
|
21005
21583
|
"Cache-Control": "no-cache",
|
|
@@ -21075,6 +21653,79 @@ async function serveSuccessfulStream(res, account, result, logger, refreshBalanc
|
|
|
21075
21653
|
body.pipe(strip).pipe(res);
|
|
21076
21654
|
}
|
|
21077
21655
|
/**
|
|
21656
|
+
* Answer one already-successful upstream stream as a single JSON document.
|
|
21657
|
+
*
|
|
21658
|
+
* The pool lane asks for SSE (`prepareChatBody` forces it), so the only way to
|
|
21659
|
+
* honour `stream: false` is to consume the whole body here and reassemble it.
|
|
21660
|
+
* Nothing is written until the body completes, which is also why a mid-flight
|
|
21661
|
+
* failure can still become a proper HTTP error instead of a 200 that ends in a
|
|
21662
|
+
* truncated answer.
|
|
21663
|
+
*
|
|
21664
|
+
* The bookkeeping deliberately mirrors `serveSuccessfulStream`: same
|
|
21665
|
+
* `noteServed`, same background balance refresh, same once-only usage filing —
|
|
21666
|
+
* a turn must not cost differently depending on how the caller asked to read it.
|
|
21667
|
+
*/
|
|
21668
|
+
async function serveSuccessfulJson(res, account, result, logger, refreshBalance, pool, usage, modelId) {
|
|
21669
|
+
logger?.info?.(`heybash-xdpool: served by ${account.label} (non-streaming)`);
|
|
21670
|
+
pool.noteServed(account.id);
|
|
21671
|
+
refreshBalance(account);
|
|
21672
|
+
const tracker = new StreamTracker(Date.now());
|
|
21673
|
+
const turn = createTurnAccumulator(modelId);
|
|
21674
|
+
let recorded = false;
|
|
21675
|
+
const finish = (ok) => {
|
|
21676
|
+
if (recorded) return;
|
|
21677
|
+
recorded = true;
|
|
21678
|
+
if (usage?.recorder === void 0) return;
|
|
21679
|
+
usage.recorder.record({
|
|
21680
|
+
channel: "workbuddy",
|
|
21681
|
+
region: usage.region,
|
|
21682
|
+
model: usage.model,
|
|
21683
|
+
account: account.label,
|
|
21684
|
+
turnId: usage.turnId,
|
|
21685
|
+
at: Date.now(),
|
|
21686
|
+
ok,
|
|
21687
|
+
...tracker.ttftMs === void 0 ? {} : { ttftMs: tracker.ttftMs },
|
|
21688
|
+
...tracker.decodeMs === void 0 ? {} : { decodeMs: tracker.decodeMs },
|
|
21689
|
+
...tracker.usage === void 0 ? {} : { usage: tracker.usage }
|
|
21690
|
+
});
|
|
21691
|
+
};
|
|
21692
|
+
/**
|
|
21693
|
+
* Explicitly `Buffer<ArrayBufferLike>`: `Buffer.alloc(0)` infers
|
|
21694
|
+
* `Buffer<ArrayBuffer>`, and `Buffer.concat` widens to `ArrayBufferLike`, so the
|
|
21695
|
+
* assignment back into `buffer` fails under strict lib types. Annotating the accumulator
|
|
21696
|
+
* once is clearer than casting at each of the two assignments.
|
|
21697
|
+
*/
|
|
21698
|
+
let buffer = Buffer.alloc(0);
|
|
21699
|
+
let failure;
|
|
21700
|
+
try {
|
|
21701
|
+
for await (const chunk of Readable.fromWeb(result.response.body)) {
|
|
21702
|
+
tracker.markFirstByte(Date.now());
|
|
21703
|
+
buffer = buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([buffer, chunk]);
|
|
21704
|
+
const drained = drainSsePayloads(buffer);
|
|
21705
|
+
buffer = drained.rest;
|
|
21706
|
+
for (const payload of drained.payloads) foldPayload(turn, payload);
|
|
21707
|
+
}
|
|
21708
|
+
if (buffer.length > 0) for (const line of buffer.toString("utf8").split(/\r?\n/u)) {
|
|
21709
|
+
const trimmed = line.trim();
|
|
21710
|
+
if (trimmed.startsWith("data:")) foldPayload(turn, trimmed.slice(5).trim());
|
|
21711
|
+
}
|
|
21712
|
+
tracker.finish(Date.now());
|
|
21713
|
+
if (turn.usage !== void 0) tracker.usage = turn.usage;
|
|
21714
|
+
} catch (error) {
|
|
21715
|
+
failure = error;
|
|
21716
|
+
logger?.warn("heybash-xdpool: non-streaming reassembly failed mid-flight", error);
|
|
21717
|
+
}
|
|
21718
|
+
if (failure !== void 0) {
|
|
21719
|
+
finish(false);
|
|
21720
|
+
if (!res.headersSent) writeOpenAIError(res, 502, "upstream_stream_error", `the upstream stream broke before the answer completed: ${failure instanceof Error ? failure.message : String(failure)}`);
|
|
21721
|
+
else if (res.writable) res.end();
|
|
21722
|
+
return;
|
|
21723
|
+
}
|
|
21724
|
+
finish(true);
|
|
21725
|
+
if (!res.headersSent) writeJson$1(res, 200, turnToCompletion(turn));
|
|
21726
|
+
else if (res.writable) res.end();
|
|
21727
|
+
}
|
|
21728
|
+
/**
|
|
21078
21729
|
* Compact an over-long conversation and retry it once.
|
|
21079
21730
|
*
|
|
21080
21731
|
* Strategy, in order:
|
|
@@ -22489,7 +23140,7 @@ function combosStatusOf(store, catalog, poolRows, hostRows = []) {
|
|
|
22489
23140
|
};
|
|
22490
23141
|
}),
|
|
22491
23142
|
...hostRows.map((row) => ({
|
|
22492
|
-
id:
|
|
23143
|
+
id: row.id,
|
|
22493
23144
|
name: row.name,
|
|
22494
23145
|
owner: row.channel,
|
|
22495
23146
|
usable: true,
|
|
@@ -22503,10 +23154,7 @@ function combosStatusOf(store, catalog, poolRows, hostRows = []) {
|
|
|
22503
23154
|
aggregate: providerRows,
|
|
22504
23155
|
host: hostRows
|
|
22505
23156
|
};
|
|
22506
|
-
const displayId = (id) =>
|
|
22507
|
-
const host = hostRows.find((row) => row.id === id);
|
|
22508
|
-
return host === void 0 ? id : `${host.channel}/${host.modelId}`;
|
|
22509
|
-
};
|
|
23157
|
+
const displayId = (id) => id;
|
|
22510
23158
|
return {
|
|
22511
23159
|
combos: chains.map((chain) => {
|
|
22512
23160
|
const resolved = buildComboCatalog([{
|