dsh-connect-workbuddy 5.25.2 → 5.29.1

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-C65HMbxG.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$2 = 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$2) 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$2,
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$2,
11591
11591
  probes
11592
11592
  }, null, 2)}\n`, {
11593
11593
  mode: 384,
@@ -11819,11 +11819,11 @@ function pendingTargets(targets, state) {
11819
11819
  * @module dsh-connect-workbuddy/auto-checkin-store
11820
11820
  */
11821
11821
  /** On-disk format version; readers reject anything else. */
11822
- const STORE_FORMAT_VERSION = 1;
11822
+ const STORE_FORMAT_VERSION$1 = 1;
11823
11823
  /** Filename prefix for one region's auto-check-in memory. */
11824
11824
  const AUTO_CHECKIN_PREFIX = ".workbuddy-auto-checkin";
11825
11825
  /** Whether a parsed value looks like a stored state. */
11826
- function isState(value) {
11826
+ function isState$1(value) {
11827
11827
  if (typeof value !== "object" || value === null) return false;
11828
11828
  const candidate = value;
11829
11829
  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 +11854,11 @@ async function readAutoCheckinState(region) {
11854
11854
  }
11855
11855
  if (typeof parsed !== "object" || parsed === null) return void 0;
11856
11856
  const document = parsed;
11857
- if (document.version !== STORE_FORMAT_VERSION) return void 0;
11857
+ if (document.version !== STORE_FORMAT_VERSION$1) return void 0;
11858
11858
  const regions = document.regions;
11859
11859
  if (typeof regions !== "object" || regions === null) return void 0;
11860
11860
  const state = regions[region];
11861
- return isState(state) ? state : void 0;
11861
+ return isState$1(state) ? state : void 0;
11862
11862
  }
11863
11863
  /**
11864
11864
  * Write one region's state, merging into whatever the file already holds.
@@ -11876,7 +11876,7 @@ async function writeAutoCheckinState(region, state) {
11876
11876
  [region]: state
11877
11877
  };
11878
11878
  await writeFileAtomic(path, `${JSON.stringify({
11879
- version: STORE_FORMAT_VERSION,
11879
+ version: STORE_FORMAT_VERSION$1,
11880
11880
  regions
11881
11881
  }, null, 2)}\n`, {
11882
11882
  mode: 384,
@@ -11901,14 +11901,457 @@ async function readDocument(path) {
11901
11901
  }
11902
11902
  if (typeof parsed !== "object" || parsed === null) return {};
11903
11903
  const document = parsed;
11904
- if (document.version !== STORE_FORMAT_VERSION) return {};
11904
+ if (document.version !== STORE_FORMAT_VERSION$1) return {};
11905
11905
  const regions = document.regions;
11906
11906
  if (typeof regions !== "object" || regions === null) return {};
11907
11907
  const clean = {};
11908
- for (const [key, value] of Object.entries(regions)) if (isState(value)) clean[key] = value;
11908
+ for (const [key, value] of Object.entries(regions)) if (isState$1(value)) clean[key] = value;
11909
11909
  return clean;
11910
11910
  }
11911
11911
  //#endregion
11912
+ //#region src/growth-acp.ts
11913
+ /** Normalize a session link to its ACP endpoint, without duplicating the suffix. */
11914
+ function resolveAcpEndpoint(link) {
11915
+ let value = (link ?? "").trim().replace(/^http:\/\//u, "https://").replace(/\/+$/u, "");
11916
+ if (value === "") return "";
11917
+ if (/\/api\/v1\/acp$/u.test(value) || /\/acp$/u.test(value)) return value;
11918
+ return `${value}/api/v1/acp`;
11919
+ }
11920
+ /** Parse an SSE body: yield the JSON payloads of `data:` lines with the given id. */
11921
+ function rpcResultFromSse(text, id) {
11922
+ for (const line of text.split(/\r?\n/u)) {
11923
+ const trimmed = line.trim();
11924
+ if (!trimmed.startsWith("data:")) continue;
11925
+ let parsed;
11926
+ try {
11927
+ parsed = JSON.parse(trimmed.slice(5).trim());
11928
+ } catch {
11929
+ continue;
11930
+ }
11931
+ if (typeof parsed !== "object" || parsed === null) continue;
11932
+ const message = parsed;
11933
+ if (message["id"] !== id) continue;
11934
+ if (message["error"] !== void 0) throw new Error(`ACP RPC error: ${String(message["error"]).slice(0, 200)}`);
11935
+ return typeof message["result"] === "object" && message["result"] !== null ? message["result"] : {};
11936
+ }
11937
+ }
11938
+ /** Send one console ACP session; returns its conversation id. Throws on failure. */
11939
+ async function sendAcpSession(options) {
11940
+ const doFetch = options.fetch ?? globalThis.fetch;
11941
+ const base = options.base.replace(/\/+$/u, "");
11942
+ const ua = options.userAgent ?? "WorkBuddy/5.8.3";
11943
+ const jsonHeaders = (token) => ({
11944
+ "accept": "application/json, text/plain, */*",
11945
+ "content-type": "application/json",
11946
+ "x-codebuddy-request": "1",
11947
+ "x-client-platform": "web",
11948
+ "user-agent": ua,
11949
+ "authorization": `Bearer ${token}`,
11950
+ "origin": options.origin,
11951
+ "referer": `${options.origin.replace(/\/+$/u, "")}/`
11952
+ });
11953
+ let created;
11954
+ let lastError = "";
11955
+ for (const withPlugins of [true, false]) {
11956
+ const body = {
11957
+ prompt: options.prompt ?? "你好",
11958
+ model: options.model
11959
+ };
11960
+ if (withPlugins) body["plugins"] = [];
11961
+ try {
11962
+ const response = await doFetch(`${base}/console/as/conversations/`, {
11963
+ method: "POST",
11964
+ headers: jsonHeaders(options.accessToken),
11965
+ body: JSON.stringify(body),
11966
+ signal: AbortSignal.timeout(6e4)
11967
+ });
11968
+ if (response.ok) {
11969
+ const parsed = await response.json();
11970
+ created = typeof parsed === "object" && parsed !== null ? parsed : void 0;
11971
+ break;
11972
+ }
11973
+ lastError = `HTTP ${response.status}`;
11974
+ if (response.status !== 400 && response.status !== 404) break;
11975
+ } catch (error) {
11976
+ lastError = String(error);
11977
+ break;
11978
+ }
11979
+ }
11980
+ if (created === void 0) throw new Error(`ACP create conversation failed: ${lastError}`);
11981
+ const data = typeof created["data"] === "object" && created["data"] !== null ? created["data"] : created;
11982
+ const id = String(data["id"] ?? data["conversationId"] ?? data["info"]?.id ?? "");
11983
+ if (id === "") throw new Error("ACP create response had no conversation id");
11984
+ let session = typeof data["session"] === "object" && data["session"] !== null ? data["session"] : void 0;
11985
+ if (session === void 0 || typeof session["link"] !== "string" || typeof session["token"] !== "string") {
11986
+ const response = await doFetch(`${base}/console/as/conversations/${encodeURIComponent(id)}/session`, {
11987
+ method: "GET",
11988
+ headers: jsonHeaders(options.accessToken),
11989
+ signal: AbortSignal.timeout(6e4)
11990
+ });
11991
+ if (!response.ok) throw new Error(`ACP fetch session failed: HTTP ${response.status}`);
11992
+ const parsed = await response.json();
11993
+ const sdata = typeof parsed === "object" && parsed !== null ? parsed : {};
11994
+ session = typeof sdata["data"] === "object" && sdata["data"] !== null ? sdata["data"] : sdata;
11995
+ }
11996
+ const link = resolveAcpEndpoint(String(session?.["link"] ?? session?.["endpoint"] ?? ""));
11997
+ const sessionToken = String(session?.["token"] ?? session?.["accessToken"] ?? "");
11998
+ const sessionId = String(session?.["sessionId"] ?? session?.["session_id"] ?? "");
11999
+ if (link === "" || sessionToken === "" || sessionId === "") throw new Error("ACP session response missing link/token/sessionId");
12000
+ const connectionId = (await doFetch(link, {
12001
+ method: "GET",
12002
+ headers: {
12003
+ ...jsonHeaders(sessionToken),
12004
+ "accept": "text/event-stream"
12005
+ },
12006
+ signal: AbortSignal.timeout(6e4)
12007
+ })).headers.get("acp-connection-id") ?? "";
12008
+ if (connectionId === "") throw new Error("ACP SSE response missing acp-connection-id");
12009
+ const rpc = async (method, params, rpcId) => {
12010
+ const response = await doFetch(link, {
12011
+ method: "POST",
12012
+ headers: {
12013
+ ...jsonHeaders(sessionToken),
12014
+ "accept": "application/json, text/event-stream",
12015
+ "acp-connection-id": connectionId
12016
+ },
12017
+ body: JSON.stringify({
12018
+ jsonrpc: "2.0",
12019
+ id: rpcId,
12020
+ method,
12021
+ params
12022
+ }),
12023
+ signal: AbortSignal.timeout(6e4)
12024
+ });
12025
+ if (!response.ok) throw new Error(`ACP RPC ${method} failed: HTTP ${response.status}`);
12026
+ rpcResultFromSse(await response.text(), rpcId);
12027
+ };
12028
+ await rpc("initialize", {
12029
+ protocolVersion: 1,
12030
+ clientInfo: {
12031
+ name: "dsh-connect-workbuddy",
12032
+ version: "1.0"
12033
+ },
12034
+ clientCapabilities: {
12035
+ fs: {
12036
+ readTextFile: false,
12037
+ writeTextFile: false
12038
+ },
12039
+ _meta: { "codebuddy.ai": {
12040
+ question: false,
12041
+ terminalOutput: false
12042
+ } }
12043
+ }
12044
+ }, 1);
12045
+ await rpc("session/prompt", {
12046
+ sessionId,
12047
+ prompt: [{
12048
+ type: "text",
12049
+ text: options.prompt ?? "你好"
12050
+ }]
12051
+ }, 2);
12052
+ try {
12053
+ await doFetch(link, {
12054
+ method: "DELETE",
12055
+ headers: {
12056
+ ...jsonHeaders(sessionToken),
12057
+ "acp-connection-id": connectionId
12058
+ },
12059
+ signal: AbortSignal.timeout(1e4)
12060
+ });
12061
+ } catch {}
12062
+ return id;
12063
+ }
12064
+ /**
12065
+ * Ensure the account is active today. Idempotent: already-active sends nothing.
12066
+ * After sending, polls the heatmap up to `verifyAttempts` times to confirm the
12067
+ * write landed before reporting success.
12068
+ */
12069
+ async function activateGrowth(options) {
12070
+ const before = await options.heatmap();
12071
+ if (before?.isActive === true) return {
12072
+ status: "already-active",
12073
+ score: before.score
12074
+ };
12075
+ let conversationId;
12076
+ try {
12077
+ conversationId = await sendAcpSession(options);
12078
+ } catch (error) {
12079
+ return {
12080
+ status: "failed",
12081
+ reason: String(error)
12082
+ };
12083
+ }
12084
+ const sleep = options.sleep ?? (async (ms) => {
12085
+ await new Promise((resolve) => setTimeout(resolve, ms));
12086
+ });
12087
+ const attempts = options.verifyAttempts ?? 4;
12088
+ const gap = options.verifyIntervalMs ?? 1500;
12089
+ for (let i = 0; i < attempts; i += 1) {
12090
+ if (i > 0) await sleep(gap);
12091
+ const now = await options.heatmap();
12092
+ if (now?.isActive === true) return {
12093
+ status: "activated",
12094
+ score: now.score,
12095
+ conversationId
12096
+ };
12097
+ }
12098
+ return {
12099
+ status: "failed",
12100
+ conversationId,
12101
+ reason: "ACP session sent but heatmap today.is_active stayed false"
12102
+ };
12103
+ }
12104
+ //#endregion
12105
+ //#region src/growth-run.ts
12106
+ /** Accounts still due today: pool members minus those already settled. */
12107
+ function growthPendingTargets(targets, state) {
12108
+ const done = new Set(state?.doneAccountIds ?? []);
12109
+ return targets.filter((target) => !done.has(target.accountId));
12110
+ }
12111
+ /**
12112
+ * Fold one growth attempt into today's state: every addressed account is marked
12113
+ * settled. No backoff, no `lastError` — the card shows a plain done/total count.
12114
+ * `scopeSize` is the REAL member count passed by the caller (never accumulated),
12115
+ * so a manual run cannot inflate the denominator the way the earlier bug did.
12116
+ */
12117
+ function foldGrowthAttempt(state, attemptedIds, scopeSize, nowMs) {
12118
+ const done = /* @__PURE__ */ new Set([...state.doneAccountIds, ...attemptedIds]);
12119
+ return {
12120
+ day: state.day,
12121
+ doneAccountIds: [...done],
12122
+ scopeSize,
12123
+ failures: 0,
12124
+ lastAttemptAtMs: nowMs
12125
+ };
12126
+ }
12127
+ /** A day summary with NO pending/retry/failure fields — just done of total. */
12128
+ function growthTodaySummary(state, day) {
12129
+ if (state === void 0 || state.day !== day) return void 0;
12130
+ return {
12131
+ done: Math.min(state.doneAccountIds.length, state.scopeSize),
12132
+ total: state.scopeSize
12133
+ };
12134
+ }
12135
+ async function pause(deps, issued) {
12136
+ if (issued > 0) await (deps.wait ?? (async (ms) => {
12137
+ await new Promise((r) => setTimeout(r, ms));
12138
+ }))(400);
12139
+ }
12140
+ /**
12141
+ * Redeem every claimable tier for every target, one account at a time.
12142
+ * Only tiers the gateway reported `available` are written — a `locked` tier is
12143
+ * never redeemed, so a repeated run is a no-op rather than a refused write.
12144
+ * Never throws: each problem becomes a `failed` row and the batch continues.
12145
+ */
12146
+ async function redeemGrowthAll(targets, deps) {
12147
+ const rows = [];
12148
+ let issued = 0;
12149
+ for (const target of targets) {
12150
+ const base = {
12151
+ accountId: target.accountId,
12152
+ accountName: target.accountName
12153
+ };
12154
+ let credential;
12155
+ try {
12156
+ credential = await deps.credentialFor(target.accountId);
12157
+ } catch (error) {
12158
+ rows.push({
12159
+ ...base,
12160
+ status: "failed",
12161
+ message: String(error)
12162
+ });
12163
+ continue;
12164
+ }
12165
+ if (credential === void 0) {
12166
+ rows.push({
12167
+ ...base,
12168
+ status: "failed",
12169
+ message: "no stored credential for this account"
12170
+ });
12171
+ continue;
12172
+ }
12173
+ let streak;
12174
+ try {
12175
+ streak = await deps.readStreak(credential);
12176
+ } catch (error) {
12177
+ rows.push({
12178
+ ...base,
12179
+ status: "failed",
12180
+ message: String(error)
12181
+ });
12182
+ continue;
12183
+ }
12184
+ if (streak === void 0) {
12185
+ rows.push({
12186
+ ...base,
12187
+ status: "failed",
12188
+ message: "growth streak was not readable"
12189
+ });
12190
+ continue;
12191
+ }
12192
+ if (streak.availableTiers.length === 0) {
12193
+ rows.push({
12194
+ ...base,
12195
+ status: "skipped",
12196
+ message: "no tier is available to redeem"
12197
+ });
12198
+ continue;
12199
+ }
12200
+ await pause(deps, issued);
12201
+ issued += 1;
12202
+ let credit = 0;
12203
+ const done = [];
12204
+ let failure = "";
12205
+ for (const tier of streak.availableTiers) try {
12206
+ const result = await deps.redeem(credential, tier);
12207
+ credit += result.credit;
12208
+ done.push(tier);
12209
+ } catch (error) {
12210
+ failure = String(error);
12211
+ break;
12212
+ }
12213
+ if (failure !== "" && done.length === 0) rows.push({
12214
+ ...base,
12215
+ status: "failed",
12216
+ message: failure
12217
+ });
12218
+ else rows.push({
12219
+ ...base,
12220
+ status: "done",
12221
+ credit,
12222
+ message: `redeemed ${done.join(",")}${failure === "" ? "" : `; stopped: ${failure}`}`
12223
+ });
12224
+ }
12225
+ return rows;
12226
+ }
12227
+ /**
12228
+ * Ensure "active today" for every target, one account at a time. The caller
12229
+ * supplies `activateOne` so model selection and ACP details stay outside this
12230
+ * module. Idempotency lives in the activate function (already-active sends no
12231
+ * session), so a repeated batch is safe.
12232
+ */
12233
+ async function activateGrowthAll(targets, activateOne, wait) {
12234
+ const rows = [];
12235
+ let issued = 0;
12236
+ for (const target of targets) {
12237
+ let result;
12238
+ try {
12239
+ result = await activateOne(target.accountId);
12240
+ } catch (error) {
12241
+ rows.push({
12242
+ accountId: target.accountId,
12243
+ accountName: target.accountName,
12244
+ status: "failed",
12245
+ message: String(error)
12246
+ });
12247
+ continue;
12248
+ }
12249
+ if (result.status === "already-active") {
12250
+ rows.push({
12251
+ accountId: target.accountId,
12252
+ accountName: target.accountName,
12253
+ status: "skipped",
12254
+ message: "already active today"
12255
+ });
12256
+ continue;
12257
+ }
12258
+ if (result.status === "activated") {
12259
+ if (issued > 0) await (wait ?? (async (ms) => {
12260
+ await new Promise((r) => setTimeout(r, ms));
12261
+ }))(400);
12262
+ issued += 1;
12263
+ rows.push({
12264
+ accountId: target.accountId,
12265
+ accountName: target.accountName,
12266
+ status: "done",
12267
+ message: "activated"
12268
+ });
12269
+ continue;
12270
+ }
12271
+ rows.push({
12272
+ accountId: target.accountId,
12273
+ accountName: target.accountName,
12274
+ status: "failed",
12275
+ message: result.reason ?? "activation failed"
12276
+ });
12277
+ }
12278
+ return rows;
12279
+ }
12280
+ //#endregion
12281
+ //#region src/growth-state-store.ts
12282
+ /**
12283
+ * On-disk memory for the two background growth capabilities (issue #286).
12284
+ *
12285
+ * Same discipline as `auto-checkin-store.ts`: one file per CAPABILITY + REGION
12286
+ * under `$DSH_HOME`, atomic + locked writes, `mode: 0o600`, no token and no
12287
+ * account name inside — only account ids and a short failure reason. Kept in a
12288
+ * separate file from auto-check-in so the three capabilities' `doneAccountIds`
12289
+ * can never overwrite each other: "checked in" ≠ "active" ≠ "redeemed".
12290
+ *
12291
+ * Reads and writes never throw. A corrupt file degrades to "nothing done
12292
+ * today", and a repeat run is idempotent by design.
12293
+ *
12294
+ * @module dsh-connect-workbuddy/growth-state-store
12295
+ */
12296
+ const STORE_FORMAT_VERSION = 1;
12297
+ /** Path for one capability + region. */
12298
+ function growthStatePath(capability, region) {
12299
+ return join(resolveDshHome(), `.workbuddy-${capability}.${region}.json`);
12300
+ }
12301
+ function isState(value) {
12302
+ if (typeof value !== "object" || value === null) return false;
12303
+ const candidate = value;
12304
+ 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");
12305
+ }
12306
+ /** Read one capability + region's state, or undefined when absent/corrupt. */
12307
+ async function readGrowthState(capability, region) {
12308
+ try {
12309
+ const raw = await readFile(growthStatePath(capability, region), "utf8");
12310
+ const parsed = JSON.parse(raw);
12311
+ if (typeof parsed !== "object" || parsed === null) return void 0;
12312
+ const document = parsed;
12313
+ if (document.version !== STORE_FORMAT_VERSION) return void 0;
12314
+ const regions = document.regions;
12315
+ if (typeof regions !== "object" || regions === null) return void 0;
12316
+ const state = regions[region];
12317
+ return isState(state) ? state : void 0;
12318
+ } catch {
12319
+ return;
12320
+ }
12321
+ }
12322
+ /** Write one capability + region's state, merging the sibling region. Never throws. */
12323
+ async function writeGrowthState(capability, region, state) {
12324
+ const path = growthStatePath(capability, region);
12325
+ try {
12326
+ await withFileLock(path, async () => {
12327
+ let existing = {};
12328
+ try {
12329
+ const raw = await readFile(path, "utf8");
12330
+ const parsed = JSON.parse(raw);
12331
+ if (typeof parsed === "object" && parsed !== null) {
12332
+ const doc = parsed;
12333
+ if (doc.version === STORE_FORMAT_VERSION && typeof doc.regions === "object" && doc.regions !== null) {
12334
+ const clean = {};
12335
+ for (const [key, value] of Object.entries(doc.regions)) if (isState(value)) clean[key] = value;
12336
+ existing = clean;
12337
+ }
12338
+ }
12339
+ } catch {}
12340
+ const document = {
12341
+ version: STORE_FORMAT_VERSION,
12342
+ regions: {
12343
+ ...existing,
12344
+ [region]: state
12345
+ }
12346
+ };
12347
+ await writeFileAtomic(path, `${JSON.stringify(document, null, 2)}\n`, {
12348
+ mode: 384,
12349
+ dirMode: 448
12350
+ });
12351
+ });
12352
+ } catch {}
12353
+ }
12354
+ //#endregion
11912
12355
  //#region src/web-status.ts
11913
12356
  /** Redact token-like content before it crosses to the browser. */
11914
12357
  function safeMessage(error) {
@@ -12263,6 +12706,24 @@ async function workBuddyAccountCredits(deps, region) {
12263
12706
  }));
12264
12707
  }
12265
12708
  /**
12709
+ * Decide what the user can do about a refused credential in one region.
12710
+ *
12711
+ * Shared by the two refusal paths: a credits/check-in read that was rejected
12712
+ * on an otherwise usable credential ({@link liveFigures}), and a `resolve()`
12713
+ * whose TOKEN REFRESH was rejected outright (issue #285 — the CN card hid all
12714
+ * of its accounts while the export dialog still saw them). The recovery answer
12715
+ * must not depend on which path noticed the refusal: both offer the same
12716
+ * "switch to a verified account / sign in again" advice.
12717
+ */
12718
+ async function credentialRecoveryOf(deps, region, rejectedAccountId) {
12719
+ return resolveCredentialRecovery({
12720
+ region,
12721
+ store: deps.store(region),
12722
+ ...rejectedAccountId === void 0 ? {} : { rejectedAccountId },
12723
+ probe: deps.accountUsable ?? (async () => false)
12724
+ });
12725
+ }
12726
+ /**
12266
12727
  * Read the selected account's live figures, and classify a refusal.
12267
12728
  *
12268
12729
  * Extracted so the first-paint path can omit it as a unit: the two calls here
@@ -12272,12 +12733,7 @@ async function workBuddyAccountCredits(deps, region) {
12272
12733
  async function liveFigures(deps, region, credential, selected) {
12273
12734
  const [creditsResult, checkinResult] = await Promise.allSettled([deps.client.fetchCredits(credential), deps.client.fetchCheckinStatus(credential)]);
12274
12735
  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
- });
12736
+ const recovery = !rejected ? void 0 : await credentialRecoveryOf(deps, region, selected?.id);
12281
12737
  return {
12282
12738
  ...creditsResult.status === "fulfilled" ? { credits: toCredits(creditsResult.value) } : { creditsError: safeMessage(creditsResult.reason) },
12283
12739
  ...checkinResult.status === "fulfilled" ? { checkin: checkinResult.value } : { checkinError: safeMessage(checkinResult.reason) },
@@ -12357,10 +12813,14 @@ async function workBuddyWebStatus(deps, region, options = {}) {
12357
12813
  if (credential === void 0) credential = await store.resolve();
12358
12814
  } catch (error) {
12359
12815
  const webAccounts = accounts.map(toWebAccount);
12816
+ const refreshRejected = isCredentialRejectedError(error);
12817
+ const recovery = !refreshRejected ? void 0 : await credentialRecoveryOf(deps, region, accounts.find((account) => account.selected)?.id);
12360
12818
  return {
12361
12819
  status: "signed-out",
12362
12820
  accounts: webAccounts,
12363
12821
  message: safeMessage(error),
12822
+ ...!refreshRejected ? {} : { credentialRejected: true },
12823
+ ...recovery === void 0 ? {} : { recovery },
12364
12824
  selectionExplicit,
12365
12825
  enabled,
12366
12826
  showCreditsInMainUi,
@@ -12485,6 +12945,8 @@ async function workBuddyWebPool(deps, region, fast = false) {
12485
12945
  const rankedIds = new Set(ranked.map((row) => row.account.id));
12486
12946
  const others = await pool.otherAccounts?.(region) ?? [];
12487
12947
  const checkedIn = fast ? pool.cachedCheckedInToday?.(region) ?? {} : await pool.checkedInToday?.(region).catch(() => ({})) ?? {};
12948
+ const growthRedeemed = pool.growthDoneAccountIds?.(region, "growth-redeem") ?? {};
12949
+ const growthActive = pool.growthDoneAccountIds?.(region, "growth-activity") ?? {};
12488
12950
  const claimable = fast ? pool.cachedBenefits?.(region) ?? {} : await pool.benefits?.(region).catch(() => ({})) ?? {};
12489
12951
  const rows = [...ranked.map((row) => ({
12490
12952
  account: row.account,
@@ -12535,6 +12997,8 @@ async function workBuddyWebPool(deps, region, fast = false) {
12535
12997
  current: account.id === currentAccountId,
12536
12998
  member,
12537
12999
  ...checkedIn[account.id] === void 0 ? {} : { checkedInToday: checkedIn[account.id] },
13000
+ ...growthRedeemed[account.id] === true ? { growthRedeemedToday: true } : {},
13001
+ ...growthActive[account.id] === true ? { growthActiveToday: true } : {},
12538
13002
  ...(() => {
12539
13003
  const views = claimable[account.id];
12540
13004
  if (views === void 0 || views.length === 0) return {};
@@ -12552,10 +13016,20 @@ async function workBuddyWebPool(deps, region, fast = false) {
12552
13016
  enabled: preferences.enabled,
12553
13017
  checkinSupported: pool.checkinSupported?.(region) === true,
12554
13018
  ...preferences.autoCheckin !== true ? {} : { autoCheckin: true },
13019
+ ...preferences.growthRedeem !== true ? {} : { growthRedeem: true },
13020
+ ...preferences.growthActivity !== true ? {} : { growthActivity: true },
12555
13021
  ...(() => {
12556
13022
  const today = pool.autoCheckinToday?.(region);
12557
13023
  return today === void 0 ? {} : { autoCheckinToday: today };
12558
13024
  })(),
13025
+ ...(() => {
13026
+ const today = pool.growthRedeemToday?.(region);
13027
+ return today === void 0 ? {} : { growthRedeemToday: today };
13028
+ })(),
13029
+ ...(() => {
13030
+ const today = pool.growthActivityToday?.(region);
13031
+ return today === void 0 ? {} : { growthActivityToday: today };
13032
+ })(),
12559
13033
  ...target.modelId === void 0 ? {} : { targetModelId: target.modelId },
12560
13034
  ...target.staleModelId === void 0 ? {} : { staleTargetModelId: target.staleModelId },
12561
13035
  targetModelSource: target.source,
@@ -12849,6 +13323,16 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12849
13323
  rows: await pool.checkin(region)
12850
13324
  });
12851
13325
  }
13326
+ if (action === "growth-redeem" || action === "growth-activity") {
13327
+ if (pool.growthRun === void 0) return json(res, 503, {
13328
+ reason: "pool-unavailable",
13329
+ error: "pool growth action unavailable"
13330
+ });
13331
+ return json(res, 200, {
13332
+ action,
13333
+ rows: await pool.growthRun(region, action)
13334
+ });
13335
+ }
12852
13336
  if (pool.test === void 0) return json(res, 503, {
12853
13337
  reason: "pool-unavailable",
12854
13338
  error: "pool test unavailable"
@@ -13328,6 +13812,8 @@ const poolConfig = z.object({
13328
13812
  * background path spend a request per account per day learning a refusal.
13329
13813
  */
13330
13814
  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."),
13815
+ 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."),
13816
+ 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
13817
  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
13818
  });
13333
13819
  const regionStateConfig = z.object({
@@ -15185,6 +15671,53 @@ function apply(ctx, config) {
15185
15671
  if (state === void 0) return void 0;
15186
15672
  return todaySummary(state, Date.now());
15187
15673
  },
15674
+ /**
15675
+ * Today's growth-job progress (issue #286), from the runner's own in-memory
15676
+ * state — same source the tick writes, so the card cannot drift from what
15677
+ * actually ran. `undefined` when the switch is off or nothing has run yet.
15678
+ */
15679
+ growthRedeemToday: (region) => growthTodayOf("growth-redeem", region),
15680
+ growthActivityToday: (region) => growthTodayOf("growth-activity", region),
15681
+ /**
15682
+ * Per-account growth completion for the row stamps (issue #286). Backed by
15683
+ * the runner's day state: an account is "done" once today's job addressed
15684
+ * it, regardless of whether it redeemed or was already active. No upstream
15685
+ * read, so it is safe on the card's poll.
15686
+ */
15687
+ growthDoneAccountIds: (region, cap) => {
15688
+ const state = growthState[growthKey(cap, region)];
15689
+ if (state === void 0 || state.day !== localDayKey(Date.now())) return {};
15690
+ const map = {};
15691
+ for (const id of state.doneAccountIds) map[id] = true;
15692
+ return map;
15693
+ },
15694
+ /**
15695
+ * Manual "run now" for a growth job (issue #286). Same batch + state as
15696
+ * the timer, but ignores the opt-in switch and the backoff clock: the user
15697
+ * asked for it now. Returns check-in-shaped rows for the shared log UI.
15698
+ */
15699
+ growthRun: async (region, action) => {
15700
+ const cap = action === "growth-redeem" ? "growth-redeem" : "growth-activity";
15701
+ const key = growthKey(cap, region);
15702
+ const nowMs = Date.now();
15703
+ const stored = growthState[key] ?? await readGrowthState(cap, region);
15704
+ const state = stored === void 0 || stored.day !== localDayKey(nowMs) ? emptyAutoCheckinState(localDayKey(nowMs)) : stored;
15705
+ const all = (await poolMemberAccounts(region)).map((account) => ({
15706
+ accountId: account.id,
15707
+ accountName: account.accountName
15708
+ }));
15709
+ const rows = await runGrowthBatch(cap, region, all);
15710
+ const folded = foldGrowthAttempt(state, rows.map((row) => row.accountId), all.length, nowMs);
15711
+ growthState[key] = folded;
15712
+ await writeGrowthState(cap, region, folded);
15713
+ return rows.map((row) => ({
15714
+ accountId: row.accountId,
15715
+ accountName: row.accountName,
15716
+ status: row.status === "done" ? "claimed" : row.status === "skipped" ? "already" : "failed",
15717
+ ...row.credit === void 0 ? {} : { credit: row.credit },
15718
+ ...row.message === void 0 ? {} : { message: row.message }
15719
+ }));
15720
+ },
15188
15721
  checkin: async (region) => {
15189
15722
  const rows = await checkinAllAccounts(await poolTargets(region), poolRunnerDeps(region));
15190
15723
  for (const row of rows) {
@@ -15760,7 +16293,9 @@ function apply(ctx, config) {
15760
16293
  ...probeInputTokens === void 0 ? {} : { probeInputTokens },
15761
16294
  memberAccountIds: pool?.memberAccountIds ?? [],
15762
16295
  orderAccountIds: pool?.orderAccountIds ?? [],
15763
- autoCheckin: pool?.autoCheckin === true
16296
+ autoCheckin: pool?.autoCheckin === true,
16297
+ growthRedeem: pool?.growthRedeem === true,
16298
+ growthActivity: pool?.growthActivity === true
15764
16299
  };
15765
16300
  };
15766
16301
  /**
@@ -15945,6 +16480,132 @@ function apply(ctx, config) {
15945
16480
  ctx.effect(() => () => {
15946
16481
  stopAutoCheckin();
15947
16482
  });
16483
+ const growthTimers = {};
16484
+ const growthState = {};
16485
+ const growthRunning = {};
16486
+ const GROWTH_IDLE_MS = AUTO_CHECKIN_IDLE_MS;
16487
+ const growthKey = (cap, region) => `${cap}:${region}`;
16488
+ /** Today's summary for one growth job, for the card's status line. */
16489
+ function growthTodayOf(cap, region) {
16490
+ if (!growthEnabled(cap, region)) return void 0;
16491
+ const state = growthState[growthKey(cap, region)];
16492
+ return growthTodaySummary(state, localDayKey(Date.now()));
16493
+ }
16494
+ /** Both growth capabilities apply to both regions — unlike check-in. */
16495
+ const GROWTH_REGIONS = ["cn", "global"];
16496
+ const GROWTH_CAPABILITIES = ["growth-redeem", "growth-activity"];
16497
+ function growthEnabled(cap, region) {
16498
+ const prefs = poolPreferencesOf(current(), region);
16499
+ if (!prefs.enabled) return false;
16500
+ return cap === "growth-redeem" ? prefs.growthRedeem : prefs.growthActivity;
16501
+ }
16502
+ /** The ACP model for one region: its first advertised model, or a safe fallback. */
16503
+ function growthAcpModel(region) {
16504
+ return displayModels(current(), region).filter((model) => !isRouterModelId(model.id))[0]?.id ?? (region === "cn" ? "hy3" : "deepseek-v4.1-flash");
16505
+ }
16506
+ /**
16507
+ * Execute one growth batch over the given targets — the ONE implementation
16508
+ * both the background timer and the manual "run now" button call. Never throws
16509
+ * at the batch level; each account's problem is captured on its own row by the
16510
+ * runner. Returns the raw growth rows (done/skipped/failed).
16511
+ */
16512
+ async function runGrowthBatch(cap, region, targets) {
16513
+ const store = stacks[region].store;
16514
+ if (cap === "growth-redeem") return redeemGrowthAll(targets, {
16515
+ credentialFor: (id) => store.credentialFor(id),
16516
+ readStreak: (credential) => client.fetchGrowthStreak(credential),
16517
+ redeem: (credential, tier) => client.redeemGrowthTier(credential, tier)
16518
+ });
16519
+ const model = growthAcpModel(region);
16520
+ return activateGrowthAll(targets, async (accountId) => {
16521
+ const credential = await store.credentialFor(accountId);
16522
+ if (credential === void 0) return {
16523
+ status: "failed",
16524
+ reason: "no stored credential"
16525
+ };
16526
+ const host = growthHostOf(credential);
16527
+ return activateGrowth({
16528
+ base: host,
16529
+ accessToken: credential.accessToken,
16530
+ origin: host,
16531
+ model,
16532
+ heatmap: async () => {
16533
+ const cell = await client.fetchGrowthToday(credential);
16534
+ return cell === void 0 ? void 0 : {
16535
+ isActive: cell.isActive,
16536
+ score: cell.score
16537
+ };
16538
+ }
16539
+ });
16540
+ });
16541
+ }
16542
+ /** Run one capability for one region across its pooled members. Never throws. */
16543
+ async function growthTick(cap, region) {
16544
+ const key = growthKey(cap, region);
16545
+ if (growthRunning[key] === true) return;
16546
+ growthRunning[key] = true;
16547
+ try {
16548
+ if (!growthEnabled(cap, region)) return;
16549
+ const nowMs = Date.now();
16550
+ const today = localDayKey(nowMs);
16551
+ const stored = growthState[key] ?? await readGrowthState(cap, region);
16552
+ const state = stored === void 0 || stored.day !== today ? emptyAutoCheckinState(today) : stored;
16553
+ growthState[key] = state;
16554
+ const all = (await poolMemberAccounts(region)).map((account) => ({
16555
+ accountId: account.id,
16556
+ accountName: account.accountName
16557
+ }));
16558
+ const targets = growthPendingTargets(all, state);
16559
+ if (targets.length === 0) {
16560
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16561
+ return;
16562
+ }
16563
+ const folded = foldGrowthAttempt(state, (await runGrowthBatch(cap, region, targets)).map((row) => row.accountId), all.length, nowMs);
16564
+ growthState[key] = folded;
16565
+ await writeGrowthState(cap, region, folded);
16566
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16567
+ } catch (error) {
16568
+ ctx.logger.warn(`dsh-connect-workbuddy: growth tick failed (${cap}/${region})`, error);
16569
+ scheduleGrowth(cap, region, GROWTH_IDLE_MS);
16570
+ } finally {
16571
+ growthRunning[key] = false;
16572
+ }
16573
+ }
16574
+ function scheduleGrowth(cap, region, delayMs) {
16575
+ const key = growthKey(cap, region);
16576
+ const existing = growthTimers[key];
16577
+ if (existing !== void 0) clearTimeout(existing);
16578
+ const timer = setTimeout(() => {
16579
+ growthTick(cap, region);
16580
+ }, delayMs);
16581
+ timer.unref?.();
16582
+ growthTimers[key] = timer;
16583
+ }
16584
+ function syncGrowth() {
16585
+ for (const cap of GROWTH_CAPABILITIES) for (const region of GROWTH_REGIONS) {
16586
+ const key = growthKey(cap, region);
16587
+ if (growthEnabled(cap, region)) {
16588
+ if (growthTimers[key] === void 0) scheduleGrowth(cap, region, 0);
16589
+ continue;
16590
+ }
16591
+ const timer = growthTimers[key];
16592
+ if (timer !== void 0) {
16593
+ clearTimeout(timer);
16594
+ delete growthTimers[key];
16595
+ }
16596
+ }
16597
+ }
16598
+ function stopGrowth() {
16599
+ for (const timer of Object.values(growthTimers)) clearTimeout(timer);
16600
+ for (const key of Object.keys(growthTimers)) delete growthTimers[key];
16601
+ }
16602
+ function refreshGrowthSchedules() {
16603
+ syncGrowth();
16604
+ }
16605
+ refreshGrowthSchedules();
16606
+ ctx.effect(() => () => {
16607
+ stopGrowth();
16608
+ });
15948
16609
  ctx.inject(["settings"], (sctx) => {
15949
16610
  const settings = sctx.settings;
15950
16611
  ctx.effect(() => settings.configure({ auto: true }, ctx.fiber));
@@ -15979,6 +16640,7 @@ function apply(ctx, config) {
15979
16640
  ctx.on("loader/volatile-update", () => {
15980
16641
  applySelection(current());
15981
16642
  syncAutoCheckin();
16643
+ refreshGrowthSchedules();
15982
16644
  syncDeviceSdk();
15983
16645
  });
15984
16646
  applySelection(config);