dsh-xdpool 2.6.5 → 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/CHANGELOG.md CHANGED
@@ -1,6 +1,42 @@
1
1
  # Changelog
2
2
  本项目的所有重要变更都会记录在此文件。
3
3
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
+ ## 2.6.6 — 免费线上游已关闭;国际版每日活跃;网关支持非流式
5
+
6
+ > 三处独立改动:一个必须如实说明的坏消息,两个来自社区的修复。
7
+
8
+ ### 免费模型线已被上游关闭(#96)
9
+
10
+ 实测一次裸调用,上游现在回答:
11
+
12
+ ```json
13
+ {"type":"error","error":{"type":"FreeUsageLimitError",
14
+ "message":"Free usage limit reached. Free models work in OpenCode
15
+ (https://opencode.ai); subscribe to OpenCode Go to keep going…"}}
16
+ ```
17
+
18
+ 这既不是指纹失配,也不是「按会话计额」——**上游把免费模型收进了自己的客户端**,第三方的 UA、请求头、路径怎么改都进不去。#96 的「从装上就没成功过」不是我们没修对门禁,而是那道门已经不在了。
19
+
20
+ 原来的提示让人去更新插件,那在门禁还是指纹的年代是对的,现在是一条死路。现在按名字识别 `FreeUsageLimitError`,直接说明这条路已关闭、给出可用的替代(换渠道,或订阅 OpenCode Go)。
21
+
22
+ ### 国际版账号恢复每日活跃上报(PR #138)
23
+
24
+ `scheduler.ts` 原先把 `report` / `streak` 限定为国内版,理由是国际版没有任务中心。这个前提不成立:
25
+
26
+ | 接口 | 国际版实测 |
27
+ |---|---|
28
+ | `POST /v2/report` | `200 {"code":0}` |
29
+ | `GET /activity/growth/streak` | `200`,字段形状与国内版一致 |
30
+ | `GET /activity/growth/tasks` | `200`,返回 5 条任务 |
31
+
32
+ 国际版的机制是:**每个被记录的活跃日,服务端次日凌晨发一个 30 积分的 `Bonus Pack`**,没有领取接口。一个请求就能点亮当天活跃(实测 heatmap 当天 score 从 0 变 2、`streak.days` 从 0 变 1),漏一天就真少 30 积分。
33
+
34
+ 顺带把「签到活动未开启」记为**跳过**而非失败,不再污染失败计数。
35
+
36
+ ### 网关支持 `stream: false`(PR #144)
37
+
38
+ 此前池车道与缓冲车道一律按流式处理,客户端发 `stream: false` 也只拿回 SSE。现在两条车道都按请求体决定,非流式请求返回一个完整 JSON 响应。
39
+
4
40
  ## 2.6.5 — 安装不再被判失败,积分面板不再空白
5
41
 
6
42
  > 五张 issue,三个独立根因。前两张是同一件事的两面:2.6.4 的 postinstall 会把**本来能用的安装**判成失败。
package/lib/bin.js CHANGED
@@ -1346,8 +1346,18 @@ var WorkBuddyUpstreamClient = class {
1346
1346
  if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
1347
1347
  return models;
1348
1348
  }
1349
- /** Read-only credits query, aggregated by package. Does not consume credits. */
1350
- async fetchCredits(credential) {
1349
+ /**
1350
+ * Read-only credits query, aggregated by package. Does not consume credits.
1351
+ *
1352
+ * `signal` is the caller's cancellation, merged with the built-in timeout
1353
+ * rather than replacing it: the pool's background warm must give up when the
1354
+ * host shuts down, and a caller that has already gone away must not leave a
1355
+ * 30 s request running. `AbortSignal.any` is already the repo's way of
1356
+ * combining these (see the pricing probe in the shim), and the timeout stays
1357
+ * in force so a signal-less caller keeps the old behaviour exactly.
1358
+ */
1359
+ async fetchCredits(credential, signal) {
1360
+ const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
1351
1361
  const now = /* @__PURE__ */ new Date();
1352
1362
  const fmt = (date) => {
1353
1363
  const p = (n) => n.toString().padStart(2, "0");
@@ -1364,7 +1374,7 @@ var WorkBuddyUpstreamClient = class {
1364
1374
  PackageEndTimeRangeBegin: fmt(now),
1365
1375
  PackageEndTimeRangeEnd: fmt(new Date(now.getTime() + 3185136e6))
1366
1376
  }),
1367
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1377
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
1368
1378
  });
