dsh-connect-workbuddy 5.25.2 → 5.30.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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as CREDENTIAL_REJECTED_CODE, $t as imageSizeLimitsOf, A as withoutRouters, An as openEncryptedField, At as promoBadgeTone, B as defaultDesktopAuthPath, Bt as VIDEO_TAG_TEXT_TO_VIDEO, C as setDeviceMode, Cn as fetchAtRestKeyPayload, Ct as perturbChannelFingerprints, D as applyContextBudgets, Dn as isWorkbuddyBundle, Dt as rewriteSessionTitleModel, E as WorkBuddyCatalog, En as isEncryptedFieldWrapper, Et as requestEvidenceOf, F as WorkBuddyCredentialStore, Fn as withFileLock, Ft as offDefaultFor, G as parseWorkBuddyAuth, Gt as IMAGE_SIZE_LIMITS_WIDE, H as isEncryptedCredentialError, Ht as parseSupportedSecondsRange, I as WorkBuddyEncryptedCredentialError, In as writeFileAtomic, It as offRefused, J as workbuddyOwnAuthPath, Jt as MAX_INPUT_IMAGE_BYTES, K as preferredAccountName, Kt as IMAGE_TAG_IMAGE_TO_IMAGE, L as authFileName, Lt as recordRefusal, M as WORKBUDDY_AUTH_FILENAME, Mn as workbuddyAppExecutableCandidates, Mt as REFUSES_OFF_MODEL_IDS, N as WORKBUDDY_AUTH_FILE_ENV, Nt as defaultOffModelIds, O as deriveCatalog, On as macosBundleExecutable, Ot as toolSchemaRejectAdvice, Pn as resolveDshHome, Pt as lastRefusalFor, Q as CONTEXT_OVERFLOW_MARKER, Qt as imageModelChoices, R as defaultDesktopAuthCandidates, Rt as withEffectiveOff, S as saveDeviceSdkSettings, Sn as deriveAtRestKeyId, St as parseUpstreamModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tt as regionOf, U as isVaultAccountId, Ut as pickVideoModel, V as hasEncryptedCredentialFields, Vt as WorkBuddyVideoError, W as legacyWorkbuddyOwnAuthPath, Wt as resolveVideoParams, X as APP_VERSION, Xt as imageDataUrl, Yt as WorkBuddyImageError, Z as BODY_OVERSIZE_MARKER, Zt as imageMimeForPath, _ as createDeviceProfileLookup, _t as knownRegionOf, a as readHostHeartbeat, an as parseQueueAnswer, at as classifyUpstreamError, b as readDeviceSettings, bn as clearAtRestKeyCache, bt as parseCreditMultiplier, c as WORKBUDDY_CONNECT_VERSION, cn as NATIVE_MODALITY_BY_MODEL_ID, ct as deriveStableConversationId, dt as isBodyOversizeRefusal, en as isBareBase64Image, ft as isContextTooLongBody, g as createTuringSdk, gn as isDeviceId, gt as isToolSchemaRejectBody, h as createDeviceSdkPort, ht as isFirstMessageGateBody, i as processStartTimeMs, in as sniffImageMime, it as channelGateMemberOf, j as ENCRYPTED_CREDENTIAL_CODE, jn as readAtRestKey, jt as selectPromoBadge, k as fallbackModelsFor, kn as macosNestedAppBundles, kt as attachBusyLevels, l as createFileRosterSeenStore, ln as imageDefaultFor, m as piAiRuntimeInfo, mt as isCredentialRejectedError, n as clearHostHeartbeat, nn as parseImageDataUrl, nt as WorkBuddyCredentialRejectedError, o as workbuddyHostHeartbeatPath, on as queueNoticeText, ot as conversationIdFromSessionId, p as resolveCnGateway, pt as isConversationIdGateBody, q as workbuddyAccountId, qt as IMAGE_TAG_TEXT_TO_IMAGE, r as isHeartbeatProcessAlive, rn as pickMediaModel, rt as WorkBuddyUpstreamClient, s as writeHostHeartbeat, sn as pruneTempDir, st as declaredTools, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as isWatermarkFreeImageModel, tt as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, un as nativeModalityOf, ut as forceNeutralHead, v as describeDerivedDevices, vt as modelIdOfBody, w as FALLBACK_WORKBUDDY_MODELS, wn as findWorkbuddyAppExecutable, wt as prepareChatBody, x as saveDeviceProfile, xn as deriveAtRestKey, xt as parseReasoning, y as isDeviceMode, yn as WORKBUDDY_APP_EXECUTABLE_ENV, yt as openingEvidenceOfBody, z as defaultDesktopAuthDirs, zt as VIDEO_TAG_IMAGE_TO_VIDEO } from "./host-heartbeat-BDwQzVNn.js";
1
+ import { $ as CREDENTIAL_REJECTED_CODE, $t as imageModelChoices, A as withoutRouters, An as macosBundleExecutable, At as attachBusyLevels, B as defaultDesktopAuthPath, Bt as VIDEO_TAG_IMAGE_TO_VIDEO, C as setDeviceMode, Cn as deriveAtRestKey, Ct as parseUpstreamModel, D as applyContextBudgets, Dt as requestEvidenceOf, E as WorkBuddyCatalog, En as findWorkbuddyAppExecutable, Et as regionOf, F as WorkBuddyCredentialStore, Ft as lastRefusalFor, G as parseWorkBuddyAuth, Gt as resolveVideoParams, H as isEncryptedCredentialError, Ht as WorkBuddyVideoError, I as WorkBuddyEncryptedCredentialError, In as resolveDshHome, It as offDefaultFor, J as workbuddyOwnAuthPath, Jt as IMAGE_TAG_TEXT_TO_IMAGE, K as preferredAccountName, Kt as IMAGE_SIZE_LIMITS_WIDE, L as authFileName, Ln as withFileLock, Lt as offRefused, M as WORKBUDDY_AUTH_FILENAME, Mn as openEncryptedField, Mt as selectPromoBadge, N as WORKBUDDY_AUTH_FILE_ENV, Nn as readAtRestKey, Nt as REFUSES_OFF_MODEL_IDS, O as deriveCatalog, On as isEncryptedFieldWrapper, Ot as rewriteSessionTitleModel, Pn as workbuddyAppExecutableCandidates, Pt as defaultOffModelIds, Q as CONTEXT_OVERFLOW_MARKER, Qt as imageMimeForPath, R as defaultDesktopAuthCandidates, Rn as writeFileAtomic, Rt as recordRefusal, S as saveDeviceSdkSettings, Sn as clearAtRestKeyCache, St as parseReasoning, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as fetchAtRestKeyPayload, Tt as prepareChatBody, U as isVaultAccountId, Ut as parseSupportedSecondsRange, V as hasEncryptedCredentialFields, Vt as VIDEO_TAG_TEXT_TO_VIDEO, W as legacyWorkbuddyOwnAuthPath, Wt as pickVideoModel, X as APP_VERSION, Xt as WorkBuddyImageError, Yt as MAX_INPUT_IMAGE_BYTES, Z as BODY_OVERSIZE_MARKER, Zt as imageDataUrl, _ as createDeviceProfileLookup, _t as isToolSchemaRejectBody, a as readHostHeartbeat, an as sniffImageMime, at as classifyUpstreamError, b as readDeviceSettings, bt as openingEvidenceOfBody, c as WORKBUDDY_CONNECT_VERSION, cn as pruneTempDir, ct as deriveStableConversationId, dn as isRouterModelId, dt as growthHostOf, en as imageSizeLimitsOf, fn as nativeModalityOf, ft as isBodyOversizeRefusal, g as createTuringSdk, gt as isFirstMessageGateBody, h as createDeviceSdkPort, ht as isCredentialRejectedError, i as processStartTimeMs, in as pickMediaModel, it as channelGateMemberOf, j as ENCRYPTED_CREDENTIAL_CODE, jn as macosNestedAppBundles, jt as promoBadgeTone, k as fallbackModelsFor, kn as isWorkbuddyBundle, kt as toolSchemaRejectAdvice, l as createFileRosterSeenStore, ln as NATIVE_MODALITY_BY_MODEL_ID, m as piAiRuntimeInfo, mt as isConversationIdGateBody, n as clearHostHeartbeat, nn as isWatermarkFreeImageModel, nt as WorkBuddyCredentialRejectedError, o as workbuddyHostHeartbeatPath, on as parseQueueAnswer, ot as conversationIdFromSessionId, p as resolveCnGateway, pt as isContextTooLongBody, q as workbuddyAccountId, qt as IMAGE_TAG_IMAGE_TO_IMAGE, r as isHeartbeatProcessAlive, rn as parseImageDataUrl, rt as WorkBuddyUpstreamClient, s as writeHostHeartbeat, sn as queueNoticeText, st as declaredTools, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as isBareBase64Image, tt as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, un as imageDefaultFor, ut as forceNeutralHead, v as describeDerivedDevices, vn as isDeviceId, vt as knownRegionOf, w as FALLBACK_WORKBUDDY_MODELS, wn as deriveAtRestKeyId, wt as perturbChannelFingerprints, x as saveDeviceProfile, xn as WORKBUDDY_APP_EXECUTABLE_ENV, xt as parseCreditMultiplier, y as isDeviceMode, yt as modelIdOfBody, z as defaultDesktopAuthDirs, zt as withEffectiveOff } from "./host-heartbeat-BzYVKa0r.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -440,7 +440,7 @@ function poolActionOf(url) {
440
440
  const at = url.indexOf("?");
