heybash-xdpool 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/bin.js CHANGED
@@ -4,11 +4,12 @@ import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, unlink, writeFil
4
4
  import { homedir, platform } from "node:os";
5
5
  import { basename, dirname, join, resolve } from "node:path";
6
6
  import { execFile, execFileSync } from "node:child_process";
7
+ import "@deepseek-ai/dsh-llm";
8
+ import "@deepseek-ai/dsh-llm/brand";
7
9
  import z from "@deepseek-ai/schemastery";
8
10
  import { fileURLToPath, pathToFileURL } from "node:url";
9
11
  import "@earendil-works/pi-ai";
10
12
  import "@earendil-works/pi-ai/api/openai-completions.lazy";
11
- import "@deepseek-ai/dsh-llm";
12
13
  import "@deepseek-ai/dsh-llm-pi-ai";
13
14
  // src/badges.ts
14
15
  /**
@@ -189,6 +190,38 @@ const SESSION_DEAD_MARKERS = [
189
190
  */
190
191
  const ALREADY_CHECKIN_MARKERS = ["已签到", "already"];
191
192
  /**
193
+ * Markers for "the check-in activity is not running on this gateway".
194
+ *
195
+ * Distinct from {@link ALREADY_CHECKIN_MARKERS}: "already collected" means the
196
+ * account got its reward, while this means there is nothing to collect on that
197
+ * gateway at all. Both are no-ops rather than failures, but only the first is
198
+ * evidence the account is working.
199
+ *
200
+ * Measured on the international gateway (`www.workbuddy.ai`, 2026-11-10):
201
+ * `checkin-activity-status` answers 200 with `active: false`, and claiming
202
+ * answers HTTP 400 `{"code":10001,"msg":"签到活动未开启或已过期"}`. Neither `已签到`
203
+ * nor `already` matches that wording, so the scheduler used to record a healthy
204
+ * global account as a failed job — a per-account `failed: +1` on every run, for
205
+ * an activity the gateway simply does not run.
206
+ */
207
+ const CHECKIN_UNAVAILABLE_MARKERS = [
208
+ "签到活动未开启",
209
+ "活动未开启",
210
+ "活动已过期",
211
+ "not active",
212
+ "activity is not open"
213
+ ];
214
+ /**
215
+ * Whether a claim failure means "this gateway runs no check-in activity".
216
+ *
217
+ * Callers treat this as a skipped no-op: the job reached the upstream and
218
+ * correctly found nothing to collect, which is not an account fault.
219
+ */
220
+ function isCheckinUnavailable(error) {
221
+ const message = error instanceof Error ? error.message : String(error);
222
+ return CHECKIN_UNAVAILABLE_MARKERS.some((marker) => message.includes(marker));
223
+ }
224
+ /**
192
225
  * Markers for "there is no compensation offer to collect".
193
226
  *
194
227
  * The offer is seasonal — an outage announcement opens one, and it closes on a
@@ -545,6 +578,7 @@ const SSE_SCAN_LIMIT = 1 << 20;
545
578
  /** Server request ids look like `cmb-<32 hex>` or a bare 32 hex string. */
546
579
  const SERVER_ID_PATTERN = /"id"\s*:\s*"((?:cmb-)?[0-9a-f]{32})"/;
547
580
  const DESKTOP_TASK_UA = "WorkBuddy/5.5.6 WorkBuddy/5.5.6 CLI/2.137.1";
581
+ const SKILL_SHARE_UA = "WorkBuddy/5.9.3 WorkBuddy/5.9.3 CLI/2.165.0";
548
582
  /**
549
583
  * Derive a stable 36-hex device id from the account uid.
550
584
  *
@@ -1345,8 +1379,18 @@ var WorkBuddyUpstreamClient = class {
1345
1379
  if (models.length === 0) throw new Error("workbuddy model catalog resolved to an empty list");
1346
1380
  return models;
1347
1381
  }
1348
- /** Read-only credits query, aggregated by package. Does not consume credits. */
1349
- async fetchCredits(credential) {
1382
+ /**
1383
+ * Read-only credits query, aggregated by package. Does not consume credits.
1384
+ *
1385
+ * `signal` is the caller's cancellation, merged with the built-in timeout
1386
+ * rather than replacing it: the pool's background warm must give up when the
1387
+ * host shuts down, and a caller that has already gone away must not leave a
1388
+ * 30 s request running. `AbortSignal.any` is already the repo's way of
1389
+ * combining these (see the pricing probe in the shim), and the timeout stays
1390
+ * in force so a signal-less caller keeps the old behaviour exactly.
1391
+ */
1392
+ async fetchCredits(credential, signal) {
1393
+ const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
1350
1394
  const now = /* @__PURE__ */ new Date();
1351
1395
  const fmt = (date) => {
1352
1396
  const p = (n) => n.toString().padStart(2, "0");
@@ -1363,7 +1407,7 @@ var WorkBuddyUpstreamClient = class {
1363
1407
  PackageEndTimeRangeBegin: fmt(now),
1364
1408
  PackageEndTimeRangeEnd: fmt(new Date(now.getTime() + 3185136e6))
1365
1409
  }),
1366
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1410
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
1367
1411
  });
1368
1412
  const envelope = await readEnvelope(response);