1369
1379
  const envelope = await readEnvelope(response);
1370
1380
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
@@ -3546,6 +3556,13 @@ const EXHAUST_COOLDOWN_MS = 18e5;
3546
3556
  */
3547
3557
  const CREDENTIAL_DEAD_COOLDOWN_MS = 18e5;
3548
3558
  /**
3559
+ * Shortest gap between two attempts at the same account's deadline reading.
3560
+ *
3561
+ * Only failed attempts are actually throttled by this: a successful read stamps
3562
+ * the reading itself, so {@link EXPIRY_READING_TTL_MS} takes over from there.
3563
+ */
3564
+ const EXPIRY_WARM_RETRY_MS = 6e4;
3565
+ /**
3549
3566
  * Does this refresh failure prove the credential itself is dead?
3550
3567
  *
3551
3568
  * The upstream answers a revoked refresh token with `invalid_grant: Offline user
@@ -3574,6 +3591,7 @@ var WorkBuddyAccountPool = class {
3574
3591
  credentialDeadCooldownMs;
3575
3592
  client;
3576
3593
  refreshMarginMs;
3594
+ expiryReadingTtlMs;
3577
3595
  accounts = [];
3578
3596
  /**
3579
3597
  * Files the last scan could not read, with the reason.
@@ -3669,11 +3687,42 @@ var WorkBuddyAccountPool = class {
3669
3687
  * their own cycle and are therefore never urgent — which is why this is
3670
3688
  * written from the same `fetchCredits` reading that fills `creditBalances`.
3671
3689
  *
3672
- * An absent entry means "never probed, or nothing is about to expire". Both
3673
- * are the same thing to `expiry` mode: not urgent, so it sorts last.
3690
+ * A positive value is a deadline. The two other states are kept in
3691
+ * {@link creditExpiryNone} and {@link creditExpiryReadAt} rather than as a
3692
+ * missing key, because a missing key cannot tell "we never looked" from "we
3693
+ * looked and nothing has a deadline" — and only the first is worth reading
3694
+ * again. An account whose packs are all monthly reads as `none` forever, which
3695
+ * is exactly right: asking again cannot change the answer (S1).
3674
3696
  */
3675
3697
  creditExpiry = /* @__PURE__ */ new Map();
