dsh-workbuddy-xdpool 1.0.0 → 1.1.0

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
@@ -286,6 +286,50 @@ function parseUpstreamModel(value) {
286
286
  ...supportsImages === void 0 ? {} : { supportsImages }
287
287
  };
288
288
  }
289
+ /**
290
+ * Flatten one upstream task entry.
291
+ *
292
+ * Progress is reported two ways depending on the task: flat `current`/`target`
293
+ * fields, or a nested `progress: {current, target}`. The nested form wins when
294
+ * it carries anything, because a task that reports both puts the live counter
295
+ * there. Entries without a usable `task_code` are dropped — without one the
296
+ * claim path cannot be built.
297
+ */
298
+ function parseTask(value) {
299
+ if (typeof value !== "object" || value === null) return void 0;
300
+ const raw = value;
301
+ const taskCode = typeof raw["task_code"] === "string" ? raw["task_code"] : "";
302
+ if (taskCode === "") return void 0;
303
+ const num = (key) => typeof raw[key] === "number" ? raw[key] : 0;
304
+ let current = num("current");
305
+ let target = num("target");
306
+ const progress = raw["progress"];
307
+ if (typeof progress === "object" && progress !== null) {
308
+ const nested = progress;
309
+ const nestedCurrent = typeof nested["current"] === "number" ? nested["current"] : 0;
310
+ const nestedTarget = typeof nested["target"] === "number" ? nested["target"] : 0;
311
+ if (nestedTarget > 0 || nestedCurrent > 0) {
312
+ current = nestedCurrent;
313
+ target = nestedTarget;
314
+ }
315
+ }
316
+ const acceptStatus = typeof raw["accept_status"] === "string" ? raw["accept_status"] : "";
317
+ const claimed = acceptStatus === "claimed";
318
+ return {
319
+ taskCode,
320
+ title: typeof raw["title"] === "string" && raw["title"] !== "" ? raw["title"] : taskCode,
321
+ credit: num("reward_credit"),
322
+ energy: num("reward_energy"),
323
+ hasReward: raw["has_reward"] === true,
324
+ target,
325
+ current,
326
+ acceptStatus,
327
+ status: typeof raw["status"] === "string" ? raw["status"] : "",
328
+ claimable: !claimed && target > 0 && current >= target,
329
+ claimed,
330
+ locked: raw["locked"] === true
331
+ };
332
+ }
289
333
  var WorkBuddyUpstreamClient = class {
290
334
  fetchImpl;
291
335
  clientVersion;
@@ -562,6 +606,100 @@ var WorkBuddyUpstreamClient = class {
562
606
  isStreakDay: data["is_streak_day"] === true
563
607
  };
564
608
  }