441
441
  if (at === -1) return void 0;
442
442
  const value = new URLSearchParams(url.slice(at + 1)).get(WORKBUDDY_POOL_ACTION_PARAM);
443
- return value === "checkin" || value === "test" || value === "remove" ? value : void 0;
443
+ return value === "checkin" || value === "test" || value === "remove" || value === "growth-redeem" || value === "growth-activity" ? value : void 0;
444
444
  }
445
445
  /** Query parameter naming ONE pool account a per-row request addresses. */
446
446
  const WORKBUDDY_POOL_ACCOUNT_PARAM = "accountId";
@@ -11364,7 +11364,7 @@ function mergeTransferRecords(records, indexes, region, knownRegionOfDomain) {
11364
11364
  * @module dsh-connect-workbuddy/account-pool-store
11365
11365
  */
11366
11366
  /** On-disk format version; readers reject anything else. */
11367
- const STORE_FORMAT_VERSION$1 = 1;
11367
+ const STORE_FORMAT_VERSION$3 = 1;
11368
11368
  /** Filename prefix for one region's measured pool facts. */
11369
11369
  const POOL_STORE_PREFIX = ".workbuddy-pool";
11370
11370
  /** Whether a parsed value looks like a stored probe. */
@@ -11454,7 +11454,7 @@ async function readPoolProbes(region) {
11454
11454
  }
11455
11455
  if (typeof parsed !== "object" || parsed === null) return {};
11456
11456
  const document = parsed;
11457
- if (document.version !== STORE_FORMAT_VERSION$1) return {};
11457
+ if (document.version !== STORE_FORMAT_VERSION$3) return {};
11458
11458
  if (typeof document.probes !== "object" || document.probes === null) return {};
11459
11459
  const probes = {};
11460
11460
  for (const [accountId, probe] of Object.entries(document.probes)) {
@@ -11557,7 +11557,7 @@ async function writePoolProbes(region, updates) {
11557
11557
  const merged = { ...existing };
11558
11558
  for (const [accountId, update] of Object.entries(updates)) merged[accountId] = mergePoolProbe(existing[accountId], update);
11559
11559
  await writeFileAtomic(path, `${JSON.stringify({
11560
- version: STORE_FORMAT_VERSION$1,
11560
+ version: STORE_FORMAT_VERSION$3,
11561
11561
  probes: merged
11562
11562
  }, null, 2)}\n`, {
11563
11563
  mode: 384,
@@ -11587,7 +11587,7 @@ async function reconcilePoolCredits(region, readings) {
11587
11587
  changed = true;
11588
11588
  }
11589
11589
  if (changed) await writeFileAtomic(path, `${JSON.stringify({
11590
- version: STORE_FORMAT_VERSION$1,
11590
+ version: STORE_FORMAT_VERSION$3,
11591
11591
  probes
11592
11592
  }, null, 2)}\n`, {
11593
11593
  mode: 384,
@@ -11765,23 +11765,6 @@ function todaySummary(state, nowMs) {
11765
11765
  return summarizeAutoCheckin(state);
11766
11766
  }
11767
11767
  /**
11768
- * Whether a cached check-in reading may still be served.
11769
- *
11770
- * Two conditions, and the second is the one that took a bug report: a reading is
11771
- * an answer to "has this account checked in TODAY", so it must not survive local
11772
- * midnight. The TTL alone would serve a `true` read taken at 23:58 until 00:08,
11773
- * so the column would assert a check-in that has not happened — the per-account
11774
- * half of the same lie as {@link todaySummary}.
11775
- *
11776
- * The day is derived from `atMs` rather than stored beside it: the read time
11777
- * already says which day the answer belongs to, and a second field could drift
11778
- * out of step with it.
11779
- */
11780
- function checkinReadingFresh(atMs, nowMs, ttlMs) {
11781
- if (nowMs - atMs >= ttlMs) return false;
11782
- return localDayKey(atMs) === localDayKey(nowMs);
11783
- }
11784
- /**
11785
11768
  * The accounts an attempt should address, in the pool's own order.
11786
11769
  *
11787
11770
  * Only members that are not already done. Enterprise members are dropped HERE
@@ -11819,11 +11802,11 @@ function pendingTargets(targets, state) {
11819
11802
  * @module dsh-connect-workbuddy/auto-checkin-store
11820
11803
  */
11821
11804
  /** On-disk format version; readers reject anything else. */
11822
- const STORE_FORMAT_VERSION = 1;
11805
+ const STORE_FORMAT_VERSION$2 = 1;
11823
11806
  /** Filename prefix for one region's auto-check-in memory. */
11824
11807
  const AUTO_CHECKIN_PREFIX = ".workbuddy-auto-checkin";
11825
11808
  /** Whether a parsed value looks like a stored state. */
11826
- function isState(value) {
11809
+ function isState$1(value) {
11827
11810
  if (typeof value !== "object" || value === null) return false;
11828
11811
  const candidate = value;
11829
11812
  return typeof candidate["day"] === "string" && Array.isArray(candidate["doneAccountIds"]) && candidate["doneAccountIds"].every((id) => typeof id === "string") && typeof candidate["failures"] === "number" && Number.isFinite(candidate["failures"]) && (candidate["lastAttemptAtMs"] === void 0 || typeof candidate["lastAttemptAtMs"] === "number") && (candidate["lastError"] === void 0 || typeof candidate["lastError"] === "string");
@@ -11854,11 +11837,11 @@ async function readAutoCheckinState(region) {
11854
11837
  }
11855
11838
  if (typeof parsed !== "object" || parsed === null) return void 0;
11856
11839
  const document = parsed;
11857
- if (document.version !== STORE_FORMAT_VERSION) return void 0;
11840
+ if (document.version !== STORE_FORMAT_VERSION$2) return void 0;
11858
11841
  const regions = document.regions;
11859
11842
  if (typeof regions !== "object" || regions === null) return void 0;
11860
11843
  const state = regions[region];
11861
- return isState(state) ? state : void 0;
11844
+ return isState$1(state) ? state : void 0;
11862
11845
  }
11863
11846
  /**
11864
11847
  * Write one region's state, merging into whatever the file already holds.
@@ -11876,7 +11859,7 @@ async function writeAutoCheckinState(region, state) {
11876
11859
  [region]: state
11877
11860
  };
11878
11861
  await writeFileAtomic(path, `${JSON.stringify({
11879
- version: STORE_FORMAT_VERSION,
11862
+ version: STORE_FORMAT_VERSION$2,
11880
11863
  regions
11881
11864
  }, null, 2)}\n`, {
11882
11865
  mode: 384,
@@ -11901,14 +11884,564 @@ async function readDocument(path) {
11901
11884
  }
11902
11885
  if (typeof parsed !== "object" || parsed === null) return {};
11903
11886
  const document = parsed;
11904
- if (document.version !== STORE_FORMAT_VERSION) return {};
11887
+ if (document.version !== STORE_FORMAT_VERSION$2) return {};
11905
11888
  const regions = document.regions;
11906
11889
  if (typeof regions !== "object" || regions === null) return {};
11907
11890
  const clean = {};
11908
- for (const [key, value] of Object.entries(regions)) if (isState(value)) clean[key] = value;
11891
+ for (const [key, value] of Object.entries(regions)) if (isState$1(value)) clean[key] = value;
11909
11892
  return clean;
11910
11893
  }
11911
11894
  //#endregion
11895
+ //#region src/daily-done-store.ts
11896
+ /**
11897
+ * On-disk "done today" memory for the three per-account day facts (issue #286
11898
+ * follow-up): checked-in / tier-redeemed / active-today.
11899
+ *
11900
+ * WHY THIS EXISTS. The card used to RE-READ "did this account check in today"
11901
+ * from upstream every 10 minutes, for every account — including ones that had
11902
+ * been done since morning. The user asked for the obvious: once a fact is true
11903
+ * today, remember it locally and stop asking; only read when there is no record
11904
+ * yet (a fresh day, or an account the plugin has never observed). This module is
11905
+ * that memory. It is keyed by (kind, region), persisted under `$DSH_HOME`, and
11906
+ * bounded by the LOCAL day so a `true` read at 23:58 never answers for 00:08.
11907
+ *
11908
+ * It deliberately does NOT distinguish "we did it" from "the user did it in the
11909
+ * official client": both are observed as `true` from upstream and both mean the
11910
+ * same thing to the card — done today, nothing more to do. That is why the read
11911
+ * path writes the record: the first observation (whoever caused it) is enough.
11912
+ *
11913
+ * Reads/writes never throw — a corrupt or missing file means "nothing done
11914
+ * today", and the caller then performs the one read this module saves.
11915
+ *
11916
+ * No token, no account name in the file — only account ids and a local day key.
11917
+ *
11918
+ * @module dsh-connect-workbuddy/daily-done-store
11919
+ */
11920
+ const STORE_FORMAT_VERSION$1 = 1;
11921
+ /** A process-local mirror so the hot path never touches the disk. */
11922
+ const memory = {};
11923
+ /**
11924
+ * Cache key includes the resolved home so a changed `$DSH_HOME` (only ever a
11925
+ * test fixture in practice) cannot reuse another home's memory. In production
11926
+ * the home is fixed for the process, so this is a pure correctness safeguard.
11927
+ */
11928
+ const keyOf = (kind, region) => `${resolveDshHome()}:${kind}:${region}`;
11929
+ function filePath(kind, region) {
11930
+ return join(resolveDshHome(), `.workbuddy-daydone-${kind}.${region}.json`);
11931
+ }
11932
+ function isDocument(value) {
11933
+ if (typeof value !== "object" || value === null) return false;
11934
+ const doc = value;
11935
+ return doc["version"] === STORE_FORMAT_VERSION$1 && typeof doc["day"] === "string" && Array.isArray(doc["ids"]) && doc["ids"].every((id) => typeof id === "string");
11936
+ }
11937
+ /** Load one (kind, region) from disk into the mirror, once. Never throws. */
11938
+ async function load(kind, region) {
11939
+ const key = keyOf(kind, region);
11940
+ const hit = memory[key];
11941
+ if (hit !== void 0) return hit;
11942
+ let loaded = {
11943
+ day: localDayKey(Date.now()),
11944
+ ids: /* @__PURE__ */ new Set()
11945
+ };
11946
+ try {
11947
+ const raw = await readFile(filePath(kind, region), "utf8");
11948
+ const parsed = JSON.parse(raw);
11949
+ if (isDocument(parsed) && parsed.day === localDayKey(Date.now())) loaded = {
11950
+ day: parsed.day,
11951
+ ids: new Set(parsed.ids)
11952
+ };
11953
+ } catch {}
11954
+ memory[key] = loaded;
11955
+ return loaded;
11956
+ }
11957
+ /** Is this account already recorded done TODAY? No disk read after the first. */
11958
+ async function isDoneToday(kind, region, accountId) {
11959
+ const state = await load(kind, region);
11960
+ if (state.day !== localDayKey(Date.now())) {
11961
+ memory[keyOf(kind, region)] = {
11962
+ day: localDayKey(Date.now()),
11963
+ ids: /* @__PURE__ */ new Set()
11964
+ };
11965
+ return false;
11966
+ }
11967
+ return state.ids.has(accountId);
11968
+ }
11969
+ /** Record one (or several) accounts done today. Never throws. */
11970
+ async function markDoneToday(kind, region, accountIds) {
11971
+ if (accountIds.length === 0) return;
11972
+ const key = keyOf(kind, region);
11973
+ const today = localDayKey(Date.now());
11974
+ const state = memory[key]?.day === today ? memory[key] : {
11975
+ day: today,
11976
+ ids: /* @__PURE__ */ new Set()
11977
+ };
11978
+ for (const id of accountIds) state.ids.add(id);
11979
+ memory[key] = state;
11980
+ const path = filePath(kind, region);
11981
+ try {
11982
+ await withFileLock(path, async () => {
11983
+ const document = {
11984
+ version: STORE_FORMAT_VERSION$1,
11985
+ day: today,
11986
+ ids: [...state.ids]
11987
+ };
11988
+ await writeFileAtomic(path, `${JSON.stringify(document, null, 2)}\n`, {
11989
+ mode: 384,
11990
+ dirMode: 448
11991
+ });
11992
+ });
11993
+ } catch {}
11994
+ }
11995
+ /** The full done-today set for one (kind, region), for the first-paint map. */
11996
+ async function doneTodayMap(kind, region) {
11997
+ const state = await load(kind, region);
11998
+ if (state.day !== localDayKey(Date.now())) return {};
11999
+ return Object.fromEntries([...state.ids].map((id) => [id, true]));
12000
+ }
12001
+ //#endregion
12002
+ //#region src/growth-acp.ts
12003
+ /** Normalize a session link to its ACP endpoint, without duplicating the suffix. */
12004
+ function resolveAcpEndpoint(link) {
12005
+ let value = (link ?? "").trim().replace(/^http:\/\//u, "https://").replace(/\/+$/u, "");
12006
+ if (value === "") return "";
12007
+ if (/\/api\/v1\/acp$/u.test(value) || /\/acp$/u.test(value)) return value;
12008
+ return `${value}/api/v1/acp`;
12009
+ }
12010
+ /** Parse an SSE body: yield the JSON payloads of `data:` lines with the given id. */
12011
+ function rpcResultFromSse(text, id) {
12012
+ for (const line of text.split(/\r?\n/u)) {
12013
+ const trimmed = line.trim();
12014
+ if (!trimmed.startsWith("data:")) continue;
12015
+ let parsed;
12016
+ try {
12017
+ parsed = JSON.parse(trimmed.slice(5).trim());
12018
+ } catch {
12019
+ continue;
12020
+ }
12021
+ if (typeof parsed !== "object" || parsed === null) continue;
12022
+ const message = parsed;
12023
+ if (message["id"] !== id) continue;
12024
+ if (message["error"] !== void 0) throw new Error(`ACP RPC error: ${String(message["error"]).slice(0, 200)}`);
12025
+ return typeof message["result"] === "object" && message["result"] !== null ? message["result"] : {};
12026
+ }
12027
+ }
12028
+ /** Send one console ACP session; returns its conversation id. Throws on failure. */
12029
+ async function sendAcpSession(options) {
12030
+ const doFetch = options.fetch ?? globalThis.fetch;
12031
+ const base = options.base.replace(/\/+$/u, "");
12032
+ const ua = options.userAgent ?? "WorkBuddy/5.8.3";
12033
+ const jsonHeaders = (token) => ({
12034
+ "accept": "application/json, text/plain, */*",
12035
+ "content-type": "application/json",
12036
+ "x-codebuddy-request": "1",
12037
+ "x-client-platform": "web",
12038
+ "user-agent": ua,
12039
+ "authorization": `Bearer ${token}`,
12040
+ "origin": options.origin,
12041
+ "referer": `${options.origin.replace(/\/+$/u, "")}/`
12042
+ });
12043
+ let created;
12044
+ let lastError = "";
12045
+ for (const withPlugins of [true, false]) {
12046
+ const body = {
12047
+ prompt: options.prompt ?? "你好",
12048
+ model: options.model
12049
+ };
12050
+ if (withPlugins) body["plugins"] = [];
12051
+ try {
12052
+ const response = await doFetch(`${base}/console/as/conversations/`, {
12053
+ method: "POST",
12054
+ headers: jsonHeaders(options.accessToken),
12055
+ body: JSON.stringify(body),
12056
+ signal: AbortSignal.timeout(6e4)
12057
+ });
12058
+ if (response.ok) {
12059
+ const parsed = await response.json();
12060
+ created = typeof parsed === "object" && parsed !== null ? parsed : void 0;
12061
+ break;
12062
+ }
12063
+ lastError = `HTTP ${response.status}`;
12064
+ if (response.status !== 400 && response.status !== 404) break;
12065
+ } catch (error) {
12066
+ lastError = String(error);
12067
+ break;
12068
+ }
12069
+ }
12070
+ if (created === void 0) throw new Error(`ACP create conversation failed: ${lastError}`);
12071
+ const data = typeof created["data"] === "object" && created["data"] !== null ? created["data"] : created;
12072
+ const id = String(data["id"] ?? data["conversationId"] ?? data["info"]?.id ?? "");
12073
+ if (id === "") throw new Error("ACP create response had no conversation id");
12074
+ let session = typeof data["session"] === "object" && data["session"] !== null ? data["session"] : void 0;
12075
+ if (session === void 0 || typeof session["link"] !== "string" || typeof session["token"] !== "string") {
12076
+ const response = await doFetch(`${base}/console/as/conversations/${encodeURIComponent(id)}/session`, {
12077
+ method: "GET",
12078
+ headers: jsonHeaders(options.accessToken),
12079
+ signal: AbortSignal.timeout(6e4)
12080
+ });
12081
+ if (!response.ok) throw new Error(`ACP fetch session failed: HTTP ${response.status}`);
12082
+ const parsed = await response.json();
12083
+ const sdata = typeof parsed === "object" && parsed !== null ? parsed : {};
12084
+ session = typeof sdata["data"] === "object" && sdata["data"] !== null ? sdata["data"] : sdata;
12085
+ }
12086
+ const link = resolveAcpEndpoint(String(session?.["link"] ?? session?.["endpoint"] ?? ""));
12087
+ const sessionToken = String(session?.["token"] ?? session?.["accessToken"] ?? "");
12088
+ const sessionId = String(session?.["sessionId"] ?? session?.["session_id"] ?? "");
12089
+ if (link === "" || sessionToken === "" || sessionId === "") throw new Error("ACP session response missing link/token/sessionId");
12090
+ const connectionId = (await doFetch(link, {
12091
+ method: "GET",
12092
+ headers: {
12093
+ ...jsonHeaders(sessionToken),
12094
+ "accept": "text/event-stream"
12095
+ },
12096
+ signal: AbortSignal.timeout(6e4)
12097
+ })).headers.get("acp-connection-id") ?? "";
12098
+ if (connectionId === "") throw new Error("ACP SSE response missing acp-connection-id");
12099
+ const rpc = async (method, params, rpcId) => {
12100
+ const response = await doFetch(link, {
12101
+ method: "POST",
12102
+ headers: {
12103
+ ...jsonHeaders(sessionToken),
12104
+ "accept": "application/json, text/event-stream",
12105
+ "acp-connection-id": connectionId
12106
+ },
12107
+ body: JSON.stringify({
12108
+ jsonrpc: "2.0",
12109
+ id: rpcId,
12110
+ method,
12111
+ params
12112
+ }),
12113
+ signal: AbortSignal.timeout(6e4)
12114
+ });
12115
+ if (!response.ok) throw new Error(`ACP RPC ${method} failed: HTTP ${response.status}`);
12116
+ rpcResultFromSse(await response.text(), rpcId);
12117
+ };
12118
+ await rpc("initialize", {
12119
+ protocolVersion: 1,
12120
+ clientInfo: {
12121
+ name: "dsh-connect-workbuddy",
12122
+ version: "1.0"
12123
+ },
12124
+ clientCapabilities: {
12125
+ fs: {
12126
+ readTextFile: false,
12127
+ writeTextFile: false
12128
+ },
12129
+ _meta: { "codebuddy.ai": {
12130
+ question: false,
12131
+ terminalOutput: false
12132
+ } }
12133
+ }
12134
+ }, 1);
12135
+ await rpc("session/prompt", {
12136
+ sessionId,
12137
+ prompt: [{
12138
+ type: "text",
12139
+ text: options.prompt ?? "你好"
12140
+ }]
12141
+ }, 2);
12142
+ try {
12143
+ await doFetch(link, {
12144
+ method: "DELETE",
12145
+ headers: {
12146
+ ...jsonHeaders(sessionToken),
12147
+ "acp-connection-id": connectionId
12148
+ },
12149
+ signal: AbortSignal.timeout(1e4)
12150
+ });
12151
+ } catch {}
12152
+ return id;
12153
+ }
12154
+ /**
12155
+ * Ensure the account is active today. Idempotent: already-active sends nothing.
12156
+ * After sending, polls the heatmap up to `verifyAttempts` times to confirm the
12157
+ * write landed before reporting success.
12158
+ */
12159
+ async function activateGrowth(options) {
12160
+ const before = await options.heatmap();
12161
+ if (before?.isActive === true) return {
12162
+ status: "already-active",
12163
+ score: before.score
12164
+ };
12165
+ let conversationId;
12166
+ try {
12167
+ conversationId = await sendAcpSession(options);
12168
+ } catch (error) {
12169
+ return {
12170
+ status: "failed",
12171
+ reason: String(error)
12172
+ };
12173
+ }
12174
+ const sleep = options.sleep ?? (async (ms) => {
12175
+ await new Promise((resolve) => setTimeout(resolve, ms));
12176
+ });
12177
+ const attempts = options.verifyAttempts ?? 4;
12178
+ const gap = options.verifyIntervalMs ?? 1500;
12179
+ for (let i = 0; i < attempts; i += 1) {
12180
+ if (i > 0) await sleep(gap);
12181
+ const now = await options.heatmap();
12182
+ if (now?.isActive === true) return {
12183
+ status: "activated",
12184
+ score: now.score,
12185
+ conversationId
12186
+ };
12187
+ }
12188
+ return {
12189
+ status: "failed",
12190
+ conversationId,
12191
+ reason: "ACP session sent but heatmap today.is_active stayed false"
12192
+ };
12193
+ }
12194
+ //#endregion
12195
+ //#region src/growth-run.ts
12196
+ /** Accounts still due today: pool members minus those already settled. */
12197
+ function growthPendingTargets(targets, state) {
12198
+ const done = new Set(state?.doneAccountIds ?? []);
12199
+ return targets.filter((target) => !done.has(target.accountId));
12200
+ }
12201
+ /**
12202
+ * Fold one growth attempt into today's state: every addressed account is marked
12203
+ * settled. No backoff, no `lastError` — the card shows a plain done/total count.
12204
+ * `scopeSize` is the REAL member count passed by the caller (never accumulated),
12205
+ * so a manual run cannot inflate the denominator the way the earlier bug did.
12206
+ */
12207
+ function foldGrowthAttempt(state, attemptedIds, scopeSize, nowMs) {
12208
+ const done = /* @__PURE__ */ new Set([...state.doneAccountIds, ...attemptedIds]);
12209
+ return {
12210
+ day: state.day,
12211
+ doneAccountIds: [...done],
12212
+ scopeSize,
12213
+ failures: 0,
12214
+ lastAttemptAtMs: nowMs
12215
+ };
12216
+ }
12217
+ /** A day summary with NO pending/retry/failure fields — just done of total. */
12218
+ function growthTodaySummary(state, day) {
12219
+ if (state === void 0 || state.day !== day) return void 0;
12220
+ return {
12221
+ done: Math.min(state.doneAccountIds.length, state.scopeSize),
12222
+ total: state.scopeSize
12223
+ };
12224
+ }
12225
+ async function pause(deps, issued) {
12226
+ if (issued > 0) await (deps.wait ?? (async (ms) => {
12227
+ await new Promise((r) => setTimeout(r, ms));
12228
+ }))(400);
12229
+ }
12230
+ /**
12231
+ * Redeem every claimable tier for every target, one account at a time.
12232
+ * Only tiers the gateway reported `available` are written — a `locked` tier is
12233
+ * never redeemed, so a repeated run is a no-op rather than a refused write.
12234
+ * Never throws: each problem becomes a `failed` row and the batch continues.
12235
+ */
12236
+ async function redeemGrowthAll(targets, deps) {
12237
+ const rows = [];
12238
+ let issued = 0;
12239
+ for (const target of targets) {
12240
+ const base = {
12241
+ accountId: target.accountId,
12242
+ accountName: target.accountName
12243
+ };
12244
+ let credential;
12245
+ try {
12246
+ credential = await deps.credentialFor(target.accountId);
12247
+ } catch (error) {
12248
+ rows.push({
12249
+ ...base,
12250
+ status: "failed",
12251
+ message: String(error)
12252
+ });
12253
+ continue;
12254
+ }
12255
+ if (credential === void 0) {
12256
+ rows.push({
12257
+ ...base,
12258
+ status: "failed",
12259
+ message: "no stored credential for this account"
12260
+ });
12261
+ continue;
12262
+ }
12263
+ let streak;
12264
+ try {
12265
+ streak = await deps.readStreak(credential);
12266
+ } catch (error) {
12267
+ rows.push({
12268
+ ...base,
12269
+ status: "failed",
12270
+ message: String(error)
12271
+ });
12272
+ continue;
12273
+ }
12274
+ if (streak === void 0) {
12275
+ rows.push({
12276
+ ...base,
12277
+ status: "failed",
12278
+ message: "growth streak was not readable"
12279
+ });
12280
+ continue;
12281
+ }
12282
+ if (streak.availableTiers.length === 0) {
12283
+ rows.push({
12284
+ ...base,
12285
+ status: "skipped",
12286
+ message: "no tier is available to redeem"
12287
+ });
12288
+ continue;
12289
+ }
12290
+ await pause(deps, issued);
12291
+ issued += 1;
12292
+ let credit = 0;
12293
+ const done = [];
12294
+ let failure = "";
12295
+ for (const tier of streak.availableTiers) try {
12296
+ const result = await deps.redeem(credential, tier);
12297
+ credit += result.credit;
12298
+ done.push(tier);
12299
+ } catch (error) {
12300
+ failure = String(error);
12301
+ break;
12302
+ }
12303
+ if (failure !== "" && done.length === 0) rows.push({
12304
+ ...base,
12305
+ status: "failed",
12306
+ message: failure
12307
+ });
12308
+ else rows.push({
12309
+ ...base,
12310
+ status: "done",
12311
+ credit,
12312
+ message: `redeemed ${done.join(",")}${failure === "" ? "" : `; stopped: ${failure}`}`
12313
+ });
12314
+ }
12315
+ return rows;
12316
+ }
12317
+ /**
12318
+ * Ensure "active today" for every target, one account at a time. The caller
12319
+ * supplies `activateOne` so model selection and ACP details stay outside this
12320
+ * module. Idempotency lives in the activate function (already-active sends no
12321
+ * session), so a repeated batch is safe.
12322
+ */
12323
+ async function activateGrowthAll(targets, activateOne, wait) {
12324
+ const rows = [];
12325
+ let issued = 0;
12326
+ for (const target of targets) {
12327
+ let result;
12328
+ try {
12329
+ result = await activateOne(target.accountId);
12330
+ } catch (error) {
12331
+ rows.push({
12332
+ accountId: target.accountId,
12333
+ accountName: target.accountName,
12334
+ status: "failed",
12335
+ message: String(error)
12336
+ });
12337
+ continue;
12338
+ }
12339
+ if (result.status === "already-active") {
12340
+ rows.push({
12341
+ accountId: target.accountId,
12342
+ accountName: target.accountName,
12343
+ status: "skipped",
12344
+ message: "already active today"
12345
+ });
12346
+ continue;
12347
+ }
12348
+ if (result.status === "activated") {
12349
+ if (issued > 0) await (wait ?? (async (ms) => {
12350
+ await new Promise((r) => setTimeout(r, ms));
12351
+ }))(400);
12352
+ issued += 1;
12353
+ rows.push({
12354
+ accountId: target.accountId,
12355
+ accountName: target.accountName,
12356
+ status: "done",
12357
+ message: "activated"
12358
+ });
12359
+ continue;
12360
+ }
12361
+ rows.push({
12362
+ accountId: target.accountId,
12363
+ accountName: target.accountName,
12364
+ status: "failed",
12365
+ message: result.reason ?? "activation failed"
12366
+ });
12367
+ }
12368
+ return rows;
12369
+ }
12370
+ //#endregion
12371
+ //#region src/growth-state-store.ts
12372
+ /**
12373
+ * On-disk memory for the two background growth capabilities (issue #286).
12374
+ *
12375
+ * Same discipline as `auto-checkin-store.ts`: one file per CAPABILITY + REGION
12376
+ * under `$DSH_HOME`, atomic + locked writes, `mode: 0o600`, no token and no
12377
+ * account name inside — only account ids and a short failure reason. Kept in a
12378
+ * separate file from auto-check-in so the three capabilities' `doneAccountIds`
12379
+ * can never overwrite each other: "checked in" ≠ "active" ≠ "redeemed".
12380
+ *
12381
+ * Reads and writes never throw. A corrupt file degrades to "nothing done
12382
+ * today", and a repeat run is idempotent by design.
12383
+ *
12384
+ * @module dsh-connect-workbuddy/growth-state-store
12385
+ */
12386
+ const STORE_FORMAT_VERSION = 1;
12387
+ /** Path for one capability + region. */
12388
+ function growthStatePath(capability, region) {
12389
+ return join(resolveDshHome(), `.workbuddy-${capability}.${region}.json`);
12390
+ }
12391
+ function isState(value) {
12392
+ if (typeof value !== "object" || value === null) return false;
12393
+ const candidate = value;
12394
+ return typeof candidate["day"] === "string" && Array.isArray(candidate["doneAccountIds"]) && candidate["doneAccountIds"].every((id) => typeof id === "string") && typeof candidate["failures"] === "number" && Number.isFinite(candidate["failures"]) && (candidate["lastAttemptAtMs"] === void 0 || typeof candidate["lastAttemptAtMs"] === "number") && (candidate["lastError"] === void 0 || typeof candidate["lastError"] === "string");
12395
+ }
12396
+ /** Read one capability + region's state, or undefined when absent/corrupt. */
12397
+ async function readGrowthState(capability, region) {
12398
+ try {
12399
+ const raw = await readFile(growthStatePath(capability, region), "utf8");
12400
+ const parsed = JSON.parse(raw);
12401
+ if (typeof parsed !== "object" || parsed === null) return void 0;
12402
+ const document = parsed;
12403
+ if (document.version !== STORE_FORMAT_VERSION) return void 0;
12404
+ const regions = document.regions;
12405
+ if (typeof regions !== "object" || regions === null) return void 0;
12406
+ const state = regions[region];
12407
+ return isState(state) ? state : void 0;
12408
+ } catch {
12409
+ return;
12410
+ }
12411
+ }
12412
+ /** Write one capability + region's state, merging the sibling region. Never throws. */
12413
+ async function writeGrowthState(capability, region, state) {
12414
+ const path = growthStatePath(capability, region);
12415
+ try {
12416
+ await withFileLock(path, async () => {
12417
+ let existing = {};
12418
+ try {
12419
+ const raw = await readFile(path, "utf8");
12420
+ const parsed = JSON.parse(raw);
12421
+ if (typeof parsed === "object" && parsed !== null) {
12422
+ const doc = parsed;
12423
+ if (doc.version === STORE_FORMAT_VERSION && typeof doc.regions === "object" && doc.regions !== null) {
12424
+ const clean = {};
12425
+ for (const [key, value] of Object.entries(doc.regions)) if (isState(value)) clean[key] = value;
12426
+ existing = clean;
12427
+ }
12428
+ }
12429
+ } catch {}
12430
+ const document = {
12431
+ version: STORE_FORMAT_VERSION,
12432
+ regions: {
12433
+ ...existing,
12434
+ [region]: state
12435
+ }
12436
+ };
12437
+ await writeFileAtomic(path, `${JSON.stringify(document, null, 2)}\n`, {
12438
+ mode: 384,
12439
+ dirMode: 448
12440
+ });
12441
+ });
12442
+ } catch {}
12443
+ }
12444
+ //#endregion
11912
12445
  //#region src/web-status.ts
11913
12446
  /** Redact token-like content before it crosses to the browser. */
11914
12447
  function safeMessage(error) {
@@ -12263,6 +12796,24 @@ async function workBuddyAccountCredits(deps, region) {
12263
12796
  }));
12264
12797
  }
12265
12798
  /**
12799
+ * Decide what the user can do about a refused credential in one region.
12800
+ *
12801
+ * Shared by the two refusal paths: a credits/check-in read that was rejected
12802
+ * on an otherwise usable credential ({@link liveFigures}), and a `resolve()`
12803
+ * whose TOKEN REFRESH was rejected outright (issue #285 — the CN card hid all
12804
+ * of its accounts while the export dialog still saw them). The recovery answer
12805
+ * must not depend on which path noticed the refusal: both offer the same
12806
+ * "switch to a verified account / sign in again" advice.
12807
+ */
12808
+ async function credentialRecoveryOf(deps, region, rejectedAccountId) {
12809
+ return resolveCredentialRecovery({
12810
+ region,
12811
+ store: deps.store(region),
12812
+ ...rejectedAccountId === void 0 ? {} : { rejectedAccountId },
12813
+ probe: deps.accountUsable ?? (async () => false)
12814
+ });
12815
+ }
12816
+ /**
12266
12817
  * Read the selected account's live figures, and classify a refusal.
12267
12818
  *
12268
12819
  * Extracted so the first-paint path can omit it as a unit: the two calls here
@@ -12272,12 +12823,7 @@ async function workBuddyAccountCredits(deps, region) {
12272
12823
  async function liveFigures(deps, region, credential, selected) {
12273
12824
  const [creditsResult, checkinResult] = await Promise.allSettled([deps.client.fetchCredits(credential), deps.client.fetchCheckinStatus(credential)]);
12274
12825
  const rejected = [creditsResult, checkinResult].some((result) => result.status === "rejected" && isCredentialRejectedError(result.reason));
12275
- const recovery = !rejected ? void 0 : await resolveCredentialRecovery({
12276
- region,
12277
- store: deps.store(region),
12278
- ...selected === void 0 ? {} : { rejectedAccountId: selected.id },
12279
- probe: deps.accountUsable ?? (async () => false)
12280
- });
12826
+ const recovery = !rejected ? void 0 : await credentialRecoveryOf(deps, region, selected?.id);
12281
12827
  return {
12282
12828
  ...creditsResult.status === "fulfilled" ? { credits: toCredits(creditsResult.value) } : { creditsError: safeMessage(creditsResult.reason) },
12283
12829
  ...checkinResult.status === "fulfilled" ? { checkin: checkinResult.value } : { checkinError: safeMessage(checkinResult.reason) },
@@ -12357,10 +12903,14 @@ async function workBuddyWebStatus(deps, region, options = {}) {
12357
12903
  if (credential === void 0) credential = await store.resolve();
12358
12904
  } catch (error) {
12359
12905
  const webAccounts = accounts.map(toWebAccount);
12906
+ const refreshRejected = isCredentialRejectedError(error);
12907
+ const recovery = !refreshRejected ? void 0 : await credentialRecoveryOf(deps, region, accounts.find((account) => account.selected)?.id);
12360
12908
  return {
12361
12909
  status: "signed-out",
12362
12910
  accounts: webAccounts,
12363
12911
  message: safeMessage(error),
12912
+ ...!refreshRejected ? {} : { credentialRejected: true },
12913
+ ...recovery === void 0 ? {} : { recovery },
12364
12914
  selectionExplicit,
12365
12915
  enabled,
12366
12916
  showCreditsInMainUi,
@@ -12484,7 +13034,9 @@ async function workBuddyWebPool(deps, region, fast = false) {
12484
13034
  const byId = new Map(members.map((member) => [member.account.id, member]));
12485
13035
  const rankedIds = new Set(ranked.map((row) => row.account.id));
12486
13036
  const others = await pool.otherAccounts?.(region) ?? [];
12487
- const checkedIn = fast ? pool.cachedCheckedInToday?.(region) ?? {} : await pool.checkedInToday?.(region).catch(() => ({})) ?? {};
13037
+ const checkedIn = fast ? await pool.cachedCheckedInToday?.(region) ?? {} : await pool.checkedInToday?.(region).catch(() => ({})) ?? {};
13038
+ const growthRedeemed = await pool.growthDoneAccountIds?.(region, "growth-redeem") ?? {};
13039
+ const growthActive = await pool.growthDoneAccountIds?.(region, "growth-activity") ?? {};
12488
13040
  const claimable = fast ? pool.cachedBenefits?.(region) ?? {} : await pool.benefits?.(region).catch(() => ({})) ?? {};
12489
13041
  const rows = [...ranked.map((row) => ({
12490
13042
  account: row.account,
@@ -12535,6 +13087,8 @@ async function workBuddyWebPool(deps, region, fast = false) {
12535
13087
  current: account.id === currentAccountId,
12536
13088
  member,
12537
13089
  ...checkedIn[account.id] === void 0 ? {} : { checkedInToday: checkedIn[account.id] },
13090
+ ...growthRedeemed[account.id] === true ? { growthRedeemedToday: true } : {},
13091
+ ...growthActive[account.id] === true ? { growthActiveToday: true } : {},
12538
13092
  ...(() => {
12539
13093
  const views = claimable[account.id];
12540
13094
  if (views === void 0 || views.length === 0) return {};
@@ -12552,10 +13106,20 @@ async function workBuddyWebPool(deps, region, fast = false) {
12552
13106
  enabled: preferences.enabled,
12553
13107
  checkinSupported: pool.checkinSupported?.(region) === true,
12554
13108
  ...preferences.autoCheckin !== true ? {} : { autoCheckin: true },
13109
+ ...preferences.growthRedeem !== true ? {} : { growthRedeem: true },
13110
+ ...preferences.growthActivity !== true ? {} : { growthActivity: true },
12555
13111
  ...(() => {
12556
13112
  const today = pool.autoCheckinToday?.(region);
12557
13113
  return today === void 0 ? {} : { autoCheckinToday: today };
12558
13114
  })(),
13115
+ ...(() => {
13116
+ const today = pool.growthRedeemToday?.(region);
13117
+ return today === void 0 ? {} : { growthRedeemToday: today };
13118
+ })(),
13119
+ ...(() => {
13120
+ const today = pool.growthActivityToday?.(region);
13121
+ return today === void 0 ? {} : { growthActivityToday: today };
13122
+ })(),
12559
13123
  ...target.modelId === void 0 ? {} : { targetModelId: target.modelId },
12560
13124
  ...target.staleModelId === void 0 ? {} : { staleTargetModelId: target.staleModelId },
12561
13125
  targetModelSource: target.source,
@@ -12849,6 +13413,16 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12849
13413
  rows: await pool.checkin(region)
12850
13414
  });
12851
13415
  }
13416
+ if (action === "growth-redeem" || action === "growth-activity") {
13417
+ if (pool.growthRun === void 0) return json(res, 503, {
13418
+ reason: "pool-unavailable",
13419
+ error: "pool growth action unavailable"
13420
+ });
13421
+ return json(res, 200, {
13422
+ action,
13423
+ rows: await pool.growthRun(region, action)
13424
+ });
13425
+ }
12852
13426
  if (pool.test === void 0) return json(res, 503, {
12853
13427
  reason: "pool-unavailable",
12854
13428
  error: "pool test unavailable"
@@ -13328,6 +13902,8 @@ const poolConfig = z.object({
13328
13902
  * background path spend a request per account per day learning a refusal.
13329
13903
  */
13330
13904
  autoCheckin: z.boolean().default(false).description("Claim the daily check-in automatically for the accounts checked into this pool (opt-in). Idempotent: an account already checked in today is reported, never re-claimed. Only the CN region has a daily check-in."),
13905
+ growthRedeem: z.boolean().default(false).description("Redeem claimable streak-growth tiers automatically (opt-in, both regions). Only tiers the gateway marks available are written; a locked tier is skipped. Idempotent across repeat runs."),
13906
+ growthActivity: z.boolean().default(false).description("Light up \"active today\" via one console ACP session per account per day (opt-in, both regions). Spends a small amount of credit. Idempotent: an already-active account sends no session."),
13331
13907
  orderAccountIds: z.array(z.string()).default([]).description("The user's hand-ordered pool order, as account ids. Independent of membership: an id need not be checked in (it only takes effect once the account is a member), and ids not listed sort last. Separate from memberAccountIds so reordering never conflicts with, or is destroyed by, a membership edit.")
13332
13908
  });
13333
13909
  const regionStateConfig = z.object({
@@ -13937,35 +14513,15 @@ function apply(ctx, config) {
13937
14513
  };
13938
14514
  })());
13939
14515
  /**
13940
- * How long a check-in reading is reused before asking the upstream again.
13941
- *
13942
- * The card polls the usage route every 60 seconds, but "did this account
13943
- * check in today" changes only when a check-in runs or the day rolls over.
13944
- * Without a cache, a 10-account pool cost ~14,400 upstream requests a day for
13945
- * an answer that was almost always identical.
13946
- */
13947
- const CHECKIN_CACHE_MS = 6e5;
13948
- /**
13949
- * Per-region, per-account check-in readings.
13950
- *
13951
- * Invalidated by this plugin's own check-in batch (the only writer that can
13952
- * change the answer during a session), so the user sees their result
13953
- * immediately instead of waiting out the TTL.
13954
- *
13955
- * A reading is ALSO bounded by the local day, not just by the TTL — see
13956
- * `checkinReadingFresh`. Both readers go through it, because an entry is an
13957
- * answer to "has this account checked in TODAY" and a `true` read at 23:58
13958
- * must not be served at 00:08.
13959
- */
13960
- const checkinStateCache = {};
13961
- /**
13962
14516
  * Per-region, per-account benefit readings (issue #79).
13963
14517
  *
13964
- * Same shape and same reasoning as `checkinStateCache`: claim state changes
13965
- * when a human acts on the web page or in the desktop app, not spontaneously,
13966
- * so a per-poll read of two endpoints per account would be thousands of
13967
- * requests a day to learn nothing. Coarser than the check-in TTL because a
13968
- * benefit window is measured in days, not hours.
14518
+ * "Did this account check in today" is NOT cached here any more: it lives in
14519
+ * the persistent done-today memory (`daily-done-store`), so a fact observed
14520
+ * once is never re-read that day — not even after a restart. Benefit claim
14521
+ * state changes when a human acts on the web page or in the desktop app, not
14522
+ * spontaneously, so a per-poll read of two endpoints per account would be
14523
+ * thousands of requests a day to learn nothing. Its window is measured in
14524
+ * days, not hours.
13969
14525
  */
13970
14526
  const benefitStateCache = {};
13971
14527
  const settingsNs = settingsNamespaceOf(ctx);
@@ -15048,22 +15604,14 @@ function apply(ctx, config) {
15048
15604
  if (region !== "cn" || !poolPreferencesOf(current(), region).enabled) return {};
15049
15605
  const store = stacks[region].store;
15050
15606
  const accounts = await store.accounts();
15051
- const now = Date.now();
15052
15607
  const entries = await Promise.all(accounts.map(async (account) => {
15053
15608
  if (account.enterprise === true) return void 0;
15054
- const cached = checkinStateCache[region]?.[account.id];
15055
- if (cached !== void 0 && checkinReadingFresh(cached.atMs, now, CHECKIN_CACHE_MS)) return [account.id, cached.checkedIn];
15609
+ if (await isDoneToday("checkin", region, account.id)) return [account.id, true];
15056
15610
  const credential = await store.credentialFor(account.id).catch(() => void 0);
15057
15611
  if (credential === void 0) return void 0;
15058
15612
  const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
15059
15613
  if (status === void 0 || !status.active) return void 0;
15060
- checkinStateCache[region] = {
15061
- ...checkinStateCache[region],
15062
- [account.id]: {
15063
- checkedIn: status.todayCheckedIn,
15064
- atMs: now
15065
- }
15066
- };
15614
+ if (status.todayCheckedIn) await markDoneToday("checkin", region, [account.id]);
15067
15615
  return [account.id, status.todayCheckedIn];
15068
15616
  }));
15069
15617
  return Object.fromEntries(entries.filter((entry) => entry !== void 0));
@@ -15076,17 +15624,15 @@ function apply(ctx, config) {
15076
15624
  * on one request per account. An unmeasured account is absent, which the
15077
15625
  * card already renders as unknown rather than as "not checked in".
15078
15626
  */
15079
- cachedCheckedInToday(region) {
15080
- if (!poolPreferencesOf(current(), region).enabled) return {};
15081
- const now = Date.now();
15082
- const state = checkinStateCache[region] ?? {};
15083
- const cached = {};
15084
- for (const [accountId, entry] of Object.entries(state)) {
15085
- if (!checkinReadingFresh(entry.atMs, now, CHECKIN_CACHE_MS)) continue;
15086
- cached[accountId] = entry.checkedIn;
15087
- }
15088
- return cached;
15089
- },
15627
+ /**
15628
+ * Today's checked-in accounts for the first paint (issue #77).
15629
+ *
15630
+ * Reads the persistent done-today memory and NOTHING else: no upstream
15631
+ * request, so painting never blocks, and — unlike the old in-memory TTL
15632
+ * cache — it survives a restart within the same day. An account with no
15633
+ * record is absent, which the card already renders as unknown.
15634
+ */
15635
+ cachedCheckedInToday: (region) => doneTodayMap("checkin", region),
15090
15636
  /**
15091
15637
  * Claimable promotional benefits per account (issue #79).
15092
15638
  *
@@ -15185,13 +15731,56 @@ function apply(ctx, config) {
15185
15731
  if (state === void 0) return void 0;
15186
15732
  return todaySummary(state, Date.now());
15187
15733
  },
15734
+ /**
15735
+ * Today's growth-job progress (issue #286), from the runner's own in-memory
15736
+ * state — same source the tick writes, so the card cannot drift from what
15737
+ * actually ran. `undefined` when the switch is off or nothing has run yet.
15738
+ */
15739
+ growthRedeemToday: (region) => growthTodayOf("growth-redeem", region),
15740
+ growthActivityToday: (region) => growthTodayOf("growth-activity", region),
15741
+ /**
15742
+ * Per-account growth completion for the row stamps (issue #286). Backed by
15743
+ * the runner's day state: an account is "done" once today's job addressed
15744
+ * it, regardless of whether it redeemed or was already active. No upstream
15745
+ * read, so it is safe on the card's poll.
15746
+ */
15747
+ growthDoneAccountIds: async (region, cap) => {
15748
+ const map = { ...await doneTodayMap(cap, region) };
15749
+ const state = growthState[growthKey(cap, region)] ?? await readGrowthState(cap, region);
15750
+ if (state !== void 0 && state.day === localDayKey(Date.now())) for (const id of state.doneAccountIds) map[id] = true;
15751
+ return map;
15752
+ },
15753
+ /**
15754
+ * Manual "run now" for a growth job (issue #286). Same batch + state as
15755
+ * the timer, but ignores the opt-in switch and the backoff clock: the user
15756
+ * asked for it now. Returns check-in-shaped rows for the shared log UI.
15757
+ */
15758
+ growthRun: async (region, action) => {
15759
+ const cap = action === "growth-redeem" ? "growth-redeem" : "growth-activity";
15760
+ const key = growthKey(cap, region);
15761
+ const nowMs = Date.now();
15762
+ const stored = growthState[key] ?? await readGrowthState(cap, region);
15763
+ const state = stored === void 0 || stored.day !== localDayKey(nowMs) ? emptyAutoCheckinState(localDayKey(nowMs)) : stored;
15764
+ const all = (await poolMemberAccounts(region)).map((account) => ({
15765
+ accountId: account.id,
15766
+ accountName: account.accountName
15767
+ }));
15768
+ const rows = await runGrowthBatch(cap, region, all);
15769
+ const folded = foldGrowthAttempt(state, rows.map((row) => row.accountId), all.length, nowMs);
15770
+ growthState[key] = folded;
15771
+ await writeGrowthState(cap, region, folded);
15772
+ await markDoneToday(cap, region, rows.map((row) => row.accountId));
15773
+ return rows.map((row) => ({
15774
+ accountId: row.accountId,
15775
+ accountName: row.accountName,
15776
+ status: row.status === "done" ? "claimed" : row.status === "skipped" ? "already" : "failed",
15777
+ ...row.credit === void 0 ? {} : { credit: row.credit },
15778
+ ...row.message === void 0 ? {} : { message: row.message }
15779
+ }));
15780
+ },
15188
15781
  checkin: async (region) => {
15189
15782
  const rows = await checkinAllAccounts(await poolTargets(region), poolRunnerDeps(region));
15190
- for (const row of rows) {
15191
- if (row.status === "failed") continue;
15192
- const cached = checkinStateCache[region];
15193
- if (cached !== void 0) delete cached[row.accountId];
15194
- }
15783
+ await markDoneToday("checkin", region, rows.filter((row) => row.status === "claimed" || row.status === "already").map((row) => row.accountId));
15195
15784
  if (rows.some((row) => row.status !== "failed")) {
15196
15785
  await poolMembersOf(region);
15197
15786
  await applyPoolSelection(region);
@@ -15760,7 +16349,9 @@ function apply(ctx, config) {
15760
16349
  ...probeInputTokens === void 0 ? {} : { probeInputTokens },
15761
16350
  memberAccountIds: pool?.memberAccountIds ?? [],
15762
16351
  orderAccountIds: pool?.orderAccountIds ?? [],
15763
- autoCheckin: pool?.autoCheckin === true
16352
+ autoCheckin: pool?.autoCheckin === true,
16353
+ growthRedeem: pool?.growthRedeem === true,
16354
+ growthActivity: pool?.growthActivity === true
15764
16355
  };
15765
16356
  };
15766
16357
  /**
@@ -15881,11 +16472,7 @@ function apply(ctx, config) {
15881
16472
  return;
15882
16473
  }
15883
16474
  const rows = await checkinAllAccounts(targets, poolRunnerDeps(region));
15884
- for (const row of rows) {
15885
- if (row.status === "failed") continue;
15886
- const cached = checkinStateCache[region];
15887
- if (cached !== void 0) delete cached[row.accountId];
15888
- }
16475
+ await markDoneToday("checkin", region, rows.filter((row) => row.status === "claimed" || row.status === "already").map((row) => row.accountId));
15889
16476
  if (rows.some((row) => row.status !== "failed")) {
15890
16477
  await poolMembersOf(region);
15891
16478
  await applyPoolSelection(region);
@@ -15945,6 +16532,134 @@ function apply(ctx, config) {
15945
16532
  ctx.effect(() => () => {
15946
16533
  stopAutoCheckin();
15947
16534
  });
16535
+ const growthTimers = {};
16536
+ const growthState = {};
16537
+ const growthRunning = {};
16538
+ const GROWTH_IDLE_MS = AUTO_CHECKIN_IDLE_MS;
16539
+ const growthKey = (cap, region) => `${cap}:${region}`;
16540
+ /** Today's summary for one growth job, for the card's status line. */
16541
+ function growthTodayOf(cap, region) {
16542
+ if (!growthEnabled(cap, region)) return void 0;
16543
+ const state = growthState[growthKey(cap, region)];
16544
+ return growthTodaySummary(state, localDayKey(Date.now()));
16545
+ }
16546
+ /** Both growth capabilities apply to both regions — unlike check-in. */
16547
+ const GROWTH_REGIONS = ["cn", "global"];
16548
+ const GROWTH_CAPABILITIES = ["growth-redeem", "growth-activity"];
16549
+ function growthEnabled(cap, region) {
16550
+ const prefs = poolPreferencesOf(current(), region);
16551
+ if (!prefs.enabled) return false;
16552
+ return cap === "growth-redeem" ? prefs.growthRedeem : prefs.growthActivity;
16553
+ }
16554
+ /** The ACP model for one region: its first advertised model, or a safe fallback. */
16555
+ function growthAcpModel(region) {
16556
+ return displayModels(current(), region).filter((model) => !isRouterModelId(model.id))[0]?.id ?? (region === "cn" ? "hy3" : "deepseek-v4.1-flash");
16557
+ }
16558
+ /**
16559
+ * Execute one growth batch over the given targets — the ONE implementation
16560
+ * both the background timer and the manual "run now" button call. Never throws
16561
+ * at the batch level; each account's problem is captured on its own row by the
16562
+ * runner. Returns the raw growth rows (done/skipped/failed).
16563
+ */
16564
+ async function runGrowthBatch(cap, region, targets) {
16565
+ const store = stacks[region].store;
16566
+ if (cap === "growth-redeem") return redeemGrowthAll(targets, {
16567
+ credentialFor: (id) => store.credentialFor(id),
16568
+ readStreak: (credential) => client.fetchGrowthStreak(credential),
16569
+ redeem: (credential, tier) => client.redeemGrowthTier(credential, tier)
16570
+ });
16571
+ const model = growthAcpModel(region);
16572
+ return activateGrowthAll(targets, async (accountId) => {
16573
+ const credential = await store.credentialFor(accountId);
16574
+ if (credential === void 0) return {
16575
+ status: "failed",
16576
+ reason: "no stored credential"
16577
+ };
16578
+ const host = growthHostOf(credential);
16579
+ return activateGrowth({
16580
+ base: host,
16581
+ accessToken: credential.accessToken,
16582
+ origin: host,
16583
+ model,
16584
+ heatmap: async () => {
16585
+ const cell = await client.fetchGrowthToday(credential);
16586
+ return cell === void 0 ? void 0 : {
16587
+ isActive: cell.isActive,
16588
+ score: cell.score
16589
+ };
16590
+ }
16591
+ });
16592
+ });
16593
+ }
16594
+ /** Run one capability for one region across its pooled members. Never throws. */
16595
+ async function growthTick(cap, region) {
16596
+ const key = growthKey(cap, region);
16597
+ if (growthRunning[key] === true) return;
16598
+ growthRunning[key] = true;
16599
+ try {
16600
+ if (!growthEnabled(cap, region)) return;
16601
+ const nowMs = Date.now();
16602
+ const today = localDayKey(nowMs);
16603
+ const stored = growthState[key] ?? await readGrowthState(cap, region);
16604
+ const state = stored === void 0 || stored.day !== today ? emptyAutoCheckinState(today) : stored;
16605
+ growthState[key] = state;
16606
+ const all = (await poolMemberAccounts(region)).map((account) => ({
16607
+ accountId: account.id,
16608
+ accountName: account.accountName
16609
+ }));
16610
+ const targets = growthPendingTargets(all, state);
16611
+ if (targets.length === 0) {
16612
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16613
+ return;
16614
+ }
16615
+ const rows = await runGrowthBatch(cap, region, targets);
16616
+ const folded = foldGrowthAttempt(state, rows.map((row) => row.accountId), all.length, nowMs);
16617
+ growthState[key] = folded;
16618
+ await writeGrowthState(cap, region, folded);
16619
+ await markDoneToday(cap, region, rows.map((row) => row.accountId));
16620
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16621
+ } catch (error) {
16622
+ ctx.logger.warn(`dsh-connect-workbuddy: growth tick failed (${cap}/${region})`, error);
16623
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16624
+ } finally {
16625
+ growthRunning[key] = false;
16626
+ }
16627
+ }
16628
+ function scheduleGrowth(cap, region, delayMs) {
16629
+ const key = growthKey(cap, region);
16630
+ const existing = growthTimers[key];
16631
+ if (existing !== void 0) clearTimeout(existing);
16632
+ const timer = setTimeout(() => {
16633
+ growthTick(cap, region);
16634
+ }, delayMs);
16635
+ timer.unref?.();
16636
+ growthTimers[key] = timer;
16637
+ }
16638
+ function syncGrowth() {
16639
+ for (const cap of GROWTH_CAPABILITIES) for (const region of GROWTH_REGIONS) {
16640
+ const key = growthKey(cap, region);
16641
+ if (growthEnabled(cap, region)) {
16642
+ if (growthTimers[key] === void 0) scheduleGrowth(cap, region, 0);
16643
+ continue;
16644
+ }
16645
+ const timer = growthTimers[key];
16646
+ if (timer !== void 0) {
16647
+ clearTimeout(timer);
16648
+ delete growthTimers[key];
16649
+ }
16650
+ }
16651
+ }
16652
+ function stopGrowth() {
16653
+ for (const timer of Object.values(growthTimers)) clearTimeout(timer);
16654
+ for (const key of Object.keys(growthTimers)) delete growthTimers[key];
16655
+ }
16656
+ function refreshGrowthSchedules() {
16657
+ syncGrowth();
16658
+ }
16659
+ refreshGrowthSchedules();
16660
+ ctx.effect(() => () => {
16661
+ stopGrowth();
16662
+ });
15948
16663
  ctx.inject(["settings"], (sctx) => {
15949
16664
  const settings = sctx.settings;
15950
16665
  ctx.effect(() => settings.configure({ auto: true }, ctx.fiber));
@@ -15979,6 +16694,7 @@ function apply(ctx, config) {
15979
16694
  ctx.on("loader/volatile-update", () => {
15980
16695
  applySelection(current());
15981
16696
  syncAutoCheckin();
16697
+ refreshGrowthSchedules();
15982
16698
  syncDeviceSdk();
15983
16699
  });
15984
16700
  applySelection(config);