3676
3698
  /**
3699
+ * Accounts whose last reading found NO one-off deadline (all monthly packs, or
3700
+ * none at all). Written instead of deleting the key, so the account stops
3701
+ * being a candidate for re-reading.
3702
+ */
3703
+ creditExpiryNone = /* @__PURE__ */ new Set();
3704
+ /** When each account's deadline reading was taken, epoch ms. */
3705
+ creditExpiryReadAt = /* @__PURE__ */ new Map();
3706
+ /**
3707
+ * Accounts whose deadline reading is being fetched right now.
3708
+ *
3709
+ * Same de-duplication idea as {@link refreshInflight}, for the same reason: a
3710
+ * scan-triggered warm and a request-triggered top-up must not both spend a
3711
+ * billing round trip on the same account. A Set rather than a Map of promises
3712
+ * because no caller ever awaits the warm — the point is only that a second
3713
+ * pass skips it.
3714
+ */
3715
+ expiryWarmInflight = /* @__PURE__ */ new Set();
3716
+ /**
3717
+ * Last time the pool tried to warm an account's deadline reading, epoch ms.
3718
+ *
3719
+ * The TTL is the success gate, not a retry gate: a failed read writes nothing,
3720
+ * so without this a permanently failing billing endpoint would be hit on every
3721
+ * scan and every served request. One attempt per account per minute is cheap
3722
+ * and still recovers quickly from a transient failure.
3723
+ */
3724
+ expiryWarmAttemptAt = /* @__PURE__ */ new Map();
3725
+ /**
3677
3726
  * Last time each account served a request, epoch ms. Drives the idle term
3678
3727
  * of the priority-mode weighting below: an account that just served loses to
3679
3728
  * one that has been idle, so a small pool stops hammering a single account.
@@ -3718,6 +3767,7 @@ var WorkBuddyAccountPool = class {
3718
3767
  this.credentialDeadCooldownMs = options.credentialDeadCooldownMs ?? CREDENTIAL_DEAD_COOLDOWN_MS;
3719
3768
  this.client = options.client;
3720
3769
  this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
3770
+ this.expiryReadingTtlMs = options.expiryReadingTtlMs ?? 36e5;
3721
3771
  this.distribution = options.distribution ?? "priority";
3722
3772
  this.persistent = options.persistent ?? false;
3723
3773
  this.storePath = accountStorePath();
@@ -3932,6 +3982,7 @@ var WorkBuddyAccountPool = class {
3932
3982
  ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
3933
3983
  this.accounts = ordered;
3934
3984
  this.lastScanAtMs = Date.now();
3985
+ this.warmExpiryReadings();
3935
3986
  if (this.persistent) try {
3936
3987
  const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
3937
3988
  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.`);
@@ -3942,6 +3993,76 @@ var WorkBuddyAccountPool = class {
3942
3993
  }
3943
3994
  return this.accounts;
3944
3995
  }
3996
+ /**
3997
+ * Warm the deadline readings that `expiry` mode sorts on.
3998
+ *
3999
+ * Fire-and-forget on purpose, from `scan()`: the pool's first request arrives
4000
+ * before any reading exists, and the honest answer to that is the documented
4001
+ * fallback plus a log line, not a stalled request. Everything about the call
4002
+ * is chosen to be unable to make things worse:
4003
+ *
4004
+ * - `this.client` may not exist (a host that wired only token refresh), in
4005
+ * which case there is nothing to read with and the pass is a no-op — the
4006
+ * same guard `ensureFresh` uses;
4007
+ * - a dead sign-in is skipped, and a successful read NEVER calls
4008
+ * `clearCredentialDead`. That is the difference between this and
4009
+ * `reviveBenched`: the billing endpoint answers 200 for a banned account
4010
+ * (observed on 11140), so treating a read as proof of health is what got a
4011
+ * banned account revived six times in a day (S2). Only a token refresh or a
4012
+ * fresh sign-in may clear that mark;
4013
+ * - accounts whose reading is fresh enough are skipped, and so are accounts
4014
+ * already being read (S10's de-duplication, mirroring `refreshInflight`);
4015
+ * - a failed read writes nothing and only warns, so the next pass tries
4016
+ * again without the failure being mistaken for a reading.
4017
+ */
4018
+ warmExpiryReadings() {
4019
+ if (this.client?.fetchCredits === void 0) return;
4020
+ for (const account of this.accounts) this.warmExpiryReadingFor(account.id);
4021
+ }
4022
+ /** One account's warm read; see {@link warmExpiryReadings} for the rules. */
4023
+ async warmOneExpiryReading(account, client) {
4024
+ this.expiryWarmInflight.add(account.id);
4025
+ this.expiryWarmAttemptAt.set(account.id, Date.now());
4026
+ try {
4027
+ const credits = await client.fetchCredits(account.credential);
4028
+ this.noteExpiryOnly(account.id, credits.nearestExpiryMs);
4029
+ } catch (error) {
4030
+ 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);
4031
+ } finally {
4032
+ this.expiryWarmInflight.delete(account.id);
4033
+ }
4034
+ }
4035
+ /**
4036
+ * Top up one account's deadline reading, from wherever the pool notices it is
4037
+ * missing or stale.
4038
+ *
4039
+ * The request path is the second caller (after `scan()`), because a reading
4040
+ * ages out while the pool is busy too: the shim calls this for the account that
4041
+ * just served a request, which is the one whose spend is most likely to have
4042
+ * moved its deadline. No timer is created — the existing balance refresh is
4043
+ * already the natural heartbeat, and this rides on it.
4044
+ *
4045
+ * Every gate lives here rather than in the callers, so both paths obey exactly
4046
+ * the same rules: no client, no account, a rejected sign-in, an already-running
4047
+ * read, a finished "nothing expires" answer, a fresh reading, or an attempt
4048
+ * made within the last minute all mean "do nothing".
4049
+ */
4050
+ warmExpiryReadingFor(accountId) {
4051
+ if (this.distribution !== "expiry") return;
4052
+ const client = this.client;
4053
+ if (client?.fetchCredits === void 0) return;
4054
+ const account = this.accounts.find((item) => item.id === accountId);
4055
+ if (account === void 0) return;
4056
+ const now = Date.now();
4057
+ if ((account.credentialDeadUntilMs ?? 0) > now) return;
4058
+ if (this.expiryWarmInflight.has(accountId)) return;
4059
+ const reading = this.expiryReadingOf(accountId, now);
4060
+ if (reading.state === "none") return;
4061
+ if (reading.state === "at" && !reading.stale) return;
4062
+ const lastAttempt = this.expiryWarmAttemptAt.get(accountId) ?? 0;
4063
+ if (lastAttempt > (reading.readAtMs ?? 0) && now - lastAttempt < EXPIRY_WARM_RETRY_MS) return;
4064
+ this.warmOneExpiryReading(account, client);
4065
+ }
3945
4066
  /** All accounts, cooldown state included. */