609
+ /**
610
+ * Report one chat-activity event to the growth system.
611
+ *
612
+ * The body is an ARRAY holding a single `chat_request_send` event, and every
613
+ * field is filled in: a three-field minimal event is accepted with 200 and
614
+ * then silently dropped, so the full shape is load-bearing rather than
615
+ * cosmetic. `userId` is the one field the server actually keys on — without
616
+ * it the request still answers 200 and scores nothing.
617
+ *
618
+ * One report per account per day is the quota the reference panel settled on;
619
+ * a single report lights the growth streak and unlocks the `first_buddy`
620
+ * family, which is why this runs before the task-centre pass.
621
+ */
622
+ async reportActivity(credential, conversationId) {
623
+ const conversationID = conversationId ?? `wb2api-${Date.now()}`;
624
+ const requestID = conversationID;
625
+ const now = Date.now();
626
+ const event = {
627
+ eventCode: "chat_request_send",
628
+ timestamp: now,
629
+ reportDelay: 0,
630
+ mode: "craft",
631
+ conversationId: conversationID,
632
+ requestId: requestID,
633
+ inputLength: 12,
634
+ requestModelId: "deepseek-v4-flash",
635
+ requestModelName: "DeepSeek V4 Flash",
636
+ isPlan: false,
637
+ isAutoExecuteTerminal: false,
638
+ isAutoModify: false,
639
+ codebaseEnable: false,
640
+ maxToken: 0,
641
+ maxSteps: 0,
642
+ temperature: 0,
643
+ maxRetries: 0,
644
+ mentionContexts: [],
645
+ knowledgeId: [],
646
+ knowledgeName: [],
647
+ codebaseId: "",
648
+ mentionContextCount: 0,
649
+ command: "",
650
+ expertId: "",
651
+ recommendId: "",
652
+ skillId: "",
653
+ skillCount: 0,
654
+ totalCount: 0,
655
+ fileUri: "",
656
+ presentAt: now,
657
+ traceId: "",
658
+ rootRequestId: requestID,
659
+ parentConversationId: conversationID,
660
+ agentName: "default",
661
+ agentType: "conversation",
662
+ userId: credential.uid ?? ""
663
+ };
664
+ const response = await this.fetchImpl(`${billingBase(credential)}/v2/report`, {
665
+ method: "POST",
666
+ headers: billingHeaders(credential),
667
+ body: JSON.stringify([event]),
668
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
669
+ });
670
+ const envelope = await readEnvelope(response);
671
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
672
+ }
673
+ /**
674
+ * Read back the growth streak in days.
675
+ *
676
+ * This is the read-only oracle for {@link reportActivity}: a report that
677
+ * returned 200 yet left the streak untouched was silently dropped (a missing
678
+ * `userId` is the usual cause), so callers verify instead of trusting the
679
+ * status code.
680
+ *
681
+ * Two shape traps, both measured against the live upstream:
682
+ *
683
+ * - The path carries NO `/v2` prefix, unlike its sibling task endpoints under
684
+ * `/v2/activity/growth/*`. Asking for the `/v2` form does not 404; it
685
+ * answers with a body that carries no `streak` object at all.
686
+ * - The counter is nested as `data.streak.days`, not `data.days`. Reading the
687
+ * flat field yields a constant 0, which would make every successful report
688
+ * look like a silent drop.
689
+ *
690
+ * Returns 0 only when the field is genuinely absent.
691
+ */
692
+ async growthStreakDays(credential) {
693
+ const response = await this.fetchImpl(`${chatBase(credential)}/activity/growth/streak`, {
694
+ headers: billingHeaders(credential),
695
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
696
+ });
697
+ const envelope = await readEnvelope(response);
698
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
699
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
700
+ const streak = typeof data["streak"] === "object" && data["streak"] !== null ? data["streak"] : {};
701
+ return typeof streak["days"] === "number" ? streak["days"] : 0;
702
+ }
565
703
  /** Legacy thin wrapper kept for `status`/`doctor`: returns raw envelope data. */
566
704
  async credits(credential) {
567
705
  try {
@@ -576,6 +714,87 @@ var WorkBuddyUpstreamClient = class {
576
714
  };
577
715
  }
578
716
  }
717
+ /**
718
+ * Fetch the growth task list for one account.
719
+ *
720
+ * The upstream answers `data.tasks[]`, and `claimable` is derived locally —
721
+ * the upstream does not mark it. Only a task whose progress reached its
722
+ * target and that is not already claimed counts as eligible.
723
+ */
724
+ async listTasks(credential) {
725
+ const response = await this.fetchImpl(`${chatBase(credential)}/v2/activity/growth/tasks`, {
726
+ headers: chatHeaders(credential),
727
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
728
+ });
729
+ const envelope = await readEnvelope(response);
730
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
731
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
732
+ const raw = Array.isArray(data["tasks"]) ? data["tasks"] : [];
733
+ const out = [];
734
+ for (const entry of raw) {
735
+ const parsed = parseTask(entry);
736
+ if (parsed !== void 0) out.push(parsed);
737
+ }
738
+ return out;
739
+ }
740
+ /**
741
+ * Accept (enrol in) tasks by code.
742
+ *
743
+ * Accepting is the "sign up" half: it produces no progress by itself, and the
744
+ * upstream answers success for an already-accepted task, so replaying this is
745
+ * safe. Progress is lit by real activity (a chat, an activity report).
746
+ */
747
+ async acceptTasks(credential, taskCodes) {
748
+ if (taskCodes.length === 0) return;
749
+ const response = await this.fetchImpl(`${chatBase(credential)}/v2/activity/growth/tasks/accept`, {
750
+ method: "POST",
751
+ headers: chatHeaders(credential),
752
+ body: JSON.stringify({ task_codes: [...taskCodes] }),
753
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
754
+ });
755
+ const envelope = await readEnvelope(response);
756
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
757
+ }
758
+ /**
759
+ * Claim one task's reward.
760
+ *
761
+ * Two details differ from list/accept and are load-bearing:
762
+ *
763
+ * - The task code rides the PATH, not the body.
764
+ * - It is served by the web origin, not the chat host, and only when the
765
+ * request carries the growth-centre Origin/Referer plus
766
+ * `x-client-platform: web`. The chat host's `/reward/claim` path does not
767
+ * exist and answers 400 "task not completed".
768
+ *
769
+ * A repeat claim answers `already_claimed` with zero credit, which is treated
770
+ * as success so the caller can stay idempotent.
771
+ */
772
+ async claimTaskReward(credential, taskCode) {
773
+ const headers = {
774
+ ...billingHeaders(credential),
775
+ "Accept": "application/json, text/plain, */*",
776
+ "Origin": "https://www.workbuddy.cn",
777
+ "Referer": "https://www.workbuddy.cn/profile/growth-center",
778
+ "x-client-platform": "web",
779
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
780
+ };
781
+ const response = await this.fetchImpl(`https://www.workbuddy.cn/activity/growth/tasks/${encodeURIComponent(taskCode)}/claim`, {
782
+ method: "POST",
783
+ headers,
784
+ signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
785
+ });
786
+ const envelope = await readEnvelope(response);
787
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
788
+ const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
789
+ if (data["already_claimed"] === true) return {
790
+ credit: 0,
791
+ energy: 0
792
+ };
793
+ return {
794
+ credit: typeof data["credit"] === "number" ? data["credit"] : 0,
795
+ energy: typeof data["energy"] === "number" ? data["energy"] : 0
796
+ };
797
+ }
579
798
  };