1369
1413
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
@@ -1558,9 +1602,20 @@ var WorkBuddyUpstreamClient = class {
1558
1602
  * Business fields win over the fingerprint, so a caller can override a device
1559
1603
  * id to align with a real install.
1560
1604
  */
1561
- async reportDesktopEvents(credential, events) {
1605
+ async reportDesktopEvents(credential, events, identity) {
1562
1606
  if (events.length === 0) return;
1563
1607
  const fingerprint = this.desktopFingerprint(credential);
1608
+ if (identity === "skill-share") Object.assign(fingerprint, {
1609
+ ideVersion: "5.9.3",
1610
+ extVersion: "5.9.3",
1611
+ releaseDate: 1793093056315,
1612
+ commit: "d46924219e79332f49c37ccebf27292f87001b19",
1613
+ qimei36: deriveDeviceId(credential, "qimei"),
1614
+ osVersion: "10.0.28000",
1615
+ cpuModel: "11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz",
1616
+ cpuCores: 8,
1617
+ memorySize: 16
1618
+ });
1564
1619
  const body = events.map((event) => ({
1565
1620
  ...fingerprint,
1566
1621
  ...event
@@ -1571,7 +1626,7 @@ var WorkBuddyUpstreamClient = class {
1571
1626
  "Authorization": `Bearer ${credential.accessToken}`,
1572
1627
  "Accept": "application/json, text/plain, */*",
1573
1628
  "Content-Type": "application/json;charset=UTF-8",
1574
- "User-Agent": DESKTOP_TASK_UA,
1629
+ "User-Agent": identity === "skill-share" ? SKILL_SHARE_UA : DESKTOP_TASK_UA,
1575
1630
  "X-Product": "SaaS",
1576
1631
  "X-Request-ID": deriveDeviceId(credential, "req") + String(Date.now() % 1e6),
1577
1632
  ...credential.uid === void 0 || credential.uid === "" ? {} : { "X-User-Id": credential.uid },
@@ -1713,6 +1768,80 @@ var WorkBuddyUpstreamClient = class {
1713
1768
  }
1714
1769
  return out;
1715
1770
  }
1771
+ /** Read public marketplace skills for the share-link task. */
1772
+ async shareableSkills(credential) {
1773
+ if (regionOf(credential.domain) !== "cn") throw new Error("skill sharing is only available for domestic accounts");
1774
+ const response = await this.fetchImpl("https://www.codebuddy.cn/v2/operation-platform/market/skill/list", {
1775
+ method: "POST",
1776
+ headers: {
1777
+ ...chatHeaders(credential),
1778
+ "User-Agent": DESKTOP_TASK_UA
1779
+ },
1780
+ body: JSON.stringify({
1781
+ page: 1,
1782
+ page_size: 20
1783
+ }),
1784
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1785
+ });
1786
+ const envelope = await readEnvelope(response);
1787
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1788
+ const rows = asRecord(envelope.data)["skills"];
1789
+ if (!Array.isArray(rows)) return [];
1790
+ return rows.flatMap((value) => {
1791
+ const row = asRecord(value);
1792
+ const id = typeof row["skill_id"] === "string" ? row["skill_id"] : typeof row["id"] === "string" ? row["id"] : "";
1793
+ const name = [
1794
+ row["display_name_zh"],
1795
+ row["name"],
1796
+ row["display_name_en"]
1797
+ ].find((v) => typeof v === "string" && v.trim() !== "");
1798
+ const description = [
1799
+ row["description_zh"],
1800
+ row["description"],
1801
+ row["description_en"]
1802
+ ].find((v) => typeof v === "string" && v.trim() !== "");
1803
+ return id.trim() === "" || typeof name !== "string" ? [] : [{
1804
+ id: id.trim(),
1805
+ name: name.trim(),
1806
+ description: typeof description === "string" ? description.trim().slice(0, 60) : ""
1807
+ }];
1808
+ });
1809
+ }
1810
+ /** Create a real link for a public marketplace skill. Never sends it to a person. */
1811
+ async createSkillShareLink(credential, skill) {
1812
+ if (regionOf(credential.domain) !== "cn" || !credential.uid || !skill.id || !skill.name) throw new Error("skill share requires a domestic account and a marketplace skill");
1813
+ const response = await this.fetchImpl("https://open.workbuddy.cn/api/v2/open-platform/asset-shares/c2c/channels", {
1814
+ method: "POST",
1815
+ headers: {
1816
+ "Authorization": `Bearer ${credential.accessToken}`,
1817
+ "X-User-Id": credential.uid,
1818
+ "X-Domain": "copilot.tencent.com",
1819
+ "Content-Type": "application/json",
1820
+ "Accept": "application/json, text/plain, */*",
1821
+ "User-Agent": SKILL_SHARE_UA
1822
+ },
1823
+ body: JSON.stringify({
1824
+ asset_kind: "skill",
1825
+ asset_source: "market",
1826
+ asset_ref: JSON.stringify({ asset_id: skill.id }),
1827
+ ways: ["link"],
1828
+ extra: {
1829
+ name: skill.name,
1830
+ description: skill.description,
1831
+ shareKey: skill.id,
1832
+ marketplaceSource: "builtin-market"
1833
+ }
1834
+ }),
1835
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1836
+ });
1837
+ const envelope = await readEnvelope(response);
1838
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1839
+ const data = asRecord(envelope.data);
1840
+ const shareCode = typeof data["share_code"] === "string" ? data["share_code"].trim() : "";
1841
+ const link = (Array.isArray(data["ways"]) ? data["ways"] : []).map(asRecord).find((way) => way["share_way"] === "link")?.["resource_ref"];
1842
+ if (shareCode === "" || typeof link !== "string" || link.trim() === "") throw new Error("skill share response has no share code or link");
1843
+ return { shareCode };
1844
+ }
1716
1845
  /**
1717
1846
  * Open a REAL desktop conversation and return the ids the server assigned.
1718
1847
  *
@@ -1968,7 +2097,11 @@ var WorkBuddyUpstreamClient = class {
1968
2097
  * rather than an error, which is why it is thrown as-is for them to classify.
1969
2098
  */
1970
2099
  async buddyAdoptFirst(credential) {
1971
- await this.growthJson(credential, "POST", "/activity/growth/buddy/first", {});
2100
+ const data = await this.growthJson(credential, "POST", "/activity/growth/buddy/first", {});
2101
+ return {
2102
+ credit: numOf(data["credit"]),
2103
+ energy: numOf(data["energy"])
2104
+ };
1972
2105
  }
1973
2106
  /** Current travel state for the account's buddy. */
1974
2107
  async buddyTravelStatus(credential) {
@@ -3540,6 +3673,13 @@ const EXHAUST_COOLDOWN_MS = 18e5;
3540
3673
  */
3541
3674
  const CREDENTIAL_DEAD_COOLDOWN_MS = 18e5;
3542
3675
  /**
3676
+ * Shortest gap between two attempts at the same account's deadline reading.
3677
+ *
3678
+ * Only failed attempts are actually throttled by this: a successful read stamps
3679
+ * the reading itself, so {@link EXPIRY_READING_TTL_MS} takes over from there.
3680
+ */
3681
+ const EXPIRY_WARM_RETRY_MS = 6e4;
3682
+ /**
3543
3683
  * Does this refresh failure prove the credential itself is dead?
3544
3684
  *
3545
3685
  * The upstream answers a revoked refresh token with `invalid_grant: Offline user
@@ -3568,6 +3708,7 @@ var WorkBuddyAccountPool = class {
3568
3708
  credentialDeadCooldownMs;
3569
3709
  client;
3570
3710
  refreshMarginMs;
3711
+ expiryReadingTtlMs;
3571
3712
  accounts = [];
3572
3713
  /**
3573
3714
  * Files the last scan could not read, with the reason.
@@ -3663,11 +3804,42 @@ var WorkBuddyAccountPool = class {
3663
3804
  * their own cycle and are therefore never urgent — which is why this is
3664
3805
  * written from the same `fetchCredits` reading that fills `creditBalances`.
3665
3806
  *
3666
- * An absent entry means "never probed, or nothing is about to expire". Both
3667
- * are the same thing to `expiry` mode: not urgent, so it sorts last.
3807
+ * A positive value is a deadline. The two other states are kept in
3808
+ * {@link creditExpiryNone} and {@link creditExpiryReadAt} rather than as a
3809
+ * missing key, because a missing key cannot tell "we never looked" from "we
3810
+ * looked and nothing has a deadline" — and only the first is worth reading
3811
+ * again. An account whose packs are all monthly reads as `none` forever, which
3812
+ * is exactly right: asking again cannot change the answer (S1).
3668
3813
  */
3669
3814
  creditExpiry = /* @__PURE__ */ new Map();
3670
3815
  /**
3816
+ * Accounts whose last reading found NO one-off deadline (all monthly packs, or
3817
+ * none at all). Written instead of deleting the key, so the account stops
3818
+ * being a candidate for re-reading.
3819
+ */
3820
+ creditExpiryNone = /* @__PURE__ */ new Set();
3821
+ /** When each account's deadline reading was taken, epoch ms. */
3822
+ creditExpiryReadAt = /* @__PURE__ */ new Map();
3823
+ /**
3824
+ * Accounts whose deadline reading is being fetched right now.
3825
+ *
3826
+ * Same de-duplication idea as {@link refreshInflight}, for the same reason: a
3827
+ * scan-triggered warm and a request-triggered top-up must not both spend a
3828
+ * billing round trip on the same account. A Set rather than a Map of promises
3829
+ * because no caller ever awaits the warm — the point is only that a second
3830
+ * pass skips it.
3831
+ */
3832
+ expiryWarmInflight = /* @__PURE__ */ new Set();
3833
+ /**
3834
+ * Last time the pool tried to warm an account's deadline reading, epoch ms.
3835
+ *
3836
+ * The TTL is the success gate, not a retry gate: a failed read writes nothing,
3837
+ * so without this a permanently failing billing endpoint would be hit on every
3838
+ * scan and every served request. One attempt per account per minute is cheap
3839
+ * and still recovers quickly from a transient failure.
3840
+ */
3841
+ expiryWarmAttemptAt = /* @__PURE__ */ new Map();
3842
+ /**
3671
3843
  * Last time each account served a request, epoch ms. Drives the idle term
3672
3844
  * of the priority-mode weighting below: an account that just served loses to
3673
3845
  * one that has been idle, so a small pool stops hammering a single account.
@@ -3712,6 +3884,7 @@ var WorkBuddyAccountPool = class {
3712
3884
  this.credentialDeadCooldownMs = options.credentialDeadCooldownMs ?? CREDENTIAL_DEAD_COOLDOWN_MS;
3713
3885
  this.client = options.client;
3714
3886
  this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
3887
+ this.expiryReadingTtlMs = options.expiryReadingTtlMs ?? 36e5;
3715
3888
  this.distribution = options.distribution ?? "priority";
3716
3889
  this.persistent = options.persistent ?? false;
3717
3890
  this.storePath = accountStorePath();
@@ -3926,6 +4099,7 @@ var WorkBuddyAccountPool = class {
3926
4099
  ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
3927
4100
  this.accounts = ordered;
3928
4101
  this.lastScanAtMs = Date.now();
4102
+ this.warmExpiryReadings();
3929
4103
  if (this.persistent) try {
3930
4104
  const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
3931
4105
  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.`);
@@ -3936,6 +4110,76 @@ var WorkBuddyAccountPool = class {
3936
4110
  }
3937
4111
  return this.accounts;
3938
4112
  }
4113
+ /**
4114
+ * Warm the deadline readings that `expiry` mode sorts on.
4115
+ *
4116
+ * Fire-and-forget on purpose, from `scan()`: the pool's first request arrives
4117
+ * before any reading exists, and the honest answer to that is the documented
4118
+ * fallback plus a log line, not a stalled request. Everything about the call
4119
+ * is chosen to be unable to make things worse:
4120
+ *
4121
+ * - `this.client` may not exist (a host that wired only token refresh), in
4122
+ * which case there is nothing to read with and the pass is a no-op — the
4123
+ * same guard `ensureFresh` uses;
4124
+ * - a dead sign-in is skipped, and a successful read NEVER calls
4125
+ * `clearCredentialDead`. That is the difference between this and
4126
+ * `reviveBenched`: the billing endpoint answers 200 for a banned account
4127
+ * (observed on 11140), so treating a read as proof of health is what got a
4128
+ * banned account revived six times in a day (S2). Only a token refresh or a
4129
+ * fresh sign-in may clear that mark;
4130
+ * - accounts whose reading is fresh enough are skipped, and so are accounts
4131
+ * already being read (S10's de-duplication, mirroring `refreshInflight`);
4132
+ * - a failed read writes nothing and only warns, so the next pass tries
4133
+ * again without the failure being mistaken for a reading.
4134
+ */
4135
+ warmExpiryReadings() {
4136
+ if (this.client?.fetchCredits === void 0) return;
4137
+ for (const account of this.accounts) this.warmExpiryReadingFor(account.id);
4138
+ }
4139
+ /** One account's warm read; see {@link warmExpiryReadings} for the rules. */
4140
+ async warmOneExpiryReading(account, client) {
4141
+ this.expiryWarmInflight.add(account.id);
4142
+ this.expiryWarmAttemptAt.set(account.id, Date.now());
4143
+ try {
4144
+ const credits = await client.fetchCredits(account.credential);
4145
+ this.noteExpiryOnly(account.id, credits.nearestExpiryMs);
4146
+ } catch (error) {
4147
+ 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);
4148
+ } finally {
4149
+ this.expiryWarmInflight.delete(account.id);
4150
+ }
4151
+ }
4152
+ /**
4153
+ * Top up one account's deadline reading, from wherever the pool notices it is
4154
+ * missing or stale.
4155
+ *
4156
+ * The request path is the second caller (after `scan()`), because a reading
4157
+ * ages out while the pool is busy too: the shim calls this for the account that
4158
+ * just served a request, which is the one whose spend is most likely to have
4159
+ * moved its deadline. No timer is created — the existing balance refresh is
4160
+ * already the natural heartbeat, and this rides on it.
4161
+ *
4162
+ * Every gate lives here rather than in the callers, so both paths obey exactly
4163
+ * the same rules: no client, no account, a rejected sign-in, an already-running
4164
+ * read, a finished "nothing expires" answer, a fresh reading, or an attempt
4165
+ * made within the last minute all mean "do nothing".
4166
+ */
4167
+ warmExpiryReadingFor(accountId) {
4168
+ if (this.distribution !== "expiry") return;
4169
+ const client = this.client;
4170
+ if (client?.fetchCredits === void 0) return;
4171
+ const account = this.accounts.find((item) => item.id === accountId);
4172
+ if (account === void 0) return;
4173
+ const now = Date.now();
4174
+ if ((account.credentialDeadUntilMs ?? 0) > now) return;
4175
+ if (this.expiryWarmInflight.has(accountId)) return;
4176
+ const reading = this.expiryReadingOf(accountId, now);
4177
+ if (reading.state === "none") return;
4178
+ if (reading.state === "at" && !reading.stale) return;
4179
+ const lastAttempt = this.expiryWarmAttemptAt.get(accountId) ?? 0;
4180
+ if (lastAttempt > (reading.readAtMs ?? 0) && now - lastAttempt < EXPIRY_WARM_RETRY_MS) return;
4181
+ this.warmOneExpiryReading(account, client);
4182
+ }
3939
4183
  /** All accounts, cooldown state included. */
3940
4184
  list(region) {
3941
4185
  if (region === void 0) return this.accounts;
@@ -4283,18 +4527,37 @@ var WorkBuddyAccountPool = class {
4283
4527
  * A pool where nobody has a known expiry therefore behaves exactly like
4284
4528
  * priority, which is the honest degradation: without a reading there is
4285
4529
  * nothing to sort by.
4530
+ *
4531
+ * What this method must NOT do is pretend. With only SOME readings in hand it
4532
+ * still has to fall back to `pool[0]`, because picking the earliest of the
4533
+ * accounts that happen to have answered would silently drop the account that
4534
+ * really dies first — the failure mode S0 in `EXPIRY-ADVERSARIAL-20261111.md`
4535
+ * called "worse than not fixing it", since the pick looks plausible and is
4536
+ * wrong. So the incomplete case is announced instead: the caller keeps the old
4537
+ * semantics and the log says which accounts were not read.
4286
4538
  */
4287
4539
  pickByExpiry(pool) {
4540
+ const now = Date.now();
4541
+ const unread = [];
4542
+ const stale = [];
4288
4543
  let best;
4289
4544
  let bestAt = Number.POSITIVE_INFINITY;
4290
4545
  for (const account of pool) {
4291
- const at = this.creditExpiry.get(account.id);
4292
- if (at === void 0) continue;
4546
+ const reading = this.expiryReadingOf(account.id, now);
4547
+ if (reading.stale) stale.push(account);
4548
+ if (reading.state === "unread" || reading.stale) {
4549
+ unread.push(account);
4550
+ continue;
4551
+ }
4552
+ if (reading.state === "none") continue;
4553
+ const at = reading.at ?? Number.POSITIVE_INFINITY;
4293
4554
  if (at < bestAt) {
4294
4555
  best = account;
4295
4556
  bestAt = at;
4296
4557
  }
4297
4558
  }
4559
+ 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`);
4560
+ 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.`);
4298
4561
  return best ?? pool[0];
4299
4562
  }
4300
4563
  /**
@@ -4472,21 +4735,91 @@ var WorkBuddyAccountPool = class {
4472
4735
  * merged: a pack that has been spent or has died disappears from the next
4473
4736
  * reading, and keeping the stale deadline would pin the pool to an account
4474
4737
  * whose credits are already gone — the opposite of what `expiry` mode wants.
4738
+ *
4739
+ * "Nothing expires" is a real answer, not the absence of one: it is stored as
4740
+ * {@link creditExpiryNone} so the account is not read again on every pass.
4475
4741
  */
4476
4742
  noteCredits(accountId, balance, nearestExpiryMs) {
4477
4743
  if (!Number.isFinite(balance)) return;
4478
4744
  if (!this.accounts.some((account) => account.id === accountId)) return;
4479
4745
  this.creditBalances.set(accountId, balance);
4746
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4747
+ }
4748
+ /**
4749
+ * Record ONLY the deadline, never the balance.
4750
+ *
4751
+ * The scan-triggered warm exists to fill `expiry` mode's sort key. Writing the
4752
+ * balance as a side effect would change what the reserve floor decides — an
4753
+ * account could be pulled out of rotation by a background read the user never
4754
+ * asked for, which is a behaviour change outside this fix's scope (S7 in
4755
+ * `EXPIRY-ADVERSARIAL-20261111.md`; the reserve's own cold-start hole is V4,
4756
+ * fixed separately).
4757
+ */
4758
+ noteExpiryOnly(accountId, nearestExpiryMs) {
4759
+ if (!this.accounts.some((account) => account.id === accountId)) return;
4760
+ this.noteExpiryReading(accountId, nearestExpiryMs);
4761
+ }
4762
+ /**
4763
+ * The three-state writer both entry points funnel through.
4764
+ *
4765
+ * One place, so the invariant "a finished reading always leaves a state" can be
4766
+ * read off a single function: either a deadline is stored, or the account joins
4767
+ * `creditExpiryNone`. Nothing here deletes the read stamp — that is what makes
4768
+ * "read, found nothing" distinguishable from "never read".
4769
+ */
4770
+ noteExpiryReading(accountId, nearestExpiryMs) {
4771
+ this.creditExpiryReadAt.set(accountId, Date.now());
4480
4772
  if (nearestExpiryMs === void 0 || !Number.isFinite(nearestExpiryMs)) {
4481
4773
  this.creditExpiry.delete(accountId);
4774
+ this.creditExpiryNone.add(accountId);
4482
4775
  return;
4483
4776
  }
4777
+ this.creditExpiryNone.delete(accountId);
4484
4778
  this.creditExpiry.set(accountId, nearestExpiryMs);
4485
4779
  }
4486
4780
  /** Nearest one-off pack expiry for one account, or undefined when none known. */
4487
4781
  creditExpiryOf(accountId) {
4488
4782
  return this.creditExpiry.get(accountId);
4489
4783
  }
4784
+ /**
4785
+ * The full three-state reading for one account, including staleness.
4786
+ *
4787
+ * `stale` is evaluated against {@link EXPIRY_READING_TTL_MS} here rather than
4788
+ * baked into the stored value, so the TTL stays a constant of the policy and
4789
+ * not of the data.
4790
+ *
4791
+ * Only a real deadline can go stale. "We never asked" is not a reading, and
4792
+ * "nothing here has a deadline" does not become less true with age: a monthly
4793
+ * pack does not grow an expiry date by waiting. Keeping `none` permanently
4794
+ * valid is what makes the S1 loop impossible — an account that answered once
4795
+ * is never read again by the expiry machinery, so there is no predicate that
4796
+ * can stay true forever and re-read it on every pass. If such an account does
4797
+ * gain a one-off pack later, the card refresh (which writes through
4798
+ * `noteCredits` on every poll) is what notices.
4799
+ */
4800
+ expiryReadingOf(accountId, now = Date.now()) {
4801
+ const at = this.creditExpiry.get(accountId);
4802
+ const readAtMs = this.creditExpiryReadAt.get(accountId);
4803
+ if (readAtMs === void 0) return {
4804
+ state: "unread",
4805
+ stale: false
4806
+ };
4807
+ if (at !== void 0) return {
4808
+ state: "at",
4809
+ at,
4810
+ readAtMs,
4811
+ stale: now - readAtMs > this.expiryReadingTtlMs
4812
+ };
4813
+ if (this.creditExpiryNone.has(accountId)) return {
4814
+ state: "none",
4815
+ readAtMs,
4816
+ stale: false
4817
+ };
4818
+ return {
4819
+ state: "unread",
4820
+ stale: false
4821
+ };
4822
+ }
4490
4823
  /** Last known balance for one account, or undefined when never read. */
4491
4824
  creditsOf(accountId) {
4492
4825
  return this.creditBalances.get(accountId);
@@ -4737,6 +5070,123 @@ ${new Date(until).toISOString()}
4737
5070
  };
4738
5071
  }
4739
5072
  };
5073
+ // src/doubao-catalog.ts
5074
+ /**
5075
+ * DSH-side alias for "generate an image".
5076
+ *
5077
+ * NOT a Doubao `model_item_key` — Doubao has no model by this name. Selecting it
5078
+ * makes the shim send an ordinary chat turn with `input_skill: imageGen`, and
5079
+ * Doubao answers with Seedream. Keeping it in the catalog is what puts 生图 in
5080
+ * DSH's model picker without inventing a second UI.
5081
+ */
5082
+ const DOUBAO_IMAGE_MODEL_ID = "image-gen";
5083
+ /**
5084
+ * IMAGEGEN_LABEL_OVERLAY: 生图版本名以插件根目录的 image-models.json 为准,
5085
+ * 该文件由 doubao_imagemodels.py --sync 从服务端 get_item_conf 生成。
5086
+ */
5087
+ function imageModelLabelFromOverlay() {
5088
+ try {
5089
+ const url = new URL("../image-models.json", import.meta.url);
5090
+ const parsed = JSON.parse(readFileSync(url, "utf8"));
5091
+ return typeof parsed.label === "string" && parsed.label !== "" ? parsed.label : void 0;
5092
+ } catch {
5093
+ return;
5094
+ }
5095
+ }
5096
+ /**
5097
+ * The entries DSH may offer.
5098
+ *
5099
+ * WHY THESE ENTRIES. Doubao groups models by MODE, and the model list is per-mode:
5100
+ *
5101
+ * 对话 → 豆包 快速 (0), 豆包 2.1 Turbo·专家 (3)
5102
+ * 工作任务 → 自动 (9), 2.1 Lite (seed-lite-7b), 2.1 Pro (5), Turbo (3)
5103
+ *
5104
+ * The 「工作任务」 group (`seed-lite-7b`, `5`, `9`) runs through `Agent-GeneralTask`
5105
+ * (`mode_id: "3"`, `agent_mode: 1`) and is accompanied by an HTTP `tool_local`
5106
+ * workspace responder (`msg/ack` -> `upload_command_result` -> `msg/complete`)
5107
+ * so external turns complete without `710010702`.
5108
+ *
5109
+ * MEASURED, 2026-10-22: `model_item_key` is forwarded verbatim (the server stores
5110
+ * it on the message), but in 对话 mode it does NOT change what answers —
5111
+ * 0 / 3 / 5 / seed-lite-7b AND a deliberately bogus key all returned answers of
5112
+ * indistinguishable length and latency (12.3–14.0 s). So this list is honest
5113
+ * about what the PICKER can offer; it does not claim per-key routing.
5114
+ *
5115
+ * 「豆包 快速」 leads because it is the app's own chat-mode default, so an
5116
+ * unconfigured install reproduces the app rather than something that merely
5117
+ * happens to work.
5118
+ */
5119
+ const DOUBAO_MODELS = [
5120
+ {
5121
+ id: "0",
5122
+ name: "豆包 快速",
5123
+ reasoning: false
5124
+ },
5125
+ {
5126
+ id: "3",
5127
+ name: "豆包 2.1 Turbo",
5128
+ badge: "专家",
5129
+ reasoning: true
5130
+ },
5131
+ {
5132
+ id: "seed-lite-7b",
5133
+ name: "豆包 2.1 Lite",
5134
+ badge: "工作任务",
5135
+ reasoning: true,
5136
+ taskMode: true
5137
+ },
5138
+ {
5139
+ id: "5",
5140
+ name: "豆包 2.1 Pro",
5141
+ badge: "工作任务",
5142
+ reasoning: true,
5143
+ taskMode: true
5144
+ },
5145
+ {
5146
+ id: "9",
5147
+ name: "自动",
5148
+ badge: "工作任务",
5149
+ reasoning: true,
5150
+ taskMode: true
5151
+ },
5152
+ {
5153
+ id: DOUBAO_IMAGE_MODEL_ID,
5154
+ name: imageModelLabelFromOverlay() ?? "豆包 生图(Seedream 5.5)",
5155
+ reasoning: true
5156
+ }
5157
+ ];
5158
+ randomUUID();
5159
+ DOUBAO_MODELS.filter((model) => model.id === "0" || model.id === "3");
5160
+ Object.freeze([
5161
+ "priority",
5162
+ "round-robin",
5163
+ "balanced",
5164
+ "sticky",
5165
+ "expiry"
5166
+ ]);
5167
+ /**
5168
+ * The schedule every automation job falls back to.
5169
+ *
5170
+ * Shared by both halves on purpose. The host uses it when a configured hour
5171
+ * list arrives empty (the settings schema materializes "never configured" into
5172
+ * `[]`), and the card uses it when it writes the `automation` block back, so a
5173
+ * document that already holds an empty list is healed instead of being saved
5174
+ * back as an unrunnable schedule.
5175
+ *
5176
+ * This lives here rather than in `scheduler.ts` because the browser half cannot
5177
+ * import the host module: `scheduler.ts` pulls in `node:crypto` and the whole
5178
+ * upstream client, none of which exists in the browser bundle. Two hand-written
5179
+ * copies would drift, and the drift is invisible — the card would write a
5180
+ * schedule the scheduler does not run.
5181
+ */
5182
+ const DEFAULT_AUTOMATION_HOURS = {
5183
+ checkin: [9],
5184
+ report: [10],
5185
+ tasks: [11],
5186
+ streak: [12],
5187
+ travel: [9, 21],
5188
+ compensation: [13]
5189
+ };
4740
5190
  // src/catalog.ts
4741
5191
  /**
4742
5192
  * Model catalog with per-model credit multipliers.
@@ -5129,36 +5579,6 @@ function catalogFromUpstream(models, region = "cn") {
5129
5579
  if (models.length === 0) return fallbackModelsFor(region);
5130
5580
  return models.map(toModelInfo);
5131
5581
  }
5132
- Object.freeze([
5133
- "priority",
5134
- "round-robin",
5135
- "balanced",
5136
- "sticky",
5137
- "expiry"
5138
- ]);
5139
- /**
5140
- * The schedule every automation job falls back to.
5141
- *
5142
- * Shared by both halves on purpose. The host uses it when a configured hour
5143
- * list arrives empty (the settings schema materializes "never configured" into
5144
- * `[]`), and the card uses it when it writes the `automation` block back, so a
5145
- * document that already holds an empty list is healed instead of being saved
5146
- * back as an unrunnable schedule.
5147
- *
5148
- * This lives here rather than in `scheduler.ts` because the browser half cannot
5149
- * import the host module: `scheduler.ts` pulls in `node:crypto` and the whole
5150
- * upstream client, none of which exists in the browser bundle. Two hand-written
5151
- * copies would drift, and the drift is invisible — the card would write a
5152
- * schedule the scheduler does not run.
5153
- */
5154
- const DEFAULT_AUTOMATION_HOURS = {
5155
- checkin: [9],
5156
- report: [10],
5157
- tasks: [11],
5158
- streak: [12],
5159
- travel: [9, 21],
5160
- compensation: [13]
5161
- };
5162
5582
  // src/channels.ts
5163
5583
  /**
5164
5584
  * Mount the vendored free-channel pack.
@@ -10452,6 +10872,33 @@ function skillChain(conversationId, requestId) {
10452
10872
  }]
10453
10873
  };
10454
10874
  }
10875
+ /** Link-share events, sent only after the server created a real marketplace link. */
10876
+ function skillShareLinkChain(skill, shareCode, now = Date.now()) {
10877
+ if (!skill.id || !skill.name || !shareCode) throw new Error("skill share event requires a real skill and share code");
10878
+ const common = {
10879
+ eventCode: "skill_share_channel_action",
10880
+ skillId: skill.id,
10881
+ skillName: skill.name,
10882
+ skillType: "market",
10883
+ action: "link",
10884
+ panelType: "clipboard",
10885
+ isSuccessful: true,
10886
+ cost: 0,
10887
+ id: shareCode,
10888
+ actionAt: now
10889
+ };
10890
+ return {
10891
+ transport: "desktop",
10892
+ identity: "skill-share",
10893
+ events: [{
10894
+ ...common,
10895
+ panelAction: "click"
10896
+ }, {
10897
+ ...common,
10898
+ panelAction: "success"
10899
+ }]
10900
+ };
10901
+ }
10455
10902
  /** The theme-apply event `Hp_Appearance` is scored on. */
10456
10903
  function appearanceChain(themeKey = APPEARANCE_THEME_KEY) {
10457
10904
  return {
@@ -10644,6 +11091,8 @@ const EVENT_CHAIN_BUILDERS = {
10644
11091
  Hp_Appearance: true,
10645
11092
  Library_read: true,
10646
11093
  skill_1: true,
11094
+ skill_share: true,
11095
+ first_buddy: true,
10647
11096
  expert_5: true,
10648
11097
  Expert_team_use_3: true,
10649
11098
  Expert_lighthouse: true,
@@ -10654,6 +11103,22 @@ const EVENT_CHAIN_BUILDERS = {
10654
11103
  WorkBuddy_Valorant: true
10655
11104
  };
10656
11105
  const AUTOMATION_TICK_MS = 6e4;
11106
+ /**
11107
+ * How long after {@link WorkBuddyScheduler.start} the second kick runs.
11108
+ *
11109
+ * Long enough for the pool's first account scan to have produced credentials,
11110
+ * short enough that a user watching the card sees the jobs land right away.
11111
+ */
11112
+ const AUTOMATION_START_SETTLE_MS = 5e3;
11113
+ /**
11114
+ * How long after {@link WorkBuddyScheduler.start} an extra startup pass may run.
11115
+ * This pass never consumes a future scheduled slot.
11116
+ *
11117
+ * Long enough to cover a slow first account scan plus the six jobs running one
11118
+ * after another, short enough that an app left open all day resumes its normal
11119
+ * schedule well before the next configured hour.
11120
+ */
11121
+ const AUTOMATION_STARTUP_CATCHUP_MS = 12e4;
10657
11122
  const JOB_KINDS = [
10658
11123
  "checkin",
10659
11124
  "report",
@@ -10778,11 +11243,34 @@ function slotKey(date, timeZone = AUTOMATION_TIME_ZONE) {
10778
11243
  *
10779
11244
  * So the scope is per job, and the default for a job that is not named is `cn`:
10780
11245
  * a new job must opt in explicitly rather than inherit an accident.
11246
+ *
11247
+ * Measured against the live international gateway (`www.workbuddy.ai`,
11248
+ * 2026-11-10) rather than assumed — three of the six jobs do work there, and the
11249
+ * old comment's claim that the gateway "has no activity report and no streak
11250
+ * ladder" was simply wrong:
11251
+ *
11252
+ * - `POST /v2/report` answers 200 `{code:0}` and moves the very next
11253
+ * `GET /activity/growth/streak` read from `days: 0` to `days: 1` on an account
11254
+ * with no prior history. That is the whole daily-active credit mechanism: each
11255
+ * recorded active day grants a 30-credit `Bonus Pack` (31-day expiry, granted
11256
+ * server-side the following morning — there is no claim endpoint).
11257
+ * - `GET /activity/growth/streak` returns the same shape as CN (`streak.days`,
11258
+ * `next_tier`, and `redemption_status.tiers[].{tier,days,credit,energy,cards,
11259
+ * chances}`), so the streak ladder and its `7d/14d/28d` redemption work too.
11260
+ * - Check-in is the one thing that genuinely does not: the activity is closed
11261
+ * (`active: false`) and `daily-checkin` answers `签到活动未开启或已过期`, which
11262
+ * `isAlreadyCheckin` does not recognise — hence the misleading `failed: +1`.
11263
+ *
11264
+ * The task centre also exists (`GET /v2/activity/growth/tasks` returns five
11265
+ * tasks) but is NOT safe to enable: its entries key on numeric `task_id` + `code`
11266
+ * with no `task_code`, no `reward_credit`/`reward_energy` and no `current`/
11267
+ * `target`, so `parseTask` drops them and `tasks/accept` answers `task not found`.
11268
+ * Making that work is a parsing job with no measurable payout, so it stays off.
10781
11269
  */
10782
11270
  const JOB_REGION_SCOPE = {
10783
- report: ["cn"],
11271
+ report: ["cn", "global"],
11272
+ streak: ["cn", "global"],
10784
11273
  tasks: ["cn"],
10785
- streak: ["cn"],
10786
11274
  travel: ["cn"],
10787
11275
  compensation: ["cn"],
10788
11276
  checkin: ["cn", "global"]
@@ -10831,6 +11319,17 @@ var WorkBuddyScheduler = class {
10831
11319
  travelHours;
10832
11320
  compensationHours;
10833
11321
  timer;
11322
+ /** The one-shot kick scheduled just after `start`; cleared by `stop`. */
11323
+ settleTimer;
11324
+ /**
11325
+ * Deadline for the start-of-day window described in {@link dueSlot}.
11326
+ *
11327
+ * Zero until {@link start} sets it, so a manual `tick` before the loop starts
11328
+ * keeps the original "only past hours" behaviour.
11329
+ */
11330
+ startupCatchUpUntilMs = 0;
11331
+ /** A startup pass is extra work; it never spends a future scheduled slot. */
11332
+ startupCompleted = /* @__PURE__ */ new Set();
10834
11333
  running = false;
10835
11334
  /** Guards against a slow run overlapping the next tick. */
10836
11335
  busy = false;
@@ -10853,6 +11352,10 @@ var WorkBuddyScheduler = class {
10853
11352
  compensation: { ...EMPTY_JOB_STATE }
10854
11353
  };
10855
11354
  claimableSeen = 0;
11355
+ /** Completion failures for the latest pass, keyed by account and task. */
11356
+ eventFailures = /* @__PURE__ */ new Map();
11357
+ /** Direct rewards from first-Buddy adoption, awaiting the task summary. */
11358
+ buddyAdoptionReceipts = /* @__PURE__ */ new Map();
10856
11359
  /**
10857
11360
  * Credits/energy/tasks earned per account TODAY, keyed by account id.
10858
11361
  *
@@ -10960,6 +11463,29 @@ var WorkBuddyScheduler = class {
10960
11463
  if (this.timer !== void 0) return;
10961
11464
  this.stopped = false;
10962
11465
  this.running = true;
11466
+ /**
11467
+ * Launching DSH is itself a "run today's jobs" signal.
11468
+ *
11469
+ * `setInterval` alone delays the first pass by a whole tick, so an app
11470
+ * started at 17:57 ran every catch-up job at 17:58 and the card showed all
11471
+ * six stamped on the same minute — indistinguishable from "nothing happened
11472
+ * until I moved". Kicking the loop now, and once more shortly after, makes
11473
+ * "I started DSH" and "the automation started" the same moment.
11474
+ *
11475
+ * During this window, unrun jobs receive one extra startup pass. Past due
11476
+ * slots are consumed as normal; future slots remain scheduled.
11477
+ *
11478
+ * Both kicks are cheap no-ops when the pool has no accounts yet or the day
11479
+ * is already done: `tick` returns early on an empty pool, and `dueSlot`
11480
+ * finds nothing left to consume.
11481
+ */
11482
+ this.startupCompleted.clear();
11483
+ this.startupCatchUpUntilMs = this.now().getTime() + AUTOMATION_STARTUP_CATCHUP_MS;
11484
+ this.tick();
11485
+ this.settleTimer = setTimeout(() => {
11486
+ this.tick();
11487
+ }, AUTOMATION_START_SETTLE_MS);
11488
+ this.settleTimer.unref?.();
10963
11489
  this.timer = setInterval(() => {
10964
11490
  this.tick();
10965
11491
  }, AUTOMATION_TICK_MS);
@@ -10969,6 +11495,10 @@ var WorkBuddyScheduler = class {
10969
11495
  stop() {
10970
11496
  this.stopped = true;
10971
11497
  this.running = false;
11498
+ if (this.settleTimer !== void 0) {
11499
+ clearTimeout(this.settleTimer);
11500
+ this.settleTimer = void 0;
11501
+ }
10972
11502
  if (this.timer !== void 0) {
10973
11503
  clearInterval(this.timer);
10974
11504
  this.timer = void 0;
@@ -11100,6 +11630,8 @@ var WorkBuddyScheduler = class {
11100
11630
  * PASSED and its slot is still unconsumed, so a laptop that slept through
11101
11631
  * 10:00 still runs the job when it wakes, on the same day.
11102
11632
  *
11633
+ * Startup runs are handled separately in tick and do not spend a future slot.
11634
+ *
11103
11635
  * The EARLIEST unconsumed candidate wins, which is what keeps a two-hour job
11104
11636
  * (`travelHours: [9, 21]`) whole: consuming the earliest due slot leaves the
11105
11637
  * later one for its own hour.
@@ -11131,6 +11663,19 @@ var WorkBuddyScheduler = class {
11131
11663
  }
11132
11664
  async tick() {
11133
11665
  if (!this.enabled || this.stopped || this.busy) return;
11666
+ /**
11667
+ * Never spend a slot on an empty pool.
11668
+ *
11669
+ * The kick {@link start} fires runs within milliseconds of load, which in
11670
+ * some launches lands BEFORE the pool's first credential scan (measured: all
11671
+ * six jobs reported "0 accounts ok" while the card already listed two
11672
+ * accounts). `runJob` treats "0 eligible accounts" as a successful pass, so
11673
+ * the slot was marked consumed and the day's jobs never ran again — the
11674
+ * opposite of what the kick is for. Returning before the ledger is touched
11675
+ * leaves the slot unconsumed, so the settle kick and the regular timer pick
11676
+ * the work up as soon as the pool is ready.
11677
+ */
11678
+ if (this.pool.list().length === 0) return;
11134
11679
  this.busy = true;
11135
11680
  try {
11136
11681
  const now = this.now();
@@ -11140,8 +11685,9 @@ var WorkBuddyScheduler = class {
11140
11685
  if (this.stopped) return;
11141
11686
  if (this.states[kind].lastFiredHour === slot) continue;
11142
11687
  const consumed = this.dueSlot(kind, now);
11143
- if (consumed === void 0) continue;
11144
- await this.runJob(kind, today, consumed);
11688
+ const startup = consumed === void 0 && now.getTime() <= this.startupCatchUpUntilMs && !this.startupCompleted.has(kind);
11689
+ if (consumed === void 0 && !startup) continue;
11690
+ if (await this.runJob(kind, today, consumed, startup)) this.startupCompleted.add(kind);
11145
11691
  }
11146
11692
  } catch (error) {
11147
11693
  this.logger.warn?.("heybash-xdpool automation tick failed:", error);
@@ -11253,7 +11799,7 @@ var WorkBuddyScheduler = class {
11253
11799
  * while claiming wants the whole pool to have been lit up first. Splitting
11254
11800
  * them costs one shared wait instead of one wait per account.
11255
11801
  */
11256
- async runJob(kind, today, consumedSlot) {
11802
+ async runJob(kind, today, consumedSlot, startup = false) {
11257
11803
  const accountWord = kind === "report" ? "report" : kind;
11258
11804
  let ok = 0;
11259
11805
  let failed = 0;
@@ -11277,6 +11823,7 @@ var WorkBuddyScheduler = class {
11277
11823
  this.logger.warn?.("automation: could not probe benched accounts:", error);
11278
11824
  }
11279
11825
  const accounts = this.accountsInOrder(kind);
11826
+ if (accounts.length === 0 || this.stopped) return false;
11280
11827
  if (kind === "tasks") await this.sendEventChains(accounts);
11281
11828
  for (let index = 0; index < accounts.length; index++) {
11282
11829
  if (this.stopped) break;
@@ -11286,8 +11833,11 @@ var WorkBuddyScheduler = class {
11286
11833
  switch (kind) {
11287
11834
  case "checkin": {
11288
11835
  let alreadyDone = false;
11836
+ let activityClosed = false;
11289
11837
  try {
11290
- alreadyDone = (await this.client.fetchCheckinStatus(account.credential)).todayCheckedIn === true;
11838
+ const status = await this.client.fetchCheckinStatus(account.credential);
11839
+ alreadyDone = status.todayCheckedIn === true;
11840
+ activityClosed = status.active === false;
11291
11841
  } catch (error) {
11292
11842
  this.logger.warn?.(`automation checkin ${account.label}: status read failed, claiming anyway:`, error);
11293
11843
  }
@@ -11295,6 +11845,15 @@ var WorkBuddyScheduler = class {
11295
11845
  this.logger.info?.(`automation checkin ${account.label}: already done today (read, not claimed)`);
11296
11846
  break;
11297
11847
  }
11848
+ if (activityClosed) {
11849
+ this.logger.info?.(`automation checkin ${account.label}: no check-in activity on this gateway, skipped`);
11850
+ items.push({
11851
+ title: "每日签到",
11852
+ status: "skipped",
11853
+ note: "this gateway runs no check-in activity"
11854
+ });
11855
+ break;
11856
+ }
11298
11857
  try {
11299
11858
  const claim = await this.client.claimDailyCheckin(account.credential);
11300
11859
  this.recordEarnings(account.id, today, { checkinCredit: claim.credit });
@@ -11303,6 +11862,15 @@ var WorkBuddyScheduler = class {
11303
11862
  this.logger.info?.(`automation checkin ${account.label}: +${claim.credit} credit`);
11304
11863
  }
11305
11864
  } catch (error) {
11865
+ if (isCheckinUnavailable(error)) {
11866
+ this.logger.info?.(`automation checkin ${account.label}: no check-in activity on this gateway, skipped`);
11867
+ items.push({
11868
+ title: "每日签到",
11869
+ status: "skipped",
11870
+ note: "this gateway runs no check-in activity"
11871
+ });
11872
+ break;
11873
+ }
11306
11874
  if (!isAlreadyCheckin(error)) throw error;
11307
11875
  this.logger.info?.(`automation checkin ${account.label}: already done today`);
11308
11876
  }
@@ -11357,7 +11925,7 @@ var WorkBuddyScheduler = class {
11357
11925
  }
11358
11926
  const state = this.states[kind];
11359
11927
  if (consumedSlot !== void 0) this.consumeSlot(kind, consumedSlot);
11360
- state.lastFiredHour = slotKey(this.now());
11928
+ if (!startup) state.lastFiredHour = slotKey(this.now());
11361
11929
  state.lastRunDate = today;
11362
11930
  state.lastRunAtMs = this.now().getTime();
11363
11931
  state.ok = ok;
@@ -11372,6 +11940,7 @@ var WorkBuddyScheduler = class {
11372
11940
  else state.progress = progressNote;
11373
11941
  this.logger.info?.(`automation ${accountWord}: ${state.message}`);
11374
11942
  if (kind === "tasks" || kind === "checkin" || kind === "streak" || kind === "travel" || kind === "compensation") await this.flushEarnings();
11943
+ return true;
11375
11944
  }
11376
11945
  /** Compose the one-line summary shown on the card. */
11377
11946
  summarise(kind, ok, failed, claimed, credit, energy) {
@@ -11419,6 +11988,7 @@ var WorkBuddyScheduler = class {
11419
11988
  let sentAnything = false;
11420
11989
  for (const account of accounts) {
11421
11990
  if (this.stopped) return;
11991
+ this.eventFailures.delete(account.id);
11422
11992
  let tasks;
11423
11993
  try {
11424
11994
  tasks = await this.client.listTasks(account.credential);
@@ -11426,14 +11996,28 @@ var WorkBuddyScheduler = class {
11426
11996
  this.logger.warn?.(`automation events ${account.label}: list failed:`, error);
11427
11997
  continue;
11428
11998
  }
11429
- const pending = tasks.filter((task) => task.taskCode in EVENT_CHAIN_BUILDERS && !task.claimable && !task.locked);
11999
+ const pending = tasks.filter((task) => Object.hasOwn(EVENT_CHAIN_BUILDERS, task.taskCode) && !task.claimed && !task.claimable && !task.locked);
11430
12000
  for (const task of pending) {
11431
12001
  if (this.stopped) return;
11432
12002
  let chains;
11433
12003
  try {
12004
+ if (task.taskCode === "first_buddy") {
12005
+ if (await this.completeFirstBuddy(account)) sentAnything = true;
12006
+ continue;
12007
+ }
12008
+ if (task.taskCode === "skill_share" && task.acceptStatus === "not_accepted") {
12009
+ await this.client.acceptTasks(account.credential, [task.taskCode]);
12010
+ const updated = (await this.client.listTasks(account.credential)).find((row) => row.taskCode === task.taskCode);
12011
+ if (updated === void 0 || updated.acceptStatus === "not_accepted" || updated.acceptStatus === "" || updated.locked) throw new Error("skill_share task was not accepted");
12012
+ if (updated.claimed || updated.claimable) continue;
12013
+ }
11434
12014
  chains = await this.chainsFor(task, account.credential);
11435
12015
  } catch (error) {
11436
- this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} could not be built:`, error);
12016
+ const failed = this.eventFailures.get(account.id) ?? /* @__PURE__ */ new Set();
12017
+ failed.add(task.taskCode);
12018
+ this.eventFailures.set(account.id, failed);
12019
+ if (task.taskCode === "skill_share") this.logger.warn?.(`automation events ${account.label}: skill_share failed`);
12020
+ else this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} could not be built:`, error);
11437
12021
  continue;
11438
12022
  }
11439
12023
  for (const chain of chains) {
@@ -11443,7 +12027,11 @@ var WorkBuddyScheduler = class {
11443
12027
  this.logger.info?.(`automation events ${account.label}: ${task.taskCode} chain sent`);
11444
12028
  sentAnything = true;
11445
12029
  } catch (error) {
11446
- this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} failed:`, error);
12030
+ const failed = this.eventFailures.get(account.id) ?? /* @__PURE__ */ new Set();
12031
+ failed.add(task.taskCode);
12032
+ this.eventFailures.set(account.id, failed);
12033
+ if (task.taskCode === "skill_share") this.logger.warn?.(`automation events ${account.label}: skill_share report failed`);
12034
+ else this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} failed:`, error);
11447
12035
  break;
11448
12036
  }
11449
12037
  if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
@@ -11452,6 +12040,20 @@ var WorkBuddyScheduler = class {
11452
12040
  }
11453
12041
  if (sentAnything && this.eventScoreWaitMs > 0 && !this.stopped) await sleep(this.eventScoreWaitMs);
11454
12042
  }
12043
+ /** Adopt only when the account truly lacks a Buddy; verify after the write. */
12044
+ async completeFirstBuddy(account) {
12045
+ const credential = account.credential;
12046
+ if (await this.client.buddyInfo(credential) !== void 0) return false;
12047
+ await this.client.reportDesktopEvents(credential, [{
12048
+ eventCode: "buddy_agreement_view",
12049
+ timestamp: Date.now()
12050
+ }]);
12051
+ await this.client.buddyAgree(credential);
12052
+ const receipt = await this.client.buddyAdoptFirst(credential);
12053
+ if (receipt && (receipt.credit > 0 || receipt.energy > 0)) this.buddyAdoptionReceipts.set(account.id, receipt);
12054
+ if (await this.client.buddyInfo(credential) === void 0) throw new Error("first_buddy adoption was not confirmed");
12055
+ return true;
12056
+ }
11455
12057
  /**
11456
12058
  * Send one chain on the channel it was built for.
11457
12059
  *
@@ -11466,7 +12068,7 @@ var WorkBuddyScheduler = class {
11466
12068
  await this.client.reportWebEvent(credential, web.eventCode, web.pageUrl, web.elementId, web.elementName);
11467
12069
  return;
11468
12070
  }
11469
- await this.client.reportDesktopEvents(credential, chain.events ?? []);
12071
+ await this.client.reportDesktopEvents(credential, chain.events ?? [], chain.identity);
11470
12072
  }
11471
12073
  /**
11472
12074
  * Build every chain that scores one task.
@@ -11490,6 +12092,11 @@ var WorkBuddyScheduler = class {
11490
12092
  if (this.delayMs > 0 && !this.stopped) await sleep(2e3);
11491
12093
  return [appearanceChain()];
11492
12094
  case "Library_read": return [libraryReadChain()];
12095
+ case "skill_share": {
12096
+ const skill = (await this.client.shareableSkills(credential))[0];
12097
+ if (skill === void 0) throw new Error("skill_share: no public marketplace skill available");
12098
+ return [skillShareLinkChain(skill, (await this.client.createSkillShareLink(credential, skill)).shareCode)];
12099
+ }
11493
12100
  case "skill_1": {
11494
12101
  const chat = await this.client.openConversation(credential);
11495
12102
  if (chat === void 0) throw new Error("skill_1: no server conversation");
@@ -11653,16 +12260,38 @@ var WorkBuddyScheduler = class {
11653
12260
  if (open.length > 0) await this.client.acceptTasks(credential, open);
11654
12261
  const refreshed = await this.client.listTasks(credential);
11655
12262
  const claimable = refreshed.filter((task) => task.claimable && !task.locked);
11656
- let credit = 0;
11657
- let energy = 0;
11658
- let claimed = 0;
12263
+ const adoption = this.buddyAdoptionReceipts.get(account.id);
12264
+ let credit = adoption?.credit ?? 0;
12265
+ let energy = adoption?.energy ?? 0;
12266
+ let claimed = adoption === void 0 ? 0 : 1;
11659
12267
  const titles = [];
11660
12268
  const items = [];
11661
- for (const task of refreshed) if (task.locked === true || task.claimable !== true) items.push({
11662
- title: task.title === "" ? task.taskCode : task.title,
11663
- status: "skipped",
11664
- note: task.locked === true ? "locked" : task.acceptStatus === "not_accepted" ? "not accepted" : "not scored yet"
12269
+ if (adoption !== void 0) items.push({
12270
+ title: "Buddy 领养奖励",
12271
+ status: "claimed",
12272
+ ...adoption.credit > 0 ? { credit: adoption.credit } : {},
12273
+ ...adoption.energy > 0 ? { energy: adoption.energy } : {}
11665
12274
  });
12275
+ for (const task of refreshed) {
12276
+ const title = task.title === "" ? task.taskCode : task.title;
12277
+ if (task.claimed) items.push({
12278
+ title,
12279
+ status: "already"
12280
+ });
12281
+ else if (!task.claimable && this.eventFailures.get(account.id)?.has(task.taskCode)) items.push({
12282
+ title,
12283
+ status: "failed",
12284
+ note: "automatic completion failed"
12285
+ });
12286
+ else if (task.locked || !task.claimable) {
12287
+ const note = task.locked ? "locked" : task.acceptStatus === "not_accepted" ? "not accepted" : Object.hasOwn(EVENT_CHAIN_BUILDERS, task.taskCode) ? "not scored yet" : "not covered by automation";
12288
+ items.push({
12289
+ title,
12290
+ status: "skipped",
12291
+ note
12292
+ });
12293
+ }
12294
+ }
11666
12295
  for (const task of claimable) {
11667
12296
  if (this.stopped) break;
11668
12297
  const reward = await this.client.claimTaskReward(credential, task.taskCode);
@@ -11688,6 +12317,7 @@ var WorkBuddyScheduler = class {
11688
12317
  }
11689
12318
  if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
11690
12319
  }
12320
+ this.buddyAdoptionReceipts.delete(account.id);
11691
12321
  return {
11692
12322
  claimed,
11693
12323
  credit,