3946
4067
  list(region) {
3947
4068
  if (region === void 0) return this.accounts;
@@ -4289,18 +4410,37 @@ var WorkBuddyAccountPool = class {
4289
4410
  * A pool where nobody has a known expiry therefore behaves exactly like
4290
4411
  * priority, which is the honest degradation: without a reading there is
4291
4412
  * nothing to sort by.
4413
+ *
4414
+ * What this method must NOT do is pretend. With only SOME readings in hand it
4415
+ * still has to fall back to `pool[0]`, because picking the earliest of the
4416
+ * accounts that happen to have answered would silently drop the account that
4417
+ * really dies first — the failure mode S0 in `EXPIRY-ADVERSARIAL-20261111.md`
4418
+ * called "worse than not fixing it", since the pick looks plausible and is
4419
+ * wrong. So the incomplete case is announced instead: the caller keeps the old
4420
+ * semantics and the log says which accounts were not read.
4292
4421
  */
4293
4422
  pickByExpiry(pool) {
4423
+ const now = Date.now();
4424
+ const unread = [];
4425
+ const stale = [];
4294
4426
  let best;
4295
4427
  let bestAt = Number.POSITIVE_INFINITY;
4296
4428
  for (const account of pool) {
4297
- const at = this.creditExpiry.get(account.id);
4298
- if (at === void 0) continue;
4429
+ const reading = this.expiryReadingOf(account.id, now);
4430
+ if (reading.stale) stale.push(account);
4431
+ if (reading.state === "unread" || reading.stale) {
4432
+ unread.push(account);
4433
+ continue;
4434
+ }
4435
+ if (reading.state === "none") continue;
4436
+ const at = reading.at ?? Number.POSITIVE_INFINITY;
4299
4437
  if (at < bestAt) {
4300
4438
  best = account;
4301
4439
  bestAt = at;
4302
4440
  }
4303
4441
  }
4442
+ 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`);
4443
+ 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.`);
4304
4444
  return best ?? pool[0];
4305
4445
  }
4306
4446
  /**
@@ -4478,21 +4618,91 @@ var WorkBuddyAccountPool = class {
4478
4618
  * merged: a pack that has been spent or has died disappears from the next
4479
4619
  * reading, and keeping the stale deadline would pin the pool to an account
4480
4620
  * whose credits are already gone — the opposite of what `expiry` mode wants.
4621
+ *
4622
+ * "Nothing expires" is a real answer, not the absence of one: it is stored as
4623
+ * {@link creditExpiryNone} so the account is not read again on every pass.
4481
4624
  */
4482
4625
  noteCredits(accountId, balance, nearestExpiryMs) {
4483
4626
  if (!Number.isFinite(balance)) return;
4484
4627
  if (!this.accounts.some((account) => account.id === accountId)) return;
4485
4628
  this.creditBalances.set(accountId, balance);
4629
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4630
+ }
4631
+ /**
4632
+ * Record ONLY the deadline, never the balance.
4633
+ *
4634
+ * The scan-triggered warm exists to fill `expiry` mode's sort key. Writing the
4635
+ * balance as a side effect would change what the reserve floor decides — an
4636
+ * account could be pulled out of rotation by a background read the user never
4637
+ * asked for, which is a behaviour change outside this fix's scope (S7 in
4638
+ * `EXPIRY-ADVERSARIAL-20261111.md`; the reserve's own cold-start hole is V4,
4639
+ * fixed separately).
4640
+ */
4641
+ noteExpiryOnly(accountId, nearestExpiryMs) {
4642
+ if (!this.accounts.some((account) => account.id === accountId)) return;
4643
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4644
+ }
4645
+ /**
4646
+ * The three-state writer both entry points funnel through.
4647
+ *
4648
+ * One place, so the invariant "a finished reading always leaves a state" can be
4649
+ * read off a single function: either a deadline is stored, or the account joins
4650
+ * `creditExpiryNone`. Nothing here deletes the read stamp — that is what makes
4651
+ * "read, found nothing" distinguishable from "never read".
4652
+ */
4653
+ noteExpiryReading(accountId, nearestExpiryMs) {
4654
+ this.creditExpiryReadAt.set(accountId, Date.now());
4486
4655
  if (nearestExpiryMs === void 0 || !Number.isFinite(nearestExpiryMs)) {
4487
4656
  this.creditExpiry.delete(accountId);
4657
+ this.creditExpiryNone.add(accountId);
4488
4658
  return;
4489
4659
  }
4660
+ this.creditExpiryNone.delete(accountId);
4490
4661
  this.creditExpiry.set(accountId, nearestExpiryMs);
4491
4662
  }
4492
4663
  /** Nearest one-off pack expiry for one account, or undefined when none known. */
4493
4664
  creditExpiryOf(accountId) {
4494
4665
  return this.creditExpiry.get(accountId);
4495
4666
  }
4667
+ /**
4668
+ * The full three-state reading for one account, including staleness.
4669
+ *
4670
+ * `stale` is evaluated against {@link EXPIRY_READING_TTL_MS} here rather than
4671
+ * baked into the stored value, so the TTL stays a constant of the policy and
4672
+ * not of the data.
4673
+ *
4674
+ * Only a real deadline can go stale. "We never asked" is not a reading, and
4675
+ * "nothing here has a deadline" does not become less true with age: a monthly
4676
+ * pack does not grow an expiry date by waiting. Keeping `none` permanently
4677
+ * valid is what makes the S1 loop impossible — an account that answered once
4678
+ * is never read again by the expiry machinery, so there is no predicate that
4679
+ * can stay true forever and re-read it on every pass. If such an account does
4680
+ * gain a one-off pack later, the card refresh (which writes through
4681
+ * `noteCredits` on every poll) is what notices.
4682
+ */
4683
+ expiryReadingOf(accountId, now = Date.now()) {
4684
+ const at = this.creditExpiry.get(accountId);
4685
+ const readAtMs = this.creditExpiryReadAt.get(accountId);
4686
+ if (readAtMs === void 0) return {
4687
+ state: "unread",
4688
+ stale: false
4689
+ };
4690
+ if (at !== void 0) return {
4691
+ state: "at",
4692
+ at,
4693
+ readAtMs,
4694
+ stale: now - readAtMs > this.expiryReadingTtlMs
4695
+ };
4696
+ if (this.creditExpiryNone.has(accountId)) return {
4697
+ state: "none",
4698
+ readAtMs,
4699
+ stale: false
4700
+ };
4701
+ return {
4702
+ state: "unread",
4703
+ stale: false
4704
+ };
4705
+ }
4496
4706
  /** Last known balance for one account, or undefined when never read. */
4497
4707
  creditsOf(accountId) {
4498
4708
  return this.creditBalances.get(accountId);
package/lib/client.js CHANGED
@@ -13470,7 +13470,7 @@ window.__ModuleLoader__.load({
13470
13470
  *
13471
13471
  * @module dsh-xdpool/version
13472
13472
  */
13473
- const POOL_VERSION = "2.6.5";
13473
+ const POOL_VERSION = "2.6.6";
13474
13474
  //#endregion
13475
13475
  //#region src/client/PoolCard.tsx
13476
13476
  /**
package/lib/index.d.ts CHANGED
@@ -577,8 +577,17 @@ export declare class WorkBuddyUpstreamClient {
577
577
  * list is missing half its entries for the rest of the session".
578
578
  */
579
579
  private fetchModelsOnce;
580
- /** Read-only credits query, aggregated by package. Does not consume credits. */
581
- fetchCredits(credential: WorkBuddyCredential): Promise<WorkBuddyCredits>;
580
+ /**
581
+ * Read-only credits query, aggregated by package. Does not consume credits.
582
+ *
583
+ * `signal` is the caller's cancellation, merged with the built-in timeout
584
+ * rather than replacing it: the pool's background warm must give up when the
585
+ * host shuts down, and a caller that has already gone away must not leave a
586
+ * 30 s request running. `AbortSignal.any` is already the repo's way of
587
+ * combining these (see the pricing probe in the shim), and the timeout stays
588
+ * in force so a signal-less caller keeps the old behaviour exactly.
589
+ */
590
+ fetchCredits(credential: WorkBuddyCredential, signal?: AbortSignal): Promise<WorkBuddyCredits>;
582
591
  /** Query today's check-in status without changing account state. */
583
592
  fetchCheckinStatus(credential: WorkBuddyCredential): Promise<WorkBuddyCheckinStatus>;
584
593
  /** Claim today's check-in reward. The browser route guards this mutation. */
@@ -842,6 +851,41 @@ interface TokenRefresher {
842
851
  domain?: string;
843
852
  }>;
844
853
  }
854
+ /**
855
+ * Minimal billing surface the pool needs to fill `creditExpiry` itself.
856
+ *
857
+ * Declared here for the same reason as {@link TokenRefresher}: the pool knows
858
+ * about accounts, not about HTTP, and importing `WorkBuddyUpstreamClient` would
859
+ * make the two modules circular. `fetchCredits` is OPTIONAL so every existing
860
+ * `TokenRefresher` — the test stubs, and any host that only wired token refresh
861
+ * — keeps working untouched; a client without it simply warms nothing.
862
+ */
863
+ interface CreditReader {
864
+ fetchCredits(credential: WorkBuddyCredential, signal?: AbortSignal): Promise<{
865
+ total: number;
866
+ /** Absent (or undefined) when no one-off pack has a deadline. */
867
+ nearestExpiryMs?: number | undefined;
868
+ }>;
869
+ }
870
+ /**
871
+ * What the pool knows about one account's one-off pack deadlines.
872
+ *
873
+ * The three `state`s are the whole point of the B+ fix: "never asked", "asked,
874
+ * nothing has a deadline" and "asked, here is the deadline" need different
875
+ * handling, and collapsing them into one absent-key predicate is what made a
876
+ * pure monthly-pack account be re-read forever (S1 in
877
+ * `EXPIRY-ADVERSARIAL-20261111.md`). `stale` is orthogonal: the reading is real
878
+ * but older than {@link EXPIRY_READING_TTL_MS}, so it describes the past.
879
+ */
880
+ interface ExpiryReading {
881
+ state: 'unread' | 'none' | 'at';
882
+ /** Deadline, epoch ms; present exactly when `state === 'at'`. */
883
+ at?: number;
884
+ /** When this reading was written, epoch ms; absent for `unread`. */
885
+ readAtMs?: number;
886
+ /** True when the reading is older than {@link EXPIRY_READING_TTL_MS}. */
887
+ stale: boolean;
888
+ }
845
889
  /** Live auth file name the WorkBuddy desktop app writes. */
846
890
  export declare const WORKBUDDY_LIVE_FILENAME = "workbuddy-desktop.info";
847
891
  /** Snapshot files left behind by previous logins share this prefix. */
@@ -970,9 +1014,16 @@ interface AccountPoolOptions {
970
1014
  */
971
1015
  credentialDeadCooldownMs?: number;
972
1016
  /** Upstream client used to refresh near-expiry tokens. */
973
- client?: TokenRefresher;
1017
+ client?: TokenRefresher & Partial<CreditReader>;
974
1018
  /** Refresh this long before actual expiry; default five minutes. */
975
1019
  refreshMarginMs?: number;
1020
+ /**
1021
+ * How long a credit-pack deadline reading is trusted, in ms.
1022
+ *
1023
+ * Defaults to {@link EXPIRY_READING_TTL_MS}; overridable so a test can age a
1024
+ * reading without sleeping for an hour.
1025
+ */
1026
+ expiryReadingTtlMs?: number;
976
1027
  /**
977
1028
  * How requests are spread across the pool.
978
1029
  *
@@ -1024,6 +1075,7 @@ export declare class WorkBuddyAccountPool {
1024
1075
  private credentialDeadCooldownMs;
1025
1076
  private readonly client;
1026
1077
  private readonly refreshMarginMs;
1078
+ private readonly expiryReadingTtlMs;
1027
1079
  private accounts;
1028
1080
  /**
1029
1081
  * Files the last scan could not read, with the reason.
@@ -1119,10 +1171,41 @@ export declare class WorkBuddyAccountPool {
1119
1171
  * their own cycle and are therefore never urgent — which is why this is
1120
1172
  * written from the same `fetchCredits` reading that fills `creditBalances`.
1121
1173
  *
1122
- * An absent entry means "never probed, or nothing is about to expire". Both
1123
- * are the same thing to `expiry` mode: not urgent, so it sorts last.
1174
+ * A positive value is a deadline. The two other states are kept in
1175
+ * {@link creditExpiryNone} and {@link creditExpiryReadAt} rather than as a
1176
+ * missing key, because a missing key cannot tell "we never looked" from "we
1177
+ * looked and nothing has a deadline" — and only the first is worth reading
1178
+ * again. An account whose packs are all monthly reads as `none` forever, which
1179
+ * is exactly right: asking again cannot change the answer (S1).
1124
1180
  */
1125
1181
  private creditExpiry;
1182
+ /**
1183
+ * Accounts whose last reading found NO one-off deadline (all monthly packs, or
1184
+ * none at all). Written instead of deleting the key, so the account stops
1185
+ * being a candidate for re-reading.
1186
+ */
1187
+ private creditExpiryNone;
1188
+ /** When each account's deadline reading was taken, epoch ms. */
1189
+ private creditExpiryReadAt;
1190
+ /**
1191
+ * Accounts whose deadline reading is being fetched right now.
1192
+ *
1193
+ * Same de-duplication idea as {@link refreshInflight}, for the same reason: a
1194
+ * scan-triggered warm and a request-triggered top-up must not both spend a
1195
+ * billing round trip on the same account. A Set rather than a Map of promises
1196
+ * because no caller ever awaits the warm — the point is only that a second
1197
+ * pass skips it.
1198
+ */
1199
+ private expiryWarmInflight;
1200
+ /**
1201
+ * Last time the pool tried to warm an account's deadline reading, epoch ms.
1202
+ *
1203
+ * The TTL is the success gate, not a retry gate: a failed read writes nothing,
1204
+ * so without this a permanently failing billing endpoint would be hit on every
1205
+ * scan and every served request. One attempt per account per minute is cheap
1206
+ * and still recovers quickly from a transient failure.
1207
+ */
1208
+ private expiryWarmAttemptAt;
1126
1209
  /**
1127
1210
  * Last time each account served a request, epoch ms. Drives the idle term
1128
1211
  * of the priority-mode weighting below: an account that just served loses to
@@ -1217,6 +1300,47 @@ export declare class WorkBuddyAccountPool {
1217
1300
  private pruneExpiredSnapshots;
1218
1301
  /** Rescan the auth directories and merge newly discovered accounts. */
1219
1302
  scan(): Promise<WorkBuddyAccount[]>;
1303
+ /**
1304
+ * Warm the deadline readings that `expiry` mode sorts on.
1305
+ *
1306
+ * Fire-and-forget on purpose, from `scan()`: the pool's first request arrives
1307
+ * before any reading exists, and the honest answer to that is the documented
1308
+ * fallback plus a log line, not a stalled request. Everything about the call
1309
+ * is chosen to be unable to make things worse:
1310
+ *
1311
+ * - `this.client` may not exist (a host that wired only token refresh), in
1312
+ * which case there is nothing to read with and the pass is a no-op — the
1313
+ * same guard `ensureFresh` uses;
1314
+ * - a dead sign-in is skipped, and a successful read NEVER calls
1315
+ * `clearCredentialDead`. That is the difference between this and
1316
+ * `reviveBenched`: the billing endpoint answers 200 for a banned account
1317
+ * (observed on 11140), so treating a read as proof of health is what got a
1318
+ * banned account revived six times in a day (S2). Only a token refresh or a
1319
+ * fresh sign-in may clear that mark;
1320
+ * - accounts whose reading is fresh enough are skipped, and so are accounts
1321
+ * already being read (S10's de-duplication, mirroring `refreshInflight`);
1322
+ * - a failed read writes nothing and only warns, so the next pass tries
1323
+ * again without the failure being mistaken for a reading.
1324
+ */
1325
+ private warmExpiryReadings;
1326
+ /** One account's warm read; see {@link warmExpiryReadings} for the rules. */
1327
+ private warmOneExpiryReading;
1328
+ /**
1329
+ * Top up one account's deadline reading, from wherever the pool notices it is
1330
+ * missing or stale.
1331
+ *
1332
+ * The request path is the second caller (after `scan()`), because a reading
1333
+ * ages out while the pool is busy too: the shim calls this for the account that
1334
+ * just served a request, which is the one whose spend is most likely to have
1335
+ * moved its deadline. No timer is created — the existing balance refresh is
1336
+ * already the natural heartbeat, and this rides on it.
1337
+ *
1338
+ * Every gate lives here rather than in the callers, so both paths obey exactly
1339
+ * the same rules: no client, no account, a rejected sign-in, an already-running
1340
+ * read, a finished "nothing expires" answer, a fresh reading, or an attempt
1341
+ * made within the last minute all mean "do nothing".
1342
+ */
1343
+ warmExpiryReadingFor(accountId: string): void;
1220
1344
  /** All accounts, cooldown state included. */
1221
1345
  list(region?: WorkBuddyRegion): readonly WorkBuddyAccount[];
1222
1346
  /**
@@ -1338,6 +1462,14 @@ export declare class WorkBuddyAccountPool {
1338
1462
  * A pool where nobody has a known expiry therefore behaves exactly like
1339
1463
  * priority, which is the honest degradation: without a reading there is
1340
1464
  * nothing to sort by.
1465
+ *
1466
+ * What this method must NOT do is pretend. With only SOME readings in hand it
1467
+ * still has to fall back to `pool[0]`, because picking the earliest of the
1468
+ * accounts that happen to have answered would silently drop the account that
1469
+ * really dies first — the failure mode S0 in `EXPIRY-ADVERSARIAL-20261111.md`
1470
+ * called "worse than not fixing it", since the pick looks plausible and is
1471
+ * wrong. So the incomplete case is announced instead: the caller keeps the old
1472
+ * semantics and the log says which accounts were not read.
1341
1473
  */
1342
1474
  private pickByExpiry;
1343
1475
  /**
@@ -1430,10 +1562,50 @@ export declare class WorkBuddyAccountPool {
1430
1562
  * merged: a pack that has been spent or has died disappears from the next
1431
1563
  * reading, and keeping the stale deadline would pin the pool to an account
1432
1564
  * whose credits are already gone — the opposite of what `expiry` mode wants.
1565
+ *
1566
+ * "Nothing expires" is a real answer, not the absence of one: it is stored as
1567
+ * {@link creditExpiryNone} so the account is not read again on every pass.
1433
1568
  */
1434
1569
  noteCredits(accountId: string, balance: number, nearestExpiryMs?: number): void;
1570
+ /**
1571
+ * Record ONLY the deadline, never the balance.
1572
+ *
1573
+ * The scan-triggered warm exists to fill `expiry` mode's sort key. Writing the
1574
+ * balance as a side effect would change what the reserve floor decides — an
1575
+ * account could be pulled out of rotation by a background read the user never
1576
+ * asked for, which is a behaviour change outside this fix's scope (S7 in
1577
+ * `EXPIRY-ADVERSARIAL-20261111.md`; the reserve's own cold-start hole is V4,
1578
+ * fixed separately).
1579
+ */
1580
+ noteExpiryOnly(accountId: string, nearestExpiryMs?: number): void;
1581
+ /**
1582
+ * The three-state writer both entry points funnel through.
1583
+ *
1584
+ * One place, so the invariant "a finished reading always leaves a state" can be
1585
+ * read off a single function: either a deadline is stored, or the account joins
1586
+ * `creditExpiryNone`. Nothing here deletes the read stamp — that is what makes
1587
+ * "read, found nothing" distinguishable from "never read".
1588
+ */
1589
+ private noteExpiryReading;
1435
1590
  /** Nearest one-off pack expiry for one account, or undefined when none known. */
1436
1591
  creditExpiryOf(accountId: string): number | undefined;
1592
+ /**
1593
+ * The full three-state reading for one account, including staleness.
1594
+ *
1595
+ * `stale` is evaluated against {@link EXPIRY_READING_TTL_MS} here rather than
1596
+ * baked into the stored value, so the TTL stays a constant of the policy and
1597
+ * not of the data.
1598
+ *
1599
+ * Only a real deadline can go stale. "We never asked" is not a reading, and
1600
+ * "nothing here has a deadline" does not become less true with age: a monthly
1601
+ * pack does not grow an expiry date by waiting. Keeping `none` permanently
1602
+ * valid is what makes the S1 loop impossible — an account that answered once
1603
+ * is never read again by the expiry machinery, so there is no predicate that
1604
+ * can stay true forever and re-read it on every pass. If such an account does
1605
+ * gain a one-off pack later, the card refresh (which writes through
1606
+ * `noteCredits` on every poll) is what notices.
1607
+ */
1608
+ expiryReadingOf(accountId: string, now?: number): ExpiryReading;
1437
1609
  /** Last known balance for one account, or undefined when never read. */
1438
1610
  creditsOf(accountId: string): number | undefined;
1439
1611
  /** The credit floor the user set for one account; 0 when unset. */