580
799
  //#endregion
581
800
  //#region src/accounts.ts
@@ -778,10 +997,18 @@ function idleWeight(lastUsedAt, now) {
778
997
  const hours = (now - lastUsedAt) / 36e5;
779
998
  return 1 + Math.min(Math.max(hours, 0) * IDLE_WEIGHT_PER_HOUR, IDLE_WEIGHT_MAX);
780
999
  }
1000
+ /** Default rest for an account whose credits ran out (packs reset on their own schedule). */
1001
+ const EXHAUST_COOLDOWN_MS = 18e5;
781
1002
  var WorkBuddyAccountPool = class {
782
1003
  logger;
783
1004
  authDirs;
784
1005
  cooldownMs;
1006
+ /**
1007
+ * How long an account stays out of rotation after the upstream reports its
1008
+ * credits are spent. Credit packs reset on their own schedule rather than on a
1009
+ * rate-limit window, so this is much longer than `cooldownMs`.
1010
+ */
1011
+ exhaustCooldownMs;
785
1012
  client;
786
1013
  refreshMarginMs;
787
1014
  accounts = [];
@@ -813,6 +1040,7 @@ var WorkBuddyAccountPool = class {
813
1040
  this.logger = options.logger;
814
1041
  this.authDirs = options.authDirs ?? candidateAuthDirs();
815
1042
  this.cooldownMs = options.cooldownMs ?? 6e4;
1043
+ this.exhaustCooldownMs = options.exhaustCooldownMs ?? EXHAUST_COOLDOWN_MS;
816
1044
  this.client = options.client;
817
1045
  this.refreshMarginMs = options.refreshMarginMs ?? 3e5;
818
1046
  this.distribution = options.distribution ?? "priority";
@@ -825,6 +1053,7 @@ var WorkBuddyAccountPool = class {
825
1053
  applyConfig(options) {
826
1054
  if (options.authDirs !== void 0 && options.authDirs.length > 0) this.authDirs = options.authDirs;
827
1055
  if (options.cooldownMs !== void 0 && options.cooldownMs >= 1e3) this.cooldownMs = options.cooldownMs;
1056
+ if (options.exhaustCooldownMs !== void 0 && options.exhaustCooldownMs >= 1e3) this.exhaustCooldownMs = options.exhaustCooldownMs;
828
1057
  if (options.distribution !== void 0) this.distribution = options.distribution;
829
1058
  if (options.disabledAccountIds !== void 0) this.disabledIds = new Set(options.disabledAccountIds);
830
1059
  }
@@ -951,14 +1180,12 @@ var WorkBuddyAccountPool = class {
951
1180
  if (this.preferredId !== void 0) {
952
1181
  const preferred = pool.find((account) => account.id === this.preferredId);
953
1182
  if (preferred !== void 0) {
954
- this.lastUsedAt.set(preferred.id, Date.now());
955
1183
  await this.ensureFresh(preferred);
956
1184
  return preferred;
957
1185
  }
958
1186
  }
959
1187
  const account = this.distribution === "round-robin" ? this.pickRoundRobin(pool) : this.distribution === "balanced" ? this.pickByWeight(pool) : pool[0];
960
1188
  if (account === void 0) return void 0;
961
- this.lastUsedAt.set(account.id, Date.now());
962
1189
  await this.ensureFresh(account);
963
1190
  return account;
964
1191
  }
@@ -978,6 +1205,40 @@ var WorkBuddyAccountPool = class {
978
1205
  disabledIdsInOrder() {
979
1206
  return this.accounts.filter((account) => this.disabledIds.has(account.id)).map((account) => account.id);
980
1207
  }
1208
+ /**
1209
+ * Record that an account actually served a request.
1210
+ *
1211
+ * Called by the shim once the upstream answers 200 — only then is the account
1212
+ * the one the user is really being served by. `balanced` mode reads the same map
1213
+ * for its idle weighting, so a request that failed over to another account must
1214
+ * not count as used for the account that was merely tried.
1215
+ */
1216
+ noteServed(accountId) {
1217
+ if (!this.accounts.some((account) => account.id === accountId)) return;
1218
+ this.lastUsedAt.set(accountId, Date.now());
1219
+ }
1220
+ /**
1221
+ * The account that served the most recent request, if any.
1222
+ *
1223
+ * Distinct from "who would serve the next one": this is a record of what
1224
+ * actually happened, which is what the card needs to answer "which account am
1225
+ * I using right now?". Under `balanced` there is no deterministic next account
1226
+ * at all, so a recorded fact is the only honest answer.
1227
+ *
1228
+ * Returns undefined before the first request of the process, and after every
1229
+ * known account has been re-scanned away (a login swapped out under us).
1230
+ */
1231
+ lastServedId() {
1232
+ let newest;
1233
+ for (const [id, at] of this.lastUsedAt) {
1234
+ if (!this.accounts.some((account) => account.id === id)) continue;
1235
+ if (newest === void 0 || at > newest.at) newest = {
1236
+ id,
1237
+ at
1238
+ };
1239
+ }
1240
+ return newest?.id;
1241
+ }
981
1242
  /** Best-effort refresh of one account after a session-dead upstream answer. */
982
1243
  async refreshAccount(accountId) {
983
1244
  const account = this.accounts.find((item) => item.id === accountId);
@@ -1028,6 +1289,23 @@ var WorkBuddyAccountPool = class {
1028
1289
  }
1029
1290
  }
1030
1291
  /**
1292
+ * Cool a whole account after the upstream reports its credits are spent.
1293
+ *
1294
+ * Credit exhaustion is an ACCOUNT condition, unlike a model rate limit: every
1295
+ * model on that account is unusable until the quota resets, so this cools the
1296
+ * account as a whole (no `modelId`) for the configured exhaustion window. The
1297
+ * shim then rotates to a different account instead of failing the request.
1298
+ */
1299
+ penalizeExhausted(accountId) {
1300
+ const until = Date.now() + this.exhaustCooldownMs;
1301
+ this.penalize(accountId, until);
1302
+ this.logger?.warn(`
1303
+ dsh-workbuddy-xdpool: account credits exhausted; cooling the whole account until
1304
+
1305
+ ${new Date(until).toISOString()}
1306
+ `);
1307
+ }
1308
+ /**
1031
1309
  * Mark an account (or one of its models) rate-limited.
1032
1310
  *
1033
1311
  * With `modelId`, only that model on the account is cooled — the account's
@@ -1225,6 +1503,311 @@ function catalogFromUpstream(models) {
1225
1503
  if (models.length === 0) return FALLBACK_WORKBUDDY_MODELS;
1226
1504
  return models.map(toModelInfo);
1227
1505
  }
1506
+ /** How often the loop wakes to look for a due job. */
1507
+ const AUTOMATION_TICK_MS = 6e4;
1508
+ const JOB_KINDS = [
1509
+ "checkin",
1510
+ "report",
1511
+ "tasks",
1512
+ "streak"
1513
+ ];
1514
+ const EMPTY_JOB_STATE = {
1515
+ ok: 0,
1516
+ failed: 0,
1517
+ credit: 0,
1518
+ energy: 0,
1519
+ claimed: 0
1520
+ };
1521
+ /** `YYYY-MM-DD` in local time, the day key every job resets on. */
1522
+ function dayKey(date) {
1523
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1524
+ const day = String(date.getDate()).padStart(2, "0");
1525
+ return `${date.getFullYear()}-${month}-${day}`;
1526
+ }
1527
+ /**
1528
+ * Whether `now`'s local hour is one of `hours`.
1529
+ *
1530
+ * The reference panel computes a `nextFire` instant and sleeps until it; this
1531
+ * loop instead wakes every minute and asks "is any job due now". Both fire at
1532
+ * the top of a configured hour, but the polling form cannot miss a slot to a
1533
+ * suspended process — a laptop that slept through 10:00 still runs the job the
1534
+ * moment it wakes, on the same day.
1535
+ */
1536
+ function isFireHour(now, hours) {
1537
+ return hours.includes(now.getHours());
1538
+ }
1539
+ /** Whether this account may be used: not switched off, not cooling. */
1540
+ function eligible(account, now) {
1541
+ if (account.cooldownUntilMs > now) return false;
1542
+ if (regionOf(account.credential.domain) === "global") return false;
1543
+ return true;
1544
+ }
1545
+ const sleep = (ms) => new Promise((resolve) => {
1546
+ setTimeout(resolve, ms);
1547
+ });
1548
+ /**
1549
+ * The points automation.
1550
+ *
1551
+ * Owns a single timer loop. Construction is inert — nothing runs until
1552
+ * {@link start}, and {@link stop} is idempotent so a plugin teardown that fires
1553
+ * twice is harmless.
1554
+ */
1555
+ var WorkBuddyScheduler = class {
1556
+ pool;
1557
+ client;
1558
+ logger;
1559
+ now;
1560
+ delayMs;
1561
+ enabled;
1562
+ checkinHours;
1563
+ taskHours;
1564
+ reportHours;
1565
+ streakHours;
1566
+ timer;
1567
+ running = false;
1568
+ /** Guards against a slow run overlapping the next tick. */
1569
+ busy = false;
1570
+ /**
1571
+ * Set once {@link stop} is called.
1572
+ *
1573
+ * Deliberately false before `start`: the loop is not running yet, but a
1574
+ * manual `tick` must still work. `stop` is what makes a run abandon the
1575
+ * accounts it has not reached yet.
1576
+ */
1577
+ stopped = false;
1578
+ states = {
1579
+ checkin: { ...EMPTY_JOB_STATE },
1580
+ report: { ...EMPTY_JOB_STATE },
1581
+ tasks: { ...EMPTY_JOB_STATE },
1582
+ streak: { ...EMPTY_JOB_STATE }
1583
+ };
1584
+ claimableSeen = 0;
1585
+ constructor(pool, client, options = {}) {
1586
+ this.pool = pool;
1587
+ this.client = client;
1588
+ this.logger = options.logger ?? {};
1589
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
1590
+ this.delayMs = options.accountDelayMs ?? 800;
1591
+ this.enabled = options.enabled ?? false;
1592
+ this.checkinHours = options.checkinHours ?? [9];
1593
+ this.reportHours = options.reportHours ?? [10];
1594
+ this.taskHours = options.taskHours ?? [11];
1595
+ this.streakHours = options.streakHours ?? [12];
1596
+ }
1597
+ /** Apply a new configuration; safe to call while running. */
1598
+ applyConfig(options) {
1599
+ if (options.enabled !== void 0) this.enabled = options.enabled;
1600
+ if (options.checkinHours !== void 0) this.checkinHours = options.checkinHours;
1601
+ if (options.reportHours !== void 0) this.reportHours = options.reportHours;
1602
+ if (options.taskHours !== void 0) this.taskHours = options.taskHours;
1603
+ if (options.streakHours !== void 0) this.streakHours = options.streakHours;
1604
+ }
1605
+ /** Hours for one job, used by the loop and the status document. */
1606
+ hoursOf(kind) {
1607
+ switch (kind) {
1608
+ case "checkin": return this.checkinHours;
1609
+ case "report": return this.reportHours;
1610
+ case "tasks": return this.taskHours;
1611
+ case "streak": return this.streakHours;
1612
+ }
1613
+ }
1614
+ /** Start the loop. Idempotent. */
1615
+ start() {
1616
+ if (this.timer !== void 0) return;
1617
+ this.stopped = false;
1618
+ this.running = true;
1619
+ this.timer = setInterval(() => {
1620
+ this.tick();
1621
+ }, AUTOMATION_TICK_MS);
1622
+ this.timer.unref?.();
1623
+ }
1624
+ /** Stop the loop. Idempotent, and safe before `start`. */
1625
+ stop() {
1626
+ this.stopped = true;
1627
+ this.running = false;
1628
+ if (this.timer !== void 0) {
1629
+ clearInterval(this.timer);
1630
+ this.timer = void 0;
1631
+ }
1632
+ }
1633
+ /** Snapshot for the status document. */
1634
+ status() {
1635
+ const jobs = {};
1636
+ for (const kind of JOB_KINDS) jobs[kind] = { ...this.states[kind] };
1637
+ return {
1638
+ enabled: this.enabled,
1639
+ running: this.running,
1640
+ checkinHours: this.checkinHours,
1641
+ taskHours: this.taskHours,
1642
+ reportHours: this.reportHours,
1643
+ streakHours: this.streakHours,
1644
+ jobs,
1645
+ claimableSeen: this.claimableSeen
1646
+ };
1647
+ }
1648
+ /**
1649
+ * One poll: run every due job, serially.
1650
+ *
1651
+ * Serial by design — the jobs share the same accounts and the upstream
1652
+ * rate-limits per account, so overlapping passes would only trip that limit.
1653
+ * A job that throws is recorded and the loop continues.
1654
+ */
1655
+ async tick() {
1656
+ if (!this.enabled || this.stopped || this.busy) return;
1657
+ this.busy = true;
1658
+ try {
1659
+ const now = this.now();
1660
+ const today = dayKey(now);
1661
+ for (const kind of JOB_KINDS) {
1662
+ if (this.stopped) return;
1663
+ if (this.states[kind].lastRunDate === today) continue;
1664
+ if (!isFireHour(now, this.hoursOf(kind))) continue;
1665
+ await this.runJob(kind, today);
1666
+ }
1667
+ } catch (error) {
1668
+ this.logger.warn?.("dsh-workbuddy-xdpool automation tick failed:", error);
1669
+ } finally {
1670
+ this.busy = false;
1671
+ }
1672
+ }
1673
+ /** Run one job against every eligible account and record the outcome. */
1674
+ async runJob(kind, today) {
1675
+ const accountWord = kind === "report" ? "report" : kind;
1676
+ let ok = 0;
1677
+ let failed = 0;
1678
+ let credit = 0;
1679
+ let energy = 0;
1680
+ let claimed = 0;
1681
+ const accounts = this.accountsInOrder();
1682
+ for (let index = 0; index < accounts.length; index++) {
1683
+ if (this.stopped) break;
1684
+ const account = accounts[index];
1685
+ if (account === void 0) continue;
1686
+ try {
1687
+ switch (kind) {
1688
+ case "checkin":
1689
+ await this.client.claimDailyCheckin(account.credential);
1690
+ break;
1691
+ case "report": {
1692
+ const days = await this.reportOne(account);
1693
+ this.logger.info?.(`automation report ${account.label}: streak days=${days}`);
1694
+ break;
1695
+ }
1696
+ case "tasks": {
1697
+ const result = await this.runTasks(account);
1698
+ credit += result.credit;
1699
+ energy += result.energy;
1700
+ claimed += result.claimed;
1701
+ this.claimableSeen += result.claimableCount;
1702
+ this.logger.info?.(`automation tasks ${account.label}: ${result.claimed} claimed (+${result.credit} credit, +${result.energy} energy, ${result.claimableCount} claimable seen)`);
1703
+ break;
1704
+ }
1705
+ case "streak": await this.redeemStreak(account);
1706
+ }
1707
+ ok++;
1708
+ } catch (error) {
1709
+ failed++;
1710
+ this.logger.warn?.(`automation ${accountWord} ${account.label} failed:`, error);
1711
+ }
1712
+ if (index < accounts.length - 1 && this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
1713
+ }
1714
+ const state = this.states[kind];
1715
+ state.lastRunDate = today;
1716
+ state.lastRunAtMs = this.now().getTime();
1717
+ state.ok = ok;
1718
+ state.failed = failed;
1719
+ state.credit = credit;
1720
+ state.energy = energy;
1721
+ state.claimed = claimed;
1722
+ state.message = this.summarise(kind, ok, failed, claimed, credit, energy);
1723
+ this.logger.info?.(`automation ${accountWord}: ${state.message}`);
1724
+ }
1725
+ /** Compose the one-line summary shown on the card. */
1726
+ summarise(kind, ok, failed, claimed, credit, energy) {
1727
+ if (kind === "tasks") return `${ok} accounts, ${claimed} tasks claimed (+${credit} credit, +${energy} energy)${failed > 0 ? `, ${failed} failed` : ""}`;
1728
+ return `${ok} accounts ok${failed > 0 ? `, ${failed} failed` : ""}`;
1729
+ }
1730
+ /**
1731
+ * Accounts to run against, in pool order.
1732
+ *
1733
+ * Disabled accounts are excluded here rather than filtered by the caller so a
1734
+ * card switch takes effect on the next pass without any event plumbing.
1735
+ */
1736
+ accountsInOrder() {
1737
+ const now = Date.now();
1738
+ return this.pool.list().filter((account) => {
1739
+ if (this.pool.isDisabled(account.id)) return false;
1740
+ return eligible(account, now);
1741
+ });
1742
+ }
1743
+ /**
1744
+ * Send one activity report, then verify it landed.
1745
+ *
1746
+ * The upstream answers 200 even when it drops the event, so the streak is
1747
+ * read back as the oracle: `days > 0` means it counted. A failed read-back is
1748
+ * logged and treated as a suspicious result, never as a retry — the report is
1749
+ * idempotent per day, and hammering it is exactly what the one-a-day quota
1750
+ * exists to avoid.
1751
+ */
1752
+ async reportOne(account) {
1753
+ await this.client.reportActivity(account.credential);
1754
+ try {
1755
+ const days = await this.client.growthStreakDays(account.credential);
1756
+ if (days === 0) this.logger.warn?.(`automation report ${account.label}: streak days=0 right after report (new account or scoring lag?)`);
1757
+ return days;
1758
+ } catch (error) {
1759
+ this.logger.warn?.(`automation report ${account.label}: streak read-back failed:`, error);
1760
+ return -1;
1761
+ }
1762
+ }
1763
+ /**
1764
+ * The task-centre pass for one account.
1765
+ *
1766
+ * Order matters: enrich first (enrol in everything open), then claim. Both
1767
+ * halves are idempotent — accepting an already-accepted task succeeds, and a
1768
+ * repeat claim answers `already_claimed` — so a pass that dies halfway is
1769
+ * safe to replay on the next tick.
1770
+ */
1771
+ async runTasks(account) {
1772
+ const credential = account.credential;
1773
+ const tasks = await this.client.listTasks(credential);
1774
+ const open = tasks.filter((task) => task.acceptStatus === "not_accepted" && !task.locked).map((task) => task.taskCode);
1775
+ if (open.length > 0) await this.client.acceptTasks(credential, open);
1776
+ const claimable = (open.length > 0 ? await this.client.listTasks(credential) : tasks).filter((task) => task.claimable && !task.locked);
1777
+ let credit = 0;
1778
+ let energy = 0;
1779
+ let claimed = 0;
1780
+ for (const task of claimable) {
1781
+ if (this.stopped) break;
1782
+ const reward = await this.client.claimTaskReward(credential, task.taskCode);
1783
+ credit += reward.credit;
1784
+ energy += reward.energy;
1785
+ if (reward.credit > 0 || reward.energy > 0) {
1786
+ claimed++;
1787
+ this.logger.info?.(`automation claim ${account.label}: ${task.title} +${reward.credit}c +${reward.energy}e`);
1788
+ } else this.logger.info?.(`automation claim ${account.label}: ${task.taskCode} already claimed`);
1789
+ if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
1790
+ }
1791
+ return {
1792
+ claimed,
1793
+ credit,
1794
+ energy,
1795
+ claimableCount: claimable.length
1796
+ };
1797
+ }
1798
+ /**
1799
+ * Streak redemption and lottery.
1800
+ *
1801
+ * Left as a deliberate no-op placeholder: the tier/lottery endpoints need
1802
+ * their own round of probing against the live upstream before they can be
1803
+ * wired safely, and a wrong call here could burn a redemption. The job slot,
1804
+ * scheduling and status plumbing already exist, so filling it in is a
1805
+ * self-contained change.
1806
+ */
1807
+ async redeemStreak(account) {
1808
+ this.logger.info?.(`automation streak ${account.label}: not implemented yet (skipped)`);
1809
+ }
1810
+ };
1228
1811
  //#endregion
1229
1812
  //#region src/status.ts
1230
1813
  /** Format the per-model credit multipliers. */
@@ -1251,6 +1834,26 @@ const modelSelectionSchema = z.object({
1251
1834
  imageModelIds: z.array(z.string()).description("Model ids accepting image input in this region (absent = follow upstream)"),
1252
1835
  contextBudgets: z.dict(z.number().step(1).min(1)).description("Per-model context-window override for this region")
1253
1836
  });
1837
+ /**
1838
+ * Automation schema.
1839
+ *
1840
+ * `enabled` carries a real default (false) because the scheduler reads it on
1841
+ * every tick and a missing field must mean "off" rather than "undefined".
1842
+ * The hour lists fall back in the scheduler itself, so they stay optional here
1843
+ * and an absent list keeps the documented schedule.
1844
+ *
1845
+ * `exhaustCooldownMs` is mirrored from the pool options: the card offers it as
1846
+ * part of the automation block, since how long a spent account rests only
1847
+ * matters to the automation that has to work around it.
1848
+ */
1849
+ const automationSchema = z.object({
1850
+ enabled: z.boolean().default(false).description("Run the daily points automation"),
1851
+ checkinHours: z.array(z.number().step(1).min(0).max(23)).description("Local hours for the daily check-in"),
1852
+ reportHours: z.array(z.number().step(1).min(0).max(23)).description("Local hours for the activity report (runs before tasks)"),
1853
+ taskHours: z.array(z.number().step(1).min(0).max(23)).description("Local hours for task enrolment and claiming"),
1854
+ streakHours: z.array(z.number().step(1).min(0).max(23)).description("Local hours for streak redemption"),
1855
+ exhaustCooldownMs: z.number().step(1).min(1e3).description("How long a spent account rests, in milliseconds")
1856
+ });
1254
1857
  z.object({
1255
1858
  authFile: z.string().description("WorkBuddy desktop auth file (defaults to the app own location)"),
1256
1859
  cooldownMs: z.number().step(1).min(1e3).default(6e4).description("Rate-limit cooldown per account, in milliseconds"),
@@ -1260,7 +1863,8 @@ z.object({
1260
1863
  imageModelIds: z.array(z.string()).default([]).description("Legacy shared image-id list; used by a region that has no per-region selection yet"),
1261
1864
  contextBudgets: z.dict(z.number().step(1).min(1)).default({}).description("Legacy shared context budgets; used by a region with no per-region selection yet"),
1262
1865
  modelSelectionCn: modelSelectionSchema.description("Model selection for the domestic gateway"),
1263
- modelSelectionGlobal: modelSelectionSchema.description("Model selection for the international gateway")
1866
+ modelSelectionGlobal: modelSelectionSchema.description("Model selection for the international gateway"),
1867
+ automation: automationSchema.description("Daily points automation (activity report, task claiming, check-in)")
1264
1868
  });
1265
1869
  /** Assemble the runtime objects without registering anything. */
1266
1870
  /**
@@ -1273,16 +1877,18 @@ z.object({
1273
1877
  */
1274
1878
  function createCore(logger) {
1275
1879
  const client = new WorkBuddyUpstreamClient();
1880
+ const pool = new WorkBuddyAccountPool({
1881
+ ...logger === void 0 ? {} : { logger },
1882
+ client
1883
+ });
1276
1884
  return {
1277
- pool: new WorkBuddyAccountPool({
1278
- ...logger === void 0 ? {} : { logger },
1279
- client
1280
- }),
1885
+ pool,
1281
1886
  catalogs: {
1282
1887
  cn: new WorkBuddyCatalog(),
1283
1888
  global: new WorkBuddyCatalog()
1284
1889
  },
1285
- client
1890
+ client,
1891
+ scheduler: new WorkBuddyScheduler(pool, client, { ...logger === void 0 ? {} : { logger } })
1286
1892
  };
1287
1893
  }
1288
1894
  //#endregion