dsh-connect-workbuddy 5.21.3 → 5.22.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 { $t as imageDefaultFor, A as withoutRouters, At as offRefused, B as defaultDesktopAuthPath, Bt as IMAGE_TAG_TEXT_TO_IMAGE, C as setDeviceMode, Ct as attachBusyLevels, D as applyContextBudgets, Dt as defaultOffModelIds, E as WorkBuddyCatalog, En as writeFileAtomic, Et as REFUSES_OFF_MODEL_IDS, F as WorkBuddyCredentialStore, Ft as WorkBuddyVideoError, G as parseWorkBuddyAuth, Gt as isBareBase64Image, H as isEncryptedCredentialError, Ht as WorkBuddyImageError, I as WorkBuddyEncryptedCredentialError, It as parseSupportedSecondsRange, J as workbuddyOwnAuthPath, Jt as sniffImageMime, K as preferredAccountName, Kt as parseImageDataUrl, L as authFileName, Lt as pickVideoModel, M as WORKBUDDY_AUTH_FILENAME, Mt as withEffectiveOff, N as WORKBUDDY_AUTH_FILE_ENV, Nt as VIDEO_TAG_IMAGE_TO_VIDEO, O as deriveCatalog, Ot as lastRefusalFor, Pt as VIDEO_TAG_TEXT_TO_VIDEO, Q as CREDENTIAL_REJECTED_CODE, Qt as NATIVE_MODALITY_BY_MODEL_ID, R as defaultDesktopAuthCandidates, Rt as resolveVideoParams, S as saveDeviceSdkSettings, Sn as workbuddyAppExecutableCandidates, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as withFileLock, Tt as selectPromoBadge, U as isVaultAccountId, Ut as imageDataUrl, V as hasEncryptedCredentialFields, Vt as MAX_INPUT_IMAGE_BYTES, W as legacyWorkbuddyOwnAuthPath, Wt as imageMimeForPath, X as APP_VERSION, Xt as queueNoticeText, Yt as parseQueueAnswer, Z as CONTEXT_OVERFLOW_MARKER, Zt as pruneTempDir, _ as createDeviceProfileLookup, _n as isWorkbuddyBundle, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as openEncryptedField, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, ct as isContextTooLongBody, dn as deriveAtRestKey, dt as isFirstMessageGateBody, en as nativeModalityOf, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as deriveAtRestKeyId, ft as knownRegionOf, g as createTuringSdk, gn as isEncryptedFieldWrapper, gt as parseReasoning, h as createDeviceSdkPort, ht as parseCreditMultiplier, i as processStartTimeMs, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as recordRefusal, k as fallbackModelsFor, kt as offDefaultFor, l as createFileRosterSeenStore, ln as WORKBUDDY_APP_EXECUTABLE_ENV, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as findWorkbuddyAppExecutable, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, on as isDeviceId, p as resolveCnGateway, pn as fetchAtRestKeyPayload, pt as modelIdOfBody, q as workbuddyAccountId, qt as pickMediaModel, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as clearAtRestKeyCache, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as macosBundleExecutable, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, wt as promoBadgeTone, x as saveDeviceProfile, xn as readAtRestKey, xt as requestEvidenceOf, y as isDeviceMode, yn as macosNestedAppBundles, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as IMAGE_TAG_IMAGE_TO_IMAGE } from "./host-heartbeat-WSrMdV6b.js";
1
+ import { $t as parseQueueAnswer, A as withoutRouters, An as writeFileAtomic, At as offRefused, B as defaultDesktopAuthPath, Bt as IMAGE_TAG_IMAGE_TO_IMAGE, C as setDeviceMode, Cn as macosNestedAppBundles, Ct as attachBusyLevels, D as applyContextBudgets, Dt as defaultOffModelIds, E as WorkBuddyCatalog, En as workbuddyAppExecutableCandidates, Et as REFUSES_OFF_MODEL_IDS, F as WorkBuddyCredentialStore, Ft as WorkBuddyVideoError, G as parseWorkBuddyAuth, Gt as imageMimeForPath, H as isEncryptedCredentialError, Ht as MAX_INPUT_IMAGE_BYTES, I as WorkBuddyEncryptedCredentialError, It as parseSupportedSecondsRange, J as workbuddyOwnAuthPath, Jt as isBareBase64Image, K as preferredAccountName, Kt as imageModelChoices, L as authFileName, Lt as pickVideoModel, M as WORKBUDDY_AUTH_FILENAME, Mt as withEffectiveOff, N as WORKBUDDY_AUTH_FILE_ENV, Nt as VIDEO_TAG_IMAGE_TO_VIDEO, O as deriveCatalog, On as resolveDshHome, Ot as lastRefusalFor, Pt as VIDEO_TAG_TEXT_TO_VIDEO, Q as CREDENTIAL_REJECTED_CODE, Qt as sniffImageMime, R as defaultDesktopAuthCandidates, Rt as resolveVideoParams, S as saveDeviceSdkSettings, Sn as macosBundleExecutable, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as readAtRestKey, Tt as selectPromoBadge, U as isVaultAccountId, Ut as WorkBuddyImageError, V as hasEncryptedCredentialFields, Vt as IMAGE_TAG_TEXT_TO_IMAGE, W as legacyWorkbuddyOwnAuthPath, Wt as imageDataUrl, X as APP_VERSION, Xt as parseImageDataUrl, Yt as isWatermarkFreeImageModel, Z as CONTEXT_OVERFLOW_MARKER, Zt as pickMediaModel, _ as createDeviceProfileLookup, _n as fetchAtRestKeyPayload, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as isEncryptedFieldWrapper, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, ct as isContextTooLongBody, dt as isFirstMessageGateBody, en as queueNoticeText, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, ft as knownRegionOf, g as createTuringSdk, gn as deriveAtRestKeyId, gt as parseReasoning, h as createDeviceSdkPort, hn as deriveAtRestKey, ht as parseCreditMultiplier, i as processStartTimeMs, in as nativeModalityOf, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as recordRefusal, k as fallbackModelsFor, kn as withFileLock, kt as offDefaultFor, l as createFileRosterSeenStore, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as clearAtRestKeyCache, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nn as NATIVE_MODALITY_BY_MODEL_ID, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, p as resolveCnGateway, pn as WORKBUDDY_APP_EXECUTABLE_ENV, pt as modelIdOfBody, q as workbuddyAccountId, qt as imageSizeLimitsOf, r as isHeartbeatProcessAlive, rn as imageDefaultFor, rt as channelGateMemberOf, s as writeHostHeartbeat, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as pruneTempDir, tt as WorkBuddyCredentialRejectedError, un as isDeviceId, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as findWorkbuddyAppExecutable, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as openEncryptedField, wt as promoBadgeTone, x as saveDeviceProfile, xn as isWorkbuddyBundle, xt as requestEvidenceOf, y as isDeviceMode, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as IMAGE_SIZE_LIMITS_WIDE } from "./host-heartbeat-CYnq7iGq.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";
@@ -389,15 +389,17 @@ const WORKBUDDY_DEVICE_PROFILE_PATH = "/plugins/dsh-connect-workbuddy/device-pro
389
389
  /**
390
390
  * 真实设备参数(本机安装的桌面端 Turing Shield SDK)的状态与取值。
391
391
  *
392
- * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度。
392
+ * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度;另带 `sdkEnabled`
393
+ * (总开关的当前值),供卡片画出那个勾选框。
393
394
  * - `POST ?action=refresh` → 强制重取一次,再返回同一形状。
394
395
  * - `POST ?action=reveal` → `{ token }`,完整值,**只在用户显式点击时**。
396
+ * - `POST ?action=enable|disable` → 写总开关。
395
397
  *
396
398
  * 为什么把"完整值"单独做成一个动作:这是一枚能代表这台机器的凭据,卡片是
397
399
  * 一个会被截图、被贴进 issue 的界面。默认只给掩码,复制/查看各要一次显式动作。
398
400
  */
399
401
  const WORKBUDDY_DEVICE_SDK_PATH = "/plugins/dsh-connect-workbuddy/device-sdk";
400
- /** Query parameter selecting it. */
402
+ /** Query parameter selecting the POST action. */
401
403
  const WORKBUDDY_DEVICE_SDK_ACTION_PARAM = "action";
402
404
  /**
403
405
  * The refresh intervals the card offers, in milliseconds.
@@ -617,6 +619,7 @@ const REGION_MAP_FOREIGN_KEYS = /* @__PURE__ */ new Set([
617
619
  "enabledModelIds",
618
620
  "imageModelIds",
619
621
  "imageToolEnabled",
622
+ "preferredImageModel",
620
623
  "offModelIds",
621
624
  "contextBudgets",
622
625
  "defaultThinkingEfforts",
@@ -667,6 +670,7 @@ function slotConfigWeight(slot) {
667
670
  if (slot["enabled"] === false) weight += 1;
668
671
  if (slot["showCreditsInMainUi"] === false) weight += 1;
669
672
  if (slot["imageToolEnabled"] === true) weight += 1;
673
+ if (typeof slot["preferredImageModel"] === "string" && slot["preferredImageModel"] !== "") weight += 1;
670
674
  return weight;
671
675
  }
672
676
  /**
@@ -1476,8 +1480,12 @@ function workBuddyThinkingLevelMap(info) {
1476
1480
  * stamped field is what pi-ai resolves the provider BY (issue #75) — so every
1477
1481
  * key in {@link modelIdentityKeysOf} must be a key this route registers.
1478
1482
  */
1479
- function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1483
+ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY, midConvoSystemMessages = false) {
1480
1484
  const thinkingLevelMap = workBuddyThinkingLevelMap(info);
1485
+ const compat = midConvoSystemMessages ? {
1486
+ supportsReasoningEffort: thinkingLevelMap !== void 0,
1487
+ supportsMidConvoSystemMessages: true
1488
+ } : { supportsReasoningEffort: thinkingLevelMap !== void 0 };
1481
1489
  return {
1482
1490
  id: info.id,
1483
1491
  name: workBuddyDisplayName(info),
@@ -1490,7 +1498,7 @@ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1490
1498
  maxTokens: info.maxTokens,
1491
1499
  reasoning: thinkingLevelMap !== void 0,
1492
1500
  ...thinkingLevelMap === void 0 ? {} : { thinkingLevelMap },
1493
- compat: { supportsReasoningEffort: thinkingLevelMap !== void 0 }
1501
+ compat
1494
1502
  };
1495
1503
  }
1496
1504
  /**
@@ -2320,7 +2328,8 @@ function createWorkBuddyAdapter(options) {
2320
2328
  const generation = options.piAiGeneration ?? piAiRuntimeInfo().generation;
2321
2329
  const buildModels = () => {
2322
2330
  const baseUrl = `${shim.baseUrl()}/v1`;
2323
- return catalog.current().map((info) => toPiModel(info, baseUrl, modelIdentity));
2331
+ const midConvoSystemMessages = regionOfProvider(providerId) === "cn";
2332
+ return catalog.current().map((info) => toPiModel(info, baseUrl, modelIdentity, midConvoSystemMessages));
2324
2333
  };
2325
2334
  const provider = {
2326
2335
  ...createProvider({
@@ -2958,7 +2967,8 @@ function installChannelContinue(mount) {
2958
2967
  * vendor, uniformly — 790 replay records in one real session held that value
2959
2968
  * and no other). Non-survivors are text by the time `:964–971` collects
2960
2969
  * `assistantText`, so they land in `assistantMsg.content` instead. This plugin
2961
- * sets only `compat.supportsReasoningEffort` (`src/adapter.ts:200`), which
2970
+ * sets `compat.supportsReasoningEffort` and `compat.supportsMidConvoSystemMessages`
2971
+ * (`src/adapter.ts`), neither of which touches `requiresThinkingAsText`, which
2962
2972
  * leaves `requiresThinkingAsText` at its `false` default (`:1270`), so the raw
2963
2973
  * field route is the live one rather than the fold-into-content route at `:983`.
2964
2974
  *
@@ -3384,8 +3394,8 @@ function attachUsage(directory, report, onError) {
3384
3394
  * live here rather than being re-derived per route. A previous version kept the
3385
3395
  * Host check inside `shim.ts` and only the Origin check inside `web-status.ts`,
3386
3396
  * which meant the shim's chat route had both guards while the settings card's
3387
- * thirteen routes (ten POST + three GET) had one — the asymmetry was invisible
3388
- * because each file looked internally consistent.
3397
+ * routes had one — the asymmetry was invisible because each file looked
3398
+ * internally consistent.
3389
3399
  *
3390
3400
  * - **Host** answers "is this request addressed to the interface it landed on?".
3391
3401
  * A DNS-rebinding page sends requests whose `Host` is the *attacker's* domain
@@ -5861,9 +5871,12 @@ function createWorkBuddyShim(options) {
5861
5871
  writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
5862
5872
  return;
5863
5873
  }
5864
- await prepareAccount?.().catch((error) => {
5874
+ const controller = new AbortController();
5875
+ res.on("close", () => controller.abort());
5876
+ await prepareAccount?.(controller.signal).catch((error) => {
5865
5877
  logger?.warn("dsh-connect-workbuddy: pool account selection failed", error);
5866
5878
  });
5879
+ if (controller.signal.aborted) return;
5867
5880
  let credential;
5868
5881
  try {
5869
5882
  credential = await store.resolve();
@@ -5882,8 +5895,6 @@ function createWorkBuddyShim(options) {
5882
5895
  } catch (error) {
5883
5896
  logger?.warn("dsh-connect-workbuddy: body report failed", error);
5884
5897
  }
5885
- const controller = new AbortController();
5886
- res.on("close", () => controller.abort());
5887
5898
  const preferred = channelPerturbation === "always" || channelNeedsPerturbation ? perturbChannelFingerprints(prepared, channelPerturbation === "always") ?? prepared : prepared;
5888
5899
  let result = await client.chatStream(credential, preferred, controller.signal);
5889
5900
  if (channelNeedsPerturbation && !result.ok && result.kind === "channel_reject") {
@@ -6181,6 +6192,30 @@ const IMAGE_TOOL_TIMEOUT_MS = 18e4;
6181
6192
  const IMAGE_INPUT_TIMEOUT_MS = 3e4;
6182
6193
  /** 失败后的冷却:生图按张扣积分,连续重试会在几秒内烧掉几十积分。 */
6183
6194
  const FAILURE_COOLDOWN_MS$1 = 3e4;
6195
+ /**
6196
+ * 选这次真正要用的模型。
6197
+ *
6198
+ * 优先级只有三级,且第二级「谁写的」决定写错了谁负责:
6199
+ *
6200
+ * 1. 调用方显式传的 `model`——写错就报错(`pickMediaModel` 会列出可用项)。
6201
+ * 2. 用户在卡片上选的偏好(`preferredImageModel`)——**只在没显式传时**生效,
6202
+ * 而且失效时静默回落,因为目录可能已经变过,一个过期偏好不该卡住一次生成。
6203
+ * 3. 组内第一个,也就是上游目录今天给的那条(默认 `hunyuan-image-alpha`)。
6204
+ *
6205
+ * 偏好只落在软约束这一侧,是因为它和 `model` 参数的区别是**谁写的**:参数是这次
6206
+ * 的调用者写的,偏好是用户上一次在卡片上点的。这与视频工具 `preferredVideoModel`
6207
+ * 的判据完全一致,两个工具不该有两套说法。
6208
+ */
6209
+ function resolveImageModel(models, requested, tag, deps, credential, region) {
6210
+ const choices = region === "cn" ? imageModelChoices(models, tag) : models.filter((model) => model.tags.includes(tag));
6211
+ const pinned = requested === void 0 ? deps.preferredImageModel?.(credential, tag) : void 0;
6212
+ try {
6213
+ return pickMediaModel(choices, requested ?? pinned, tag);
6214
+ } catch (error) {
6215
+ if (requested !== void 0 || pinned === void 0) throw error;
6216
+ return pickMediaModel(choices, void 0, tag);
6217
+ }
6218
+ }
6184
6219
  function asRecord$1(value) {
6185
6220
  return typeof value === "object" && value !== null ? value : {};
6186
6221
  }
@@ -6235,11 +6270,9 @@ function strictString$1(value, name) {
6235
6270
  }
6236
6271
  /** 「宽x高」——允许 `x` / `X` / 全角 `×`;不接受 `*`、空格、带单位。 */
6237
6272
  const SIZE_PATTERN = /^[0-9]+[xX×][0-9]+$/;
6238
- /** 上游实测上限:总像素约 419 万(见 docs/IMAGE_GEN.md「尺寸与比例」)。 */
6239
- const MAX_IMAGE_PIXELS = 4194304;
6240
- /** 边长支持范围。上限 2560 来自实测通过的最大长边(2560x1440 / 2560x1600)。 */
6241
- const MIN_IMAGE_EDGE = 512;
6242
- const MAX_IMAGE_EDGE = 2560;
6273
+ IMAGE_SIZE_LIMITS_WIDE.maxPixels;
6274
+ IMAGE_SIZE_LIMITS_WIDE.minEdge;
6275
+ IMAGE_SIZE_LIMITS_WIDE.maxEdge;
6243
6276
  /** 实测被上游拒绝的尺寸,报错时直接点出来,省得模型反复试。 */
6244
6277
  const KNOWN_BAD_SIZES = /* @__PURE__ */ new Set([
6245
6278
  "2560x2560",
@@ -6300,37 +6333,71 @@ function parseSizeSpec(value) {
6300
6333
  * 把解析好的尺寸规格落成一个真正要发给上游的值。
6301
6334
  *
6302
6335
  * 与 {@link parseSizeSpec} 分开,是因为这两件事的**时机**不同:格式错误要在收到
6303
- * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高。
6336
+ * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高、
6337
+ * 也要等**模型定下来**——两个模型的合法范围不一样(见 `imageSizeLimitsOf`)。
6304
6338
  *
6305
6339
  * 越界为什么由工具收、而不是让模型自己算:两条边(512–2560)与总像素
6306
6340
  * (≤4,194,304)是两个约束,手算要取「2560/长边」与「√(4194304/面积)」里更小的
6307
6341
  * 那个**再复查一遍**。要求模型在参数里做这种算术,实测会算出仍然越界的值
6308
6342
  * (2480x3508 → 1810x2560,边长合规但乘积 4,633,600 仍超)。收完之后把「动过什么」
6309
6343
  * 写进 hint,模型得据实转告用户,不能假装按用户给的尺寸出图。
6344
+ *
6345
+ * `limits` 来自**这一次选中的模型**,不是全局常量:v3.0 的边更短、像素更少,
6346
+ * 用 alpha 的范围替它算会得到上游 400(实测 `1024x1025` 就被拒)。
6310
6347
  */
6311
- function planImageSize(spec, input) {
6348
+ /**
6349
+ * `size: auto` 但量不出输入图 —— 这一步**不需要模型**,所以单独提出来。
6350
+ *
6351
+ * 报错时机是这里唯一的理由:模型的失败(目录里没这条模型)要花一次目录请求
6352
+ * 才能知道,而「你写了 auto 却没给图」在本地就能判。把它压到模型解析之后,
6353
+ * 一个纯参数错误就会被「目录里没有模型」盖掉,用户改完一处还得再撞第二处。
6354
+ */
6355
+ function missingAutoSizeInput() {
6356
+ throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6357
+ }
6358
+ /** `auto` 必须配一张量得出宽高的图;没有就报那条错误,否则原样返回。 */
6359
+ function requireAutoInput(input) {
6360
+ return input ?? missingAutoSizeInput();
6361
+ }
6362
+ function planImageSize(spec, input, limits) {
6312
6363
  if (spec.kind === "auto") {
6313
- if (input === void 0) throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6314
- const canvas = canvasForInput(input);
6364
+ const source = requireAutoInput(input);
6365
+ const canvas = canvasForInput(source, limits);
6315
6366
  const size = `${canvas.width}x${canvas.height}`;
6316
6367
  return {
6317
6368
  size,
6318
6369
  requested: "auto",
6319
- note: canvas.exact ? `size 写的是 auto,已按输入图 ${input.width}x${input.height} 的比例取画布 ${size}(${ORIENTATION_LABEL[orientationOf(input)]})` : `输入图 ${input.width}x${input.height} 太细长,等比缩不出合法的画布,已改用${ORIENTATION_LABEL[orientationOf(input)]}常用档 ${size},比例有变化`
6370
+ note: canvas.exact ? `size 写的是 auto,已按输入图 ${source.width}x${source.height} 的比例取画布 ${size}(${ORIENTATION_LABEL[orientationOf(source)]})` : `输入图 ${source.width}x${source.height} 太细长,等比缩不出合法的画布,已改用${ORIENTATION_LABEL[orientationOf(source)]}常用档 ${size},比例有变化`
6320
6371
  };
6321
6372
  }
6322
6373
  const { width, height, normalized } = spec;
6323
- if (isSizeInRange(width, height, normalized)) return { size: `${width}x${height}` };
6324
- const fitted = fitIntoRange(width, height);
6325
- if (fitted === void 0) throw inputImageError(`workbuddy image: 参数 size ${normalized} 的比例太极端,等比缩放放不进 ${MIN_IMAGE_EDGE}–${MAX_IMAGE_EDGE} 且总像素不超过 419 万的范围内。请改成接近的常用档位:方图 1024x1024、竖图 1024x1536、横图 1536x1024、16:9 桌面 2560x1440、9:16 手机壁纸 1440x2560。`);
6374
+ if (isSizeInRange(width, height, normalized, limits)) return { size: `${width}x${height}` };
6375
+ const fitted = fitIntoRange(width, height, limits);
6376
+ if (fitted === void 0) throw inputImageError(`workbuddy image: 参数 size ${normalized} 的比例太极端,等比缩放放不进 ${describeLimits(limits)} 的范围内。请改成接近的常用档位:` + sampleSizesFor(limits) + "。");
6326
6377
  const direction = fitted.direction === "up" ? "放大" : "缩小";
6327
6378
  return {
6328
6379
  size: `${fitted.width}x${fitted.height}`,
6329
6380
  requested: normalized,
6330
- note: `你给的尺寸 ${normalized} 超出 ${MIN_IMAGE_EDGE}–${MAX_IMAGE_EDGE} 边长或 419 万像素上限,已等比${direction}到 ${fitted.width}x${fitted.height}`
6381
+ note: `你给的尺寸 ${normalized} 超出${describeLimits(limits)},已等比${direction}到 ${fitted.width}x${fitted.height}`
6331
6382
  };
6332
6383
  }
6333
6384
  /**
6385
+ * 一句话说清这次的上限,用在两条错误/提示里。
6386
+ *
6387
+ * 说「419 万」而不是「4,194,304」:hint 是要模型原样转述给用户的,像素数写全
6388
+ * 数字没人读得进去,而「约 419 万像素」既准确又够用。v3.0 的 104 万同理
6389
+ * (1048576/1e4 = 104.9 → 105,不是 1)。
6390
+ */
6391
+ function describeLimits(limits) {
6392
+ const wan = (limits.maxPixels / 1e4).toFixed(0);
6393
+ return ` ${limits.minEdge}–${limits.maxEdge} 边长或约 ${wan} 万像素上限`;
6394
+ }
6395
+ /** 这个范围内拿得出手的档位例子——按半径给出,别举一个会被拒的。 */
6396
+ function sampleSizesFor(limits) {
6397
+ if (limits.maxPixels <= 1048576) return "方图 1024x1024、竖图 768x1024、横图 1280x720";
6398
+ return "方图 1024x1024、竖图 1024x1536、横图 1536x1024、16:9 桌面 2560x1440、9:16 手机壁纸 1440x2560";
6399
+ }
6400
+ /**
6334
6401
  * 这些失败说明请求真的打到了上游、可能已经扣了积分,才值得进冷却。
6335
6402
  * 参数写错 / 未登录 / 目录里没有模型都还没花钱。
6336
6403
  */
@@ -6494,7 +6561,7 @@ function firstDimensions(inputs) {
6494
6561
  * 极端比例(比 5:1 还细长)等比缩放放不进范围时,退回按方向的常用档——宁可换
6495
6562
  * 比例,也不能报错让用户无从下手;`exact: false` 就是用来把这句实话写进 hint 的。
6496
6563
  */
6497
- function canvasForInput(input) {
6564
+ function canvasForInput(input, limits) {
6498
6565
  const orientation = orientationOf(input);
6499
6566
  if (orientation === "square") return {
6500
6567
  ...DEFAULT_SIZE_BY_ORIENTATION.square,
@@ -6505,12 +6572,12 @@ function canvasForInput(input) {
6505
6572
  const short = Math.max(1, Math.round(shortest * AUTO_LONG_EDGE / longest));
6506
6573
  const width = orientation === "landscape" ? AUTO_LONG_EDGE : short;
6507
6574
  const height = orientation === "landscape" ? short : AUTO_LONG_EDGE;
6508
- if (isSizeInRange(width, height, `${width}x${height}`)) return {
6575
+ if (isSizeInRange(width, height, `${width}x${height}`, limits)) return {
6509
6576
  width,
6510
6577
  height,
6511
6578
  exact: true
6512
6579
  };
6513
- const fitted = fitIntoRange(width, height);
6580
+ const fitted = fitIntoRange(width, height, limits);
6514
6581
  if (fitted !== void 0) return {
6515
6582
  width: fitted.width,
6516
6583
  height: fitted.height,
@@ -6522,11 +6589,11 @@ function canvasForInput(input) {
6522
6589
  };
6523
6590
  }
6524
6591
  /** 两个上限(长边 2560、总像素 419 万)同时满足时,把宽高按比例收进范围。 */
6525
- function shrinkProduct(width, height) {
6592
+ function shrinkProduct(width, height, limits) {
6526
6593
  let w = width;
6527
6594
  let h = height;
6528
- for (let round = 0; round < 4 && w * h > MAX_IMAGE_PIXELS; round += 1) {
6529
- const scale = Math.sqrt(MAX_IMAGE_PIXELS / (w * h));
6595
+ for (let round = 0; round < 4 && w * h > limits.maxPixels; round += 1) {
6596
+ const scale = Math.sqrt(limits.maxPixels / (w * h));
6530
6597
  w = Math.floor(w * scale);
6531
6598
  h = Math.floor(h * scale);
6532
6599
  }
@@ -6545,38 +6612,45 @@ function shrinkProduct(width, height) {
6545
6612
  * 返回 undefined 表示等比缩放解不出来(比例比 5:1 还极端:缩到长边 2560 时短边
6546
6613
  * 已经小于 512,抬到 512 时长边又超过 2560),交给调用方按方向换档。
6547
6614
  */
6548
- function fitIntoRange(width, height) {
6615
+ function fitIntoRange(width, height, limits) {
6616
+ const { minEdge, maxEdge, maxPixels } = limits;
6549
6617
  const longest = Math.max(width, height);
6550
6618
  const shortest = Math.min(width, height);
6551
- if (!(longest > MAX_IMAGE_EDGE || width * height > MAX_IMAGE_PIXELS) && shortest < MIN_IMAGE_EDGE) {
6552
- const scale = MIN_IMAGE_EDGE / shortest;
6553
- if (longest * scale <= MAX_IMAGE_EDGE) return {
6554
- ...shrinkProduct(Math.round(width * scale), Math.round(height * scale)),
6619
+ if (!(longest > maxEdge || width * height > maxPixels) && shortest < minEdge) {
6620
+ const scale = minEdge / shortest;
6621
+ if (longest * scale <= maxEdge) return {
6622
+ ...shrinkProduct(Math.round(width * scale), Math.round(height * scale), limits),
6555
6623
  direction: "up"
6556
6624
  };
6557
6625
  return;
6558
6626
  }
6559
- const scale = Math.min(MAX_IMAGE_EDGE / longest, Math.sqrt(MAX_IMAGE_PIXELS / (width * height)));
6560
- const scaled = shrinkProduct(Math.floor(width * scale), Math.floor(height * scale));
6561
- if (scaled.width >= MIN_IMAGE_EDGE && scaled.height >= MIN_IMAGE_EDGE) return {
6627
+ const scale = Math.min(maxEdge / longest, Math.sqrt(maxPixels / (width * height)));
6628
+ const scaled = shrinkProduct(Math.floor(width * scale), Math.floor(height * scale), limits);
6629
+ if (scaled.width >= minEdge && scaled.height >= minEdge) return {
6562
6630
  ...scaled,
6563
6631
  direction: "down"
6564
6632
  };
6565
- const extreme = MIN_IMAGE_EDGE / shortest;
6566
- if (longest * extreme <= MAX_IMAGE_EDGE) {
6567
- const lifted = shrinkProduct(Math.round(width * extreme), Math.round(height * extreme));
6568
- if (lifted.width * lifted.height <= MAX_IMAGE_PIXELS) return {
6633
+ const extreme = minEdge / shortest;
6634
+ if (longest * extreme <= maxEdge) {
6635
+ const lifted = shrinkProduct(Math.round(width * extreme), Math.round(height * extreme), limits);
6636
+ if (lifted.width * lifted.height <= maxPixels) return {
6569
6637
  ...lifted,
6570
6638
  direction: "up"
6571
6639
  };
6572
6640
  }
6573
6641
  }
6574
- /** 一个尺寸是否直接可用:两条边在 512–2560,且宽乘高不超过 419 万。 */
6575
- function isSizeInRange(width, height, normalized) {
6642
+ /**
6643
+ * 一个尺寸能否**原样**发给这次选中的模型。
6644
+ *
6645
+ * 三个判据都跟着 `limits` 走,不是全局常量:v3.0 的边 2048 / 像素 1,048,576,
6646
+ * alpha 才是 2560 / 4,194,304。`KNOWN_BAD_SIZES` 是那个宽档下实测被拒的档位,
6647
+ * 窄档的边界由 `limits` 本身就够判,不必再叠一份。
6648
+ */
6649
+ function isSizeInRange(width, height, normalized, limits) {
6576
6650
  if (KNOWN_BAD_SIZES.has(normalized)) return false;
6577
- if (width < MIN_IMAGE_EDGE || height < MIN_IMAGE_EDGE) return false;
6578
- if (width > MAX_IMAGE_EDGE || height > MAX_IMAGE_EDGE) return false;
6579
- return width * height <= MAX_IMAGE_PIXELS;
6651
+ if (width < limits.minEdge || height < limits.minEdge) return false;
6652
+ if (width > limits.maxEdge || height > limits.maxEdge) return false;
6653
+ return width * height <= limits.maxPixels;
6580
6654
  }
6581
6655
  /**
6582
6656
  * 体积与空文件闸门——四种输入形态都从这里过,所以「空文件」和「超过 8 MB」的
@@ -6665,7 +6739,7 @@ function createImageTool(deps) {
6665
6739
  };
6666
6740
  return {
6667
6741
  name: WORKBUDDY_IMAGE_TOOL_NAME,
6668
- description: "用 WorkBuddy 生图或改图:一次调用只出一张图,要几张就调几次,每张单独计费。本工具没有 seed、不存历史、不能重放:同一段 prompt 重调不保证张张一样。所以先判一件事,跟要几张无关——用户要的是「一样」还是「不同」:(i) 要「一样」「同款」「同一张」「复制几张」「跟上一张一样」→ 做不到,说明原因,让他只出一张自己复制;不报价、不调用。要几张「都一样」就走这一条,不是「出 N 张」。(ii) 要「不同风格」「各来一张」→ 按 (b) 的口径报张数和总价(「4 张:国内版约 22.8、国际版约 0.12 积分」)→ 等他明确同意 → 连着调 N 次,每次换 prompt(换姿态、视角、光位)。(iii) 要「挑一张」「先看一张」→ 先出 1 张给他看,满意再按张补后面的,补之前重新报一次总价。没说同异、只问张数价钱(「4 张要多少钱」)→ 先问「要一样的还是各不相同的」,问完再报。这三条用 (i)(ii)(iii) 编号,(d) 里的 ①②③④⑤⑥⑦⑧ 是 size 的台阶,两套编号别混。什么时候必须先停下等用户点头,只看这七条:要出超过一张、这次调用会改变原图版式(裁切/留白)、文生图且主体还没定、用户把某个超过 2560 的像素当验收标准(原话里有「必须」「正好」「就是要」「不能改」)、用户要求硬排除某个元素(「绝对不能有 XX」)、要自己按表外比例算像素(见 ⑥)、用户本轮或上一轮里说过嫌贵、或正要你改区设置((c))。七条都不成立(单张文生图、size 用现成档位)就直接调,不用等点头;但单张仍要按 (b) 报一次两档价——那是告知,不是请示。成立两条以上时合成一次问完。「同意」只算用户明确说同意,沉默、反问、换话题都不算。\n(a) 画什么:prompt 写主体、风格、构图、光线。用户给了主体、只是没给风格和光线,就由你补,别为这个反问他;只有 text-to-image 才受这条限制:用户连主体都没给(只说了尺寸、比例、档位、用途、方向或风格)就先问「想画什么」,不要自己编一个主体去扣积分。改图(给了 image)不算没主体——参考图本身就是主体,别拿着图还问「想画什么」。主体=画面上要出现的人、物、景(「一只猫」「一束向日葵」);只说「主题」「氛围」「风格」不算给了主体(「秋季新品」是主题,「一束向日葵」才是主体);风格、流派、季节、情绪只说明怎么画,不说明画什么(「赛博朋克」「极简」「水彩」「秋天」「高级感」都不算主体)。可以写「不要出现 XX」来排除元素,但那是弱提示、不保证生效。用户说「绝对不能有 XX」「必须没有 XX」时,先用这句话说明做不到硬排除、问他要不要接受「写了但不保证」——他接受才画(就是上面七条的第五条)。要让图上出现文字就写明确切文字和位置,10 个字以内;整段控制在 300 字以内(按汉字算)——超了不会报错,但后半段容易被忽略,所以用户给的长描述先由你压到 300 字以内,压完直接调,并在回复里附上实际用的那版 prompt。改图时用相对的说法——「保持第一张图的主体、构图、光线不变,只把 X 改成 Y」——不要描述你没看到的具体细节;这次 size 换了比例时别写「构图不变」也别写「只换画布」:工具实际会裁切或留白,画面内容会变,只写「保持主体和光线不变」。用户只说改尺寸或方向、没说改内容时,prompt 就写「保持主体和光线不变,按新的画布重新构图」,不要另编画面内容。\n(b) 花多少:按张计费,国内版约 5.71 积分/张,国际版约 0.03 积分/张,相差约 190 倍;文生图和改图同价。报价按这个口径:还没拿到 credit 就两个区各报一个数(如「每张:国内版约 5.71、国际版约 0.03 积分」),说清「2 张就是国内约 11.4 / 国际约 0.06」,并说明走哪个区这一次定不了、以返回的 credit 为准。本次调用返回过 credit 的(同一张图、同一次请求)就直接按那个数报;没拿到过 credit 就报两档,别拿上一次的 credit 报这一次——换区、换模型都会变价。实扣和你报的「约」对不上(差一个量级通常说明这次走了另一个区)就照实说实际扣了多少,别替它圆。积分不等于人民币、也没有汇率,问折合多少照实说给不出。单张也要先把这两档价说一句,然后在同一轮里接着调——先说后调,不等回应;这是告知,不是请示(改图会改版式、要出多张这些仍在七条里,得等同意)。但用户这一句只是在问价(「多少钱」「先别画」)就只报、不调。用户要锁定金额只有一条路:按 (c) 关掉一个区的开关,让下一次只可能走另一个区。\n(c) 走哪个区:只看账号的配置,不看这次调用——插件里两个区可以分别登录、分别打开「允许模型自主生图」,本次走的是「开着且打开了那个开关」的区;两个区都满足时走国内版(贵的那一档),只开国际版时才走国际版。本次走哪个区调用前查不到,以返回的 region 为准(cn=国内版、global=国际版),回复里翻译成中文。用户嫌贵或问「能不能走便宜的那个区」,就告诉他去插件设置把不想用的那个区的「允许模型自主生图」关掉,下一次调用才生效;改设置之前这一张先别调,等改完再调,否则照样按国内版扣。用户问价就按 (b) 的两个数报,不要为了问价去出图;多张且没说同异时先问同异再报总价。要拿到真实单价就得真调一次,那就先说清「这一次会真扣一次积分」,用户同意再调。报 NOT_LOGGED_IN 时你看不出卡在哪个区,让用户把两个区都查一遍:登录了没、那个开关开了没——报这个错时还没发请求,不扣积分。\n(d) size 怎么填(必填):写「宽x高」的像素数(例如 1024x1536),改图也可以写 auto。**先过 (a) 的主体门槛**:主体没给、还在问「想画什么」的时候,后面的推导一条都不要走,更不要为了尺寸先出一张。主体确认之后,按顺序匹配,命中一条就停(比例词和方向词都算「用户提了」):\n① 用户对输出图给了具体像素 → 先改写成「数字 + x」再传(1024*1024、1024 by 1024 都写成 1024x1024;带空格、*、by 的写法宿主会直接拒掉,改写必须你自己做;大小写和 × 不用管);越界也别自己缩,工具会缩——唯一的例外是比 5:1 还细长的比例,那种缩不出合法值,见下面的范围段。改图时这是输出画布,不等于原图尺寸:输入图的宽高永远不是 size 的值——用户说「我这张图是 1600x900」是在交代输入图,照 ④ 处理。\n② 比例词各对应唯一一档:「16:9」2560x1440、「9:16」1440x2560、「4:3」2048x1536、「3:4」1536x2048、「3:2」1536x1024、「2:3」1024x1536、「1:1」1024x1024。比例词压过档位词和方向词——「2K 的 16:9 壁纸」还是 2560x1440(不是方图 2048x2048),「16:9 横图」也是 2560x1440,不是 3:2 的 1536x1024。比例词一旦命中,就不再因为用户又加了 2K / 4K / 高清 / 大图而改值,唯一例外是「1:1」:只说 1:1 是 1024x1024,同时说了 2K / 4K / 高清 / 大图才写 2048x2048(别的比例词没有这个例外)。比例词和方向词打架时按比例词,并把这件事说出来——「9:16 横图」写 1440x2560(竖的),回复里要说明「按 9:16 出的是竖图,和您说的横版不一致」。\n③ 档位词只在用户没提比例词时生效,一词一档:「2K」横 2560x1440、竖 1440x2560、方 2048x2048;「4K」不设独立档,直接用上面 2K 那组值(横的 2560x1440 就填这个)。别按常识换成 3840x2160 或 4096x2160:本工具最长边只有 2560,写大了会被等比缩回 2K 档,尺寸一样、描述还多一句换算;「高清」按 2K;「1080P」横 1920x1080、竖 1080x1920,「720P」横 1280x720、竖 720x1280——方向统一这么定:用户明说了横/竖/方就按他说的;没说就看用途(桌面壁纸算横,手机壁纸、竖版海报、开屏算竖);用途也没说就用方。1080P / 720P 没有方档,这两个落到「用途也没说」时按横的给(「1080P 的竖版海报」:海报算竖,给 1080x1920)。同一句里既说了档位词又说了用途时,尺寸按本阶(档位词)走,用途只用来定方向——「4K 配图」是 2048x2048,不是 ⑤ 的 1024x1024。只有用户提的档位超出本工具上限(说「4K」「8K」「原图那么大」)时,才在回复里补一句「本工具最长边 2560,出的是这一档」;说 2K / 高清 / 1080P 的不必提 4K 这回事。\n④ 有输入图(改图)时:先把「用户说的到底是输出尺寸还是输入图尺寸」分清楚——「改成 1200x800」「要 9:16」是输出;「我这张是 1600x900」是输入,输入尺寸永远不填进 size,这种情况直接写 auto。同一句里既有输入图尺寸又有比例时(「这张 4000x1000 的图改成 4:5」),输入那个数不参与匹配,按比例走:4000x1000 只是输入尺寸,size 填 ⑥ 算出来的 4:5 那组。分完之后按这个顺序定:提了输出像素 → 用 ①;提了比例 → 用 ②;提了档位词 → 用 ③;提了用途 → 用 ⑤;只提了方向 → 见 ⑦;只说了「保持原比例」「版式别动」「就按这张的比例」,或什么都没提、或只是交代了输入图多大(「我这张是 1600x900」)→ 写 auto。改图只要 size 的比例可能和原图不一样(写了具体比例,或按档位词 / 方向 / 用途给了某个档),工具就按 size 裁切或留白原图,版式会变——调用前先说一句「会按这个比例裁切/留白,原版式可能被切」,他同意再调,别等出完图才说。他不接受裁切就改用 auto——auto 会保住原版式;只有原图比 5:1 还细长时 auto 也会换比例(见下面的范围段),那种要提前说。\n⑤ 用户说了用途(一样先过 (a):只有用途没有主体,先问「想画什么」,别拿用途当主体)→ 配图、插图、封面、头像、表情包 1024x1024;要「大一点的方图」或「大图」单独出现 → 2048x2048;桌面壁纸 2560x1440;手机壁纸、竖版海报(要说到「海报」才算)、手机开屏 1440x2560;只说「竖版」「横版」「方图」是方向词,走 ⑦,不算用途。表里每行都自带方向,命中一行就用它;用户另外说的方向与这一行冲突就交换宽高:横的行他要竖 → 1024x1536,竖的行他要横 → 1536x1024,方的行他要横 → 1536x1024、要竖 → 1024x1536(「给这篇文章配张图,要横的」→ 1536x1024,不是 1024x1024);方向与这一行相同就照这一行走(「做张手机壁纸,要竖的」→ 仍是 1440x2560)。比例词已命中的到不了这一阶(「1:1 的配图,要横的」按 ② 走)。用途不在表里,且用户另外说了方向 → 见 ⑦;连方向也没说 → 1024x1024。\n⑥ 用户说的是表里没有的比例(4:5、21:9、5:4 等)→ 就按这个比例写一组像素:两个上限取更严的那个(长边 2560、面积 4,194,304),按比例算完取整、再把宽高乘一遍验算(21:9 → 2560x1097;4:5 → 1831x2289,再多一号就超面积)。这一阶只在你需要自己算像素时用,而算出来的比例不能比 5:1 更细长(8:1 这种长边算到 2560 时短边只剩 320,固定像素在本地必被拒,见下面的范围段)——遇到这种比例:改图就改用 auto,文生图没有 auto 可退(auto 要量输入图,没图会在本地报错),只能先跟用户说最细到 5:1、让他换个不那么细长的比例。算出来的宽高先按 ④ 说给用户(改图时尤其要说会被裁切),同意后再调用;调用完把实际填的宽高写进回复。\n⑦ 只提了方向、比例档位用途都没提 → 取 ② 表里同方向那一档:横 1536x1024、竖 1024x1536、方 1024x1024。这一阶管所有方向词:④ 里「只提了方向」、③ 里定方向、⑤ 里表外用途,都落到这里。\n⑧ 以上全都没命中、也看不出方向 → 1024x1024(默认档),回复里说一句是按默认档出的。⑧ 只管尺寸,不给主体发通行证:「随便画一张」没有主体,先按 (a) 问清想画什么,再回来走这一阶。改图有输入图时走不到这一阶——「什么都没提」在 ④ 已经派给 auto 了,别把原图裁成方图。\n范围:两条边各 512–2560,宽乘高不超过 4,194,304(这是工具的上限;① 里说「别自己缩」是因为工具会替你缩,⑤ 里那几档本身都在范围内)。写超了、或某条边小于 512,都不用你换算:工具会等比缩/放后照常出图,并把「按你给的 X 缩放成 WxH」写进 hint,同时回带 requestedSize——这句必须转告用户,别把缩过的尺寸说成用户要的。比例极端到缩不进这个范围(比 5:1 还细长)时:写了固定像素就在本地报错、不扣积分;写 auto(只有改图能写)则会改用该方向的常用档、照常出图,并在 hint 里说明比例有变化——能出图,但不是原比例,这一句同样要转告用户。\nimage 是改图用的参考图,写成数组,一张也写 [\"/abs/a.png\"];数组长度只表示参考图张数,不影响出图张数(永远一张)。多张按顺序全部生效,第一张当主参考,主体冲突以第一张为准。纯文生图把这个字段整个省掉,不要传空数组([] 会被拒)。格式与 8 MB 上限见 image 参数的说明。用户只说「这张图」却没给路径时先问他要路径,别猜一个;前面哪一轮给过就沿用那一张,调用前把文件名说出来确认。\nmodel 一般留空(或空字符串):留空就用该区目录里第一个带对应 tag 的模型(文生图 text-to-image、改图 image-to-image)。用户点名要某个模型就照他给的 id 填(区域和目录查不到不影响填),填了不存在或没有对应 tag 的 id 会直接报错并列出可用 id——别自己编 id。用户说「用上次那个模型」这类指代、没给 id 时,留空按目录第一个,并告诉他这次实际用的是哪个。用户说「用便宜的那个」是在说区、不是模型,按 (c) 回答。\n计费边界分三种说法:返回带 url 又带 credit → 按 credit 说实扣了多少;带 url 但没 credit → 按 (b) 的两档估,并说明以账单为准;没拿到图、但请求已经发到上游(超时、审核拒绝、上游报错)→ 只能说「这一次没拿到图、可能已扣费」,不得断言没扣费、不得自己重发,由用户决定要不要再花一次。清单里这些是「请求根本没发到上游」,确定不扣积分,可以改完直接重试:宿主把参数挡下来(size 不是「宽x高」也不是 auto、image 空数组、多传了别的字段)、size 写了 auto 但这次没给输入图(文生图)、写了固定像素但比例比 5:1 还细长、model 不存在、图读不出来或超过 8 MB、没登录或没开那个开关。判据:本地拒一定带 INVALID_ARGS 或 NOT_LOGGED_IN 这种错误码;抛的不是这两个码、又没拿到图,一律按「可能已扣费」讲。重试等于新的一次计费决策:本地拒那种改完直接重试;其余情况重试前按 (b) 重新报价并取得同意。\n返回:url(COS 签名 URL,约 24 小时后失效;只有 path 那种情况下 url 是 file:// 本地地址、不过期)、mode(generate 或 edit)、region(cn/global)、size(实际出图宽高)、model、prompt、hint(可直接转述给用户)、credit(上游结算的实际积分,没给就没这个字段)、requestedSize(尺寸被缩/放过时才回带,是你原本写的值)、path(上游返回内联 base64 时本工具落盘才有,此时也有一份 url 是 file:// 地址)。展示给用户时用 markdown 图片语法:有 path 就用 path(本地文件,不过期);只有 url 时引用它并提醒尽快转存——本工具不负责下载或转存,要长期保存得用户自己点开链接另存。",
6742
+ description: "用 WorkBuddy 生图或改图:一次调用只出一张图,要几张就调几次,每张单独计费。本工具没有 seed、不存历史、不能重放:同一段 prompt 重调不保证张张一样。所以先判一件事,跟要几张无关——用户要的是「一样」还是「不同」:(i) 要「一样」「同款」「同一张」「复制几张」「跟上一张一样」→ 做不到,说明原因,让他只出一张自己复制;不报价、不调用。要几张「都一样」就走这一条,不是「出 N 张」。(ii) 要「不同风格」「各来一张」→ 按 (b) 的口径报张数和总价(「4 张:国内版约 22.8、国际版约 0.12 积分」)→ 等他明确同意 → 连着调 N 次,每次换 prompt(换姿态、视角、光位)。(iii) 要「挑一张」「先看一张」→ 先出 1 张给他看,满意再按张补后面的,补之前重新报一次总价。没说同异、只问张数价钱(「4 张要多少钱」)→ 先问「要一样的还是各不相同的」,问完再报。这三条用 (i)(ii)(iii) 编号,(d) 里的 ①②③④⑤⑥⑦⑧ 是 size 的台阶,两套编号别混。什么时候必须先停下等用户点头,只看这七条:要出超过一张、这次调用会改变原图版式(裁切/留白)、文生图且主体还没定、用户把某个超过 2560 的像素当验收标准(原话里有「必须」「正好」「就是要」「不能改」)、用户要求硬排除某个元素(「绝对不能有 XX」)、要自己按表外比例算像素(见 ⑥)、用户本轮或上一轮里说过嫌贵、或正要你改区设置((c))。七条都不成立(单张文生图、size 用现成档位)就直接调,不用等点头;但单张仍要按 (b) 报一次两档价——那是告知,不是请示。成立两条以上时合成一次问完。「同意」只算用户明确说同意,沉默、反问、换话题都不算。\n(a) 画什么:prompt 写主体、风格、构图、光线。用户给了主体、只是没给风格和光线,就由你补,别为这个反问他;只有 text-to-image 才受这条限制:用户连主体都没给(只说了尺寸、比例、档位、用途、方向或风格)就先问「想画什么」,不要自己编一个主体去扣积分。改图(给了 image)不算没主体——参考图本身就是主体,别拿着图还问「想画什么」。主体=画面上要出现的人、物、景(「一只猫」「一束向日葵」);只说「主题」「氛围」「风格」不算给了主体(「秋季新品」是主题,「一束向日葵」才是主体);风格、流派、季节、情绪只说明怎么画,不说明画什么(「赛博朋克」「极简」「水彩」「秋天」「高级感」都不算主体)。可以写「不要出现 XX」来排除元素,但那是弱提示、不保证生效。用户说「绝对不能有 XX」「必须没有 XX」时,先用这句话说明做不到硬排除、问他要不要接受「写了但不保证」——他接受才画(就是上面七条的第五条)。要让图上出现文字就写明确切文字和位置,10 个字以内;整段控制在 300 字以内(按汉字算)——超了不会报错,但后半段容易被忽略,所以用户给的长描述先由你压到 300 字以内,压完直接调,并在回复里附上实际用的那版 prompt。改图时用相对的说法——「保持第一张图的主体、构图、光线不变,只把 X 改成 Y」——不要描述你没看到的具体细节;这次 size 换了比例时别写「构图不变」也别写「只换画布」:工具实际会裁切或留白,画面内容会变,只写「保持主体和光线不变」。用户只说改尺寸或方向、没说改内容时,prompt 就写「保持主体和光线不变,按新的画布重新构图」,不要另编画面内容。\n(b) 花多少:按张计费,国内版约 5.71 积分/张,国际版约 0.03 积分/张,相差约 190 倍;文生图和改图同价。报价按这个口径:还没拿到 credit 就两个区各报一个数(如「每张:国内版约 5.71、国际版约 0.03 积分」),说清「2 张就是国内约 11.4 / 国际约 0.06」,并说明走哪个区这一次定不了、以返回的 credit 为准。本次调用返回过 credit 的(同一张图、同一次请求)就直接按那个数报;没拿到过 credit 就报两档,别拿上一次的 credit 报这一次——换区、换模型都会变价。实扣和你报的「约」对不上(差一个量级通常说明这次走了另一个区)就照实说实际扣了多少,别替它圆。积分不等于人民币、也没有汇率,问折合多少照实说给不出。单张也要先把这两档价说一句,然后在同一轮里接着调——先说后调,不等回应;这是告知,不是请示(改图会改版式、要出多张这些仍在七条里,得等同意)。但用户这一句只是在问价(「多少钱」「先别画」)就只报、不调。用户要锁定金额只有一条路:按 (c) 关掉一个区的开关,让下一次只可能走另一个区。国内区还有第二条路:卡片上把生图模型选成 hunyuan-image-v3.0,出图不带水印,但约 11.1 积分/张(贵约一倍)、尺寸上限也小得多;用户抱怨水印时就把这条如实告诉他,并说明上游没有「关水印」的开关——只能换模型;不要承诺能去掉水印,也不要自己替他换。\n(c) 走哪个区:只看账号的配置,不看这次调用——插件里两个区可以分别登录、分别打开「允许模型自主生图」,本次走的是「开着且打开了那个开关」的区;两个区都满足时走国内版(贵的那一档),只开国际版时才走国际版。本次走哪个区调用前查不到,以返回的 region 为准(cn=国内版、global=国际版),回复里翻译成中文。用户嫌贵或问「能不能走便宜的那个区」,就告诉他去插件设置把不想用的那个区的「允许模型自主生图」关掉,下一次调用才生效;改设置之前这一张先别调,等改完再调,否则照样按国内版扣。用户问价就按 (b) 的两个数报,不要为了问价去出图;多张且没说同异时先问同异再报总价。要拿到真实单价就得真调一次,那就先说清「这一次会真扣一次积分」,用户同意再调。报 NOT_LOGGED_IN 时你看不出卡在哪个区,让用户把两个区都查一遍:登录了没、那个开关开了没——报这个错时还没发请求,不扣积分。\n(d) size 怎么填(必填):写「宽x高」的像素数(例如 1024x1536),改图也可以写 auto。**先过 (a) 的主体门槛**:主体没给、还在问「想画什么」的时候,后面的推导一条都不要走,更不要为了尺寸先出一张。主体确认之后,按顺序匹配,命中一条就停(比例词和方向词都算「用户提了」):\n① 用户对输出图给了具体像素 → 先改写成「数字 + x」再传(1024*1024、1024 by 1024 都写成 1024x1024;带空格、*、by 的写法宿主会直接拒掉,改写必须你自己做;大小写和 × 不用管);越界也别自己缩,工具会缩——唯一的例外是比 5:1 还细长的比例,那种缩不出合法值,见下面的范围段。改图时这是输出画布,不等于原图尺寸:输入图的宽高永远不是 size 的值——用户说「我这张图是 1600x900」是在交代输入图,照 ④ 处理。\n② 比例词各对应唯一一档:「16:9」2560x1440、「9:16」1440x2560、「4:3」2048x1536、「3:4」1536x2048、「3:2」1536x1024、「2:3」1024x1536、「1:1」1024x1024。比例词压过档位词和方向词——「2K 的 16:9 壁纸」还是 2560x1440(不是方图 2048x2048),「16:9 横图」也是 2560x1440,不是 3:2 的 1536x1024。比例词一旦命中,就不再因为用户又加了 2K / 4K / 高清 / 大图而改值,唯一例外是「1:1」:只说 1:1 是 1024x1024,同时说了 2K / 4K / 高清 / 大图才写 2048x2048(别的比例词没有这个例外)。比例词和方向词打架时按比例词,并把这件事说出来——「9:16 横图」写 1440x2560(竖的),回复里要说明「按 9:16 出的是竖图,和您说的横版不一致」。\n③ 档位词只在用户没提比例词时生效,一词一档:「2K」横 2560x1440、竖 1440x2560、方 2048x2048;「4K」不设独立档,直接用上面 2K 那组值(横的 2560x1440 就填这个)。别按常识换成 3840x2160 或 4096x2160:本工具最长边只有 2560,写大了会被等比缩回 2K 档,尺寸一样、描述还多一句换算;「高清」按 2K;「1080P」横 1920x1080、竖 1080x1920,「720P」横 1280x720、竖 720x1280——方向统一这么定:用户明说了横/竖/方就按他说的;没说就看用途(桌面壁纸算横,手机壁纸、竖版海报、开屏算竖);用途也没说就用方。1080P / 720P 没有方档,这两个落到「用途也没说」时按横的给(「1080P 的竖版海报」:海报算竖,给 1080x1920)。同一句里既说了档位词又说了用途时,尺寸按本阶(档位词)走,用途只用来定方向——「4K 配图」是 2048x2048,不是 ⑤ 的 1024x1024。只有用户提的档位超出本工具上限(说「4K」「8K」「原图那么大」)时,才在回复里补一句「本工具最长边 2560,出的是这一档」;说 2K / 高清 / 1080P 的不必提 4K 这回事。\n④ 有输入图(改图)时:先把「用户说的到底是输出尺寸还是输入图尺寸」分清楚——「改成 1200x800」「要 9:16」是输出;「我这张是 1600x900」是输入,输入尺寸永远不填进 size,这种情况直接写 auto。同一句里既有输入图尺寸又有比例时(「这张 4000x1000 的图改成 4:5」),输入那个数不参与匹配,按比例走:4000x1000 只是输入尺寸,size 填 ⑥ 算出来的 4:5 那组。分完之后按这个顺序定:提了输出像素 → 用 ①;提了比例 → 用 ②;提了档位词 → 用 ③;提了用途 → 用 ⑤;只提了方向 → 见 ⑦;只说了「保持原比例」「版式别动」「就按这张的比例」,或什么都没提、或只是交代了输入图多大(「我这张是 1600x900」)→ 写 auto。改图只要 size 的比例可能和原图不一样(写了具体比例,或按档位词 / 方向 / 用途给了某个档),工具就按 size 裁切或留白原图,版式会变——调用前先说一句「会按这个比例裁切/留白,原版式可能被切」,他同意再调,别等出完图才说。他不接受裁切就改用 auto——auto 会保住原版式;只有原图比 5:1 还细长时 auto 也会换比例(见下面的范围段),那种要提前说。\n⑤ 用户说了用途(一样先过 (a):只有用途没有主体,先问「想画什么」,别拿用途当主体)→ 配图、插图、封面、头像、表情包 1024x1024;要「大一点的方图」或「大图」单独出现 → 2048x2048;桌面壁纸 2560x1440;手机壁纸、竖版海报(要说到「海报」才算)、手机开屏 1440x2560;只说「竖版」「横版」「方图」是方向词,走 ⑦,不算用途。表里每行都自带方向,命中一行就用它;用户另外说的方向与这一行冲突就交换宽高:横的行他要竖 → 1024x1536,竖的行他要横 → 1536x1024,方的行他要横 → 1536x1024、要竖 → 1024x1536(「给这篇文章配张图,要横的」→ 1536x1024,不是 1024x1024);方向与这一行相同就照这一行走(「做张手机壁纸,要竖的」→ 仍是 1440x2560)。比例词已命中的到不了这一阶(「1:1 的配图,要横的」按 ② 走)。用途不在表里,且用户另外说了方向 → 见 ⑦;连方向也没说 → 1024x1024。\n⑥ 用户说的是表里没有的比例(4:5、21:9、5:4 等)→ 就按这个比例写一组像素:两个上限取更严的那个(长边 2560、面积 4,194,304),按比例算完取整、再把宽高乘一遍验算(21:9 → 2560x1097;4:5 → 1831x2289,再多一号就超面积)。这一阶只在你需要自己算像素时用,而算出来的比例不能比 5:1 更细长(8:1 这种长边算到 2560 时短边只剩 320,固定像素在本地必被拒,见下面的范围段)——遇到这种比例:改图就改用 auto,文生图没有 auto 可退(auto 要量输入图,没图会在本地报错),只能先跟用户说最细到 5:1、让他换个不那么细长的比例。算出来的宽高先按 ④ 说给用户(改图时尤其要说会被裁切),同意后再调用;调用完把实际填的宽高写进回复。\n⑦ 只提了方向、比例档位用途都没提 → 取 ② 表里同方向那一档:横 1536x1024、竖 1024x1536、方 1024x1024。这一阶管所有方向词:④ 里「只提了方向」、③ 里定方向、⑤ 里表外用途,都落到这里。\n⑧ 以上全都没命中、也看不出方向 → 1024x1024(默认档),回复里说一句是按默认档出的。⑧ 只管尺寸,不给主体发通行证:「随便画一张」没有主体,先按 (a) 问清想画什么,再回来走这一阶。改图有输入图时走不到这一阶——「什么都没提」在 ④ 已经派给 auto 了,别把原图裁成方图。\n范围:两条边各 512–2560,宽乘高不超过 4,194,304(这是工具的上限;① 里说「别自己缩」是因为工具会替你缩,⑤ 里那几档本身都在范围内)。写超了、或某条边小于 512,都不用你换算:工具会等比缩/放后照常出图,并把「按你给的 X 缩放成 WxH」写进 hint,同时回带 requestedSize——这句必须转告用户,别把缩过的尺寸说成用户要的。比例极端到缩不进这个范围(比 5:1 还细长)时:写了固定像素就在本地报错、不扣积分;写 auto(只有改图能写)则会改用该方向的常用档、照常出图,并在 hint 里说明比例有变化——能出图,但不是原比例,这一句同样要转告用户。\nimage 是改图用的参考图,写成数组,一张也写 [\"/abs/a.png\"];数组长度只表示参考图张数,不影响出图张数(永远一张)。多张按顺序全部生效,第一张当主参考,主体冲突以第一张为准。纯文生图把这个字段整个省掉,不要传空数组([] 会被拒)。格式与 8 MB 上限见 image 参数的说明。用户只说「这张图」却没给路径时先问他要路径,别猜一个;前面哪一轮给过就沿用那一张,调用前把文件名说出来确认。\nmodel 一般留空(或空字符串):留空就用该区目录里第一个带对应 tag 的模型(文生图 text-to-image、改图 image-to-image)。用户点名要某个模型就照他给的 id 填(区域和目录查不到不影响填),填了不存在或没有对应 tag 的 id 会直接报错并列出可用 id——别自己编 id。用户说「用上次那个模型」这类指代、没给 id 时,留空按目录第一个,并告诉他这次实际用的是哪个。用户说「用便宜的那个」是在说区、不是模型,按 (c) 回答。用户明确说「不要水印」「去掉水印」时才填 hunyuan-image-v3.0(只有国内区有),并当场说明代价:约 11.1 积分/张、最大约 104 万像素(1024x1024 顶格;1024x1536 这类竖版会等比缩成 836x1254,比例不变但更小);用户没提水印就别主动换,默认那条更便宜、尺寸档位也全。\n计费边界分三种说法:返回带 url 又带 credit → 按 credit 说实扣了多少;带 url 但没 credit → 按 (b) 的两档估,并说明以账单为准;没拿到图、但请求已经发到上游(超时、审核拒绝、上游报错)→ 只能说「这一次没拿到图、可能已扣费」,不得断言没扣费、不得自己重发,由用户决定要不要再花一次。清单里这些是「请求根本没发到上游」,确定不扣积分,可以改完直接重试:宿主把参数挡下来(size 不是「宽x高」也不是 auto、image 空数组、多传了别的字段)、size 写了 auto 但这次没给输入图(文生图)、写了固定像素但比例比 5:1 还细长、model 不存在、图读不出来或超过 8 MB、没登录或没开那个开关。判据:本地拒一定带 INVALID_ARGS 或 NOT_LOGGED_IN 这种错误码;抛的不是这两个码、又没拿到图,一律按「可能已扣费」讲。重试等于新的一次计费决策:本地拒那种改完直接重试;其余情况重试前按 (b) 重新报价并取得同意。\n返回:url(COS 签名 URL,约 24 小时后失效;只有 path 那种情况下 url 是 file:// 本地地址、不过期)、mode(generate 或 edit)、region(cn/global)、size(实际出图宽高)、model、prompt、hint(可直接转述给用户)、credit(上游结算的实际积分,没给就没这个字段)、requestedSize(尺寸被缩/放过时才回带,是你原本写的值)、path(上游返回内联 base64 时本工具落盘才有,此时也有一份 url 是 file:// 地址)。展示给用户时用 markdown 图片语法:有 path 就用 path(本地文件,不过期);只有 url 时引用它并提醒尽快转存——本工具不负责下载或转存,要长期保存得用户自己点开链接另存。",
6669
6743
  parameters: {
6670
6744
  type: "object",
6671
6745
  properties: {
@@ -6791,11 +6865,13 @@ function createImageTool(deps) {
6791
6865
  try {
6792
6866
  const models = await listModels(credential, signal);
6793
6867
  const resolved = images === void 0 ? void 0 : await Promise.all(images.map((image) => resolveImageInput(image, signal)));
6868
+ const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6794
6869
  const inputSize = resolved === void 0 ? void 0 : firstDimensions(resolved);
6795
- const plan = planImageSize(sizeSpec, inputSize);
6796
- const size = plan.size;
6870
+ if (sizeSpec.kind === "auto" && inputSize === void 0) missingAutoSizeInput();
6797
6871
  const inputs = resolved?.map((input) => input.dataUrl);
6798
- const model = pickMediaModel(models, requestedModel, inputs === void 0 ? IMAGE_TAG_TEXT_TO_IMAGE : IMAGE_TAG_IMAGE_TO_IMAGE);
6872
+ const model = resolveImageModel(models, requestedModel, inputs === void 0 ? IMAGE_TAG_TEXT_TO_IMAGE : IMAGE_TAG_IMAGE_TO_IMAGE, deps, credential, region);
6873
+ const plan = planImageSize(sizeSpec, inputSize, imageSizeLimitsOf(model.id));
6874
+ const size = plan.size;
6799
6875
  sent = true;
6800
6876
  const outcome = inputs === void 0 ? await deps.generateImage(credential, {
6801
6877
  model: model.id,
@@ -6808,17 +6884,17 @@ function createImageTool(deps) {
6808
6884
  image: inputs
6809
6885
  }, signal);
6810
6886
  const mode = inputs === void 0 ? "generate" : "edit";
6811
- const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6812
6887
  const regionLabel = region === "global" ? "国际版" : "国内版";
6813
6888
  const dimensionNote = plan.note === void 0 ? "" : `${plan.note}。`;
6814
6889
  const inputNote = inputSize === void 0 ? "" : `输入图第一张是 ${inputSize.width}x${inputSize.height}(${ORIENTATION_LABEL[orientationOf(inputSize)]})。`;
6890
+ const watermarkNote = isWatermarkFreeImageModel(model.id) ? "这个模型出图不带 WorkBuddy 水印(代价是单价更高、尺寸上限更小)。" : "这个模型出的图右下角带「AI生成 WORKBUDD>」水印——上游没有关闭它的参数;要无水印可在插件卡片里把生图模型选成 hunyuan-image-v3.0(更贵、尺寸上限更小)。";
6815
6891
  const value = {
6816
6892
  mode,
6817
6893
  region,
6818
6894
  size,
6819
6895
  model: model.id,
6820
6896
  prompt,
6821
- hint: `这张图来自 WorkBuddy ${regionLabel}(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"},尺寸 ${size})。` + inputNote + dimensionNote + (outcome.credit === void 0 ? "本次响应没带扣费字段,具体扣了多少以额度面板为准。" : `本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6897
+ hint: `这张图来自 WorkBuddy ${regionLabel}(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"},尺寸 ${size})。` + inputNote + dimensionNote + watermarkNote + (outcome.credit === void 0 ? "本次响应没带扣费字段,具体扣了多少以额度面板为准。" : `本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6822
6898
  };
6823
6899
  if (plan.requested !== void 0 && plan.requested !== size) value["requestedSize"] = plan.requested;
6824
6900
  if (outcome.url !== void 0) value["url"] = outcome.url;
@@ -9509,7 +9585,8 @@ function parseUpstreamResetAt(message) {
9509
9585
  return utcMs - offsetTotalMinutes * 6e4;
9510
9586
  }
9511
9587
  /**
9512
- * The cooldown the upstream stated, if it stated one.
9588
+ * The upstream reset metadata, if stated. A credit-package refresh timestamp
9589
+ * is retained for diagnostics; it is not a minimum wait or recovery evidence.
9513
9590
  *
9514
9591
  * Three sources, in order of authority:
9515
9592
  *
@@ -9520,13 +9597,13 @@ function parseUpstreamResetAt(message) {
9520
9597
  * this service: a 429 from the Chinese gateway carries code 6004 and a
9521
9598
  * `将在 … 重置` sentence, with no `Retry-After` header at all.
9522
9599
  * 3. The region's monthly quota refresh point, but ONLY for an out-of-credit
9523
- * outcome. A quota that resets at a known time is the one case where "when
9524
- * can I use this again" has a real answer even without a header — and it is
9525
- * the answer for the most common real limit on this service.
9600
+ * outcome. Check-in or a purchase can replenish credits earlier, so callers
9601
+ * must not render this metadata as a recovery countdown or release the
9602
+ * account when the timestamp passes.
9526
9603
  *
9527
- * A limited outcome with none of the three returns `{}`, which the card renders
9528
- * as "the upstream did not say when". That remains the honest answer for a
9529
- * genuinely timeless failure; inventing a number here would be pure fiction.
9604
+ * A limited outcome with none of the three returns `{}`. Rate-limit views state
9605
+ * that no time was given; credit-exhaustion views name the replenishment action
9606
+ * instead. Neither view invents a countdown.
9530
9607
  *
9531
9608
  * An `ok` outcome ALWAYS returns `{}`, whatever headers or body came with it.
9532
9609
  * A successful probe has already answered "can this account serve right now?"
@@ -10155,7 +10232,7 @@ function exclusionOf(probe, nowMs) {
10155
10232
  case "failed": return retryDue(probe, nowMs) ? void 0 : "failed";
10156
10233
  case "rate-limited": return retryDue(probe, nowMs) ? void 0 : "rate-limited";
10157
10234
  case "model-busy": return retryDue(probe, nowMs, 12e4) ? void 0 : "model-busy";
10158
- case "out-of-credit": return retryDue(probe, nowMs) ? void 0 : "out-of-credit";
10235
+ case "out-of-credit": return "out-of-credit";
10159
10236
  case "policy-rejected": return;
10160
10237
  case "channel-rejected": return;
10161
10238
  default: return "unusable";
@@ -10164,11 +10241,10 @@ function exclusionOf(probe, nowMs) {
10164
10241
  /**
10165
10242
  * Whether an account's cooldown has elapsed (or was never stated).
10166
10243
  *
10167
- * The fallback is the ONLY thing a transient outcome relies on: `cooldownOf`
10168
- * attaches `retryAtMs` for a rate limit or a drained quota, never for a
10169
- * transport failure, so `atMs + POOL_UNKNOWN_COOLDOWN_MS` is what brings those
10170
- * back. That is deliberate — the alternative is a permanent exclusion decided by
10171
- * an event that said nothing about the account.
10244
+ * Transient failures without a stated retry time use the local short window.
10245
+ * Credit exhaustion is cleared by later positive balance evidence or an explicit
10246
+ * successful pool test; ordinary chat success does not update the probe store.
10247
+ * It does not call this helper.
10172
10248
  *
10173
10249
  * `fallbackMs` lets one outcome carry a SHORTER clock than the generic one: the
10174
10250
  * model-scoped throttle is upstream's own "about a minute", and applying the
@@ -10179,6 +10255,30 @@ function retryDue(probe, nowMs, fallbackMs = POOL_UNKNOWN_COOLDOWN_MS) {
10179
10255
  return nowMs >= (probe.retryAtMs ?? probe.atMs + fallbackMs);
10180
10256
  }
10181
10257
  /**
10258
+ * When an EXCLUDED account becomes a candidate again, in epoch ms.
10259
+ *
10260
+ * Same arithmetic as {@link retryDue} — deliberately, so the two can never
10261
+ * disagree about when an account is back: this answers "at what instant", that
10262
+ * one answers "is that instant past". Two separate clocks would let the card
10263
+ * say "recovers at 14:05" while the ranking still refuses it at 14:06.
10264
+ *
10265
+ * `Infinity` when time cannot fix the account: a rejected token and a
10266
+ * restricted or banned account are states a cooldown cannot repair, so they
10267
+ * sort after everything that merely has to wait (`exclusionOf` gives them no
10268
+ * cooldown at all — this mirrors that, rather than inventing one).
10269
+ */
10270
+ function recoversAtOf(probe, excludedBy, fallbackMs = POOL_UNKNOWN_COOLDOWN_MS) {
10271
+ if (probe === void 0) return Number.POSITIVE_INFINITY;
10272
+ switch (excludedBy) {
10273
+ case "rate-limited":
10274
+ case "unavailable":
10275
+ case "failed": return probe.retryAtMs ?? probe.atMs + fallbackMs;
10276
+ case "model-busy": return probe.retryAtMs ?? probe.atMs + 12e4;
10277
+ case "out-of-credit": return probe.retryAtMs ?? Number.POSITIVE_INFINITY;
10278
+ default: return Number.POSITIVE_INFINITY;
10279
+ }
10280
+ }
10281
+ /**
10182
10282
  * Rank a pool's members best-first.
10183
10283
  *
10184
10284
  * The rule, in priority order — this is the whole feature:
@@ -10249,11 +10349,13 @@ function rankPool(members, nowMs, orderAccountIds) {
10249
10349
  _atRisk: (member.credits?.expiringSoon ?? 0) > 0,
10250
10350
  _expiringAmount: member.credits?.expiringSoon ?? 0,
10251
10351
  _expiring: member.credits?.nearestExpiryMs ?? Number.POSITIVE_INFINITY,
10252
- _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0
10352
+ _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0,
10353
+ _recoversAt: excludedBy === void 0 ? Number.POSITIVE_INFINITY : recoversAtOf(member.probe, excludedBy)
10253
10354
  };
10254
10355
  });
10255
10356
  rows.sort((left, right) => {
10256
10357
  if (left._usable !== right._usable) return left._usable ? -1 : 1;
10358
+ if (!left._usable && !right._usable && left._recoversAt !== right._recoversAt) return left._recoversAt - right._recoversAt;
10257
10359
  if (left._atRisk !== right._atRisk) return left._atRisk ? -1 : 1;
10258
10360
  if (left._order !== right._order) return left._order - right._order;
10259
10361
  if (left._atRisk && right._atRisk && left._expiring !== right._expiring) return left._expiring - right._expiring;
@@ -11034,18 +11136,24 @@ function knownProbeSource(value) {
11034
11136
  * The two writers describe the same account at different moments and carry
11035
11137
  * different fields:
11036
11138
  *
11037
- * - `test-batch` measures the TARGET MODEL deliberately, so it is the only
11038
- * writer that can produce a refresh point (`retryAtMs` with
11039
- * `retrySource: 'quota-refresh'`) — a time the billing side states outright.
11139
+ * - `test-batch` measures the TARGET MODEL deliberately, and it is the writer
11140
+ * that can attach the monthly refresh point (`retryAtMs` with
11141
+ * `retrySource: 'quota-refresh'`) — recorded as upstream evidence about the
11142
+ * PACKAGE's cycle, not as the moment the account becomes usable again.
11040
11143
  * - `live-request` reports what a real chat request just hit. It often carries
11041
11144
  * no `retryAtMs` at all (a transport blip names no time), and a spread would
11042
- * therefore DELETE the refresh point the probe had already resolved.
11145
+ * therefore DELETE that recorded point.
11043
11146
  *
11044
11147
  * Measured consequence of the spread, on a real `14018` account: the probe
11045
11148
  * recorded "quota refreshes 2026-11-01", the next live failure rewrote the
11046
- * record without that field, and the pool then reported "retry in about 30
11047
- * minutes" — putting an exhausted account back into rotation to be refused
11048
- * again. The correct value was in the file one write earlier.
11149
+ * record without that field, and the card then said the upstream gave no time at
11150
+ * all — while the correct value was in the file one write earlier.
11151
+ *
11152
+ * NOTE that recovery no longer follows from this field: credit exhaustion is
11153
+ * cleared by a later positive balance read, not by the timestamp passing (see
11154
+ * `reconcilePoolCredits` and `exclusionOf`). The point is inherited because it is
11155
+ * upstream evidence worth keeping, and losing it would silently downgrade a
11156
+ * recorded fact to "the upstream said nothing".
11049
11157
  *
11050
11158
  * So `retryAtMs` is INHERITED when the update does not state one, and every
11051
11159
  * other field is the update's (the newer measurement owns `outcome`, `atMs`,
@@ -11104,6 +11212,39 @@ async function writePoolProbes(region, updates) {
11104
11212
  });
11105
11213
  } catch {}
11106
11214
  }
11215
+ /**
11216
+ * 只有失败记录写入之后发起的余额查询,才能解除积分耗尽状态。
11217
+ * 持锁重读可避免较早的查询结果覆盖并发请求刚记录的新失败;其他异常保持原样。
11218
+ * 删除失败记录只表示余额恢复,不会伪造一次成功的模型测试。
11219
+ * 恢复后界面会显示“未测试”:这里删除的是最近失败记录,存储结构没有保留此前
11220
+ * 成功测试的历史,余额到账也不能证明某个模型可用;再次测试才会产生新的结论。
11221
+ */
11222
+ async function reconcilePoolCredits(region, readings) {
11223
+ const path = workbuddyPoolStorePath(region);
11224
+ try {
11225
+ return await withFileLock(path, async () => {
11226
+ const probes = await readPoolProbes(region);
11227
+ let changed = false;
11228
+ for (const reading of readings) {
11229
+ const probe = probes[reading.accountId];
11230
+ if (probe?.outcome !== "out-of-credit" || probe.atMs >= reading.startedAtMs) continue;
11231
+ if (!Number.isFinite(reading.total) || reading.total <= 0) continue;
11232
+ delete probes[reading.accountId];
11233
+ changed = true;
11234
+ }
11235
+ if (changed) await writeFileAtomic(path, `${JSON.stringify({
11236
+ version: STORE_FORMAT_VERSION$1,
11237
+ probes
11238
+ }, null, 2)}\n`, {
11239
+ mode: 384,
11240
+ dirMode: 448
11241
+ });
11242
+ return probes;
11243
+ });
11244
+ } catch {
11245
+ return readPoolProbes(region);
11246
+ }
11247
+ }
11107
11248
  //#endregion
11108
11249
  //#region src/auto-checkin.ts
11109
11250
  /**
@@ -11577,7 +11718,7 @@ function readJsonBody(req, limitBytes = PROBE_BODY_LIMIT) {
11577
11718
  * Origin alone is not enough. It answers "did a foreign page cause this?", but a
11578
11719
  * DNS-rebinding attack arrives with the attacker's domain in `Host` and no
11579
11720
  * useful Origin, so the Host check is what drops it — and until this function
11580
- * existed, all thirteen routes below (ten POST, three GET) had only the Origin
11721
+ * existed, all of the routes below had only the Origin
11581
11722
  * half while the shim's chat route had both. The asymmetry was invisible per-file.
11582
11723
  *
11583
11724
  * Both halves are cheap and NEITHER IS AUTHENTICATION. A local process — or any
@@ -11797,6 +11938,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11797
11938
  const imageToolEnabled = deps.imageToolEnabled?.(region) ?? false;
11798
11939
  const videoToolEnabled = deps.videoToolEnabled?.(region) ?? false;
11799
11940
  const preferredVideoModels = deps.preferredVideoModels?.(region) ?? {};
11941
+ const preferredImageModel = deps.preferredImageModel?.(region) ?? "";
11800
11942
  const cliBridgeEnabled = deps.cliBridgeEnabled?.() === true;
11801
11943
  const sidebarPanelEnabled = deps.sidebarPanelEnabled?.() === true;
11802
11944
  /**
@@ -11829,6 +11971,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11829
11971
  imageToolEnabled,
11830
11972
  videoToolEnabled,
11831
11973
  preferredVideoModels,
11974
+ preferredImageModel,
11832
11975
  cliBridgeEnabled,
11833
11976
  sidebarPanelEnabled,
11834
11977
  pollIntervalMs,
@@ -11855,6 +11998,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11855
11998
  imageToolEnabled,
11856
11999
  videoToolEnabled,
11857
12000
  preferredVideoModels,
12001
+ preferredImageModel,
11858
12002
  cliBridgeEnabled,
11859
12003
  sidebarPanelEnabled,
11860
12004
  pollIntervalMs,
@@ -11884,6 +12028,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11884
12028
  imageToolEnabled,
11885
12029
  videoToolEnabled,
11886
12030
  preferredVideoModels,
12031
+ preferredImageModel,
11887
12032
  cliBridgeEnabled,
11888
12033
  sidebarPanelEnabled,
11889
12034
  pollIntervalMs,
@@ -12080,211 +12225,174 @@ function requestRegion(req, res) {
12080
12225
  */
12081
12226
  function registerWorkBuddyStatusRoute(ctx, deps) {
12082
12227
  ctx.effect(() => {
12083
- const disposeUsage = ctx.webServer.register({
12084
- kind: "exact",
12085
- path: WORKBUDDY_USAGE_PATH,
12086
- handler: async (req, res) => {
12087
- if (req.method !== "GET") {
12088
- json(res, 405, { error: "method not allowed" });
12089
- return;
12228
+ /**
12229
+ * 注册时自动收好 disposer。曾经每个路由 `const disposeX = register(...)`,再
12230
+ * 在末尾手写 16 行 `disposeX()`——`benefit/claim` 漏了一行(issue #86),热重载
12231
+ * 时宿主因重复注册同路径而抛错,后面的路由全部注册不上,卡片半数按钮答 405。
12232
+ * 收成一个数组后,「新加路由忘了加卸载」这一类错误不可能再发生。
12233
+ */
12234
+ const disposers = [];
12235
+ const route = (entry) => {
12236
+ disposers.push(ctx.webServer.register(entry));
12237
+ };
12238
+ /**
12239
+ * 路由骨架:方法闸 → loopback → 可选前置条件 → 区域 → try/catch → 500。
12240
+ *
12241
+ * 这几道闸原先在每个 handler 里各抄一遍(16 处 `requireLoopback`、16 处
12242
+ * `405`、22 处 `500`)。抄漏一道不会有任何编译错误,却是一个真实的
12243
+ * DNS-rebinding 或跨区泄漏面——见 `requireLoopback` 自己的注释。收进这里
12244
+ * 之后,handler 只写业务,也不可能漏闸。
12245
+ *
12246
+ * `ready` 在区域解析**之前**跑:`models` / `media` 这类路由要先答「宿主没有
12247
+ * 这项能力」的 503,再谈区域;反过来会让一个缺区域参数的请求先拿到 400。
12248
+ */
12249
+ function raw(spec, run) {
12250
+ route({
12251
+ kind: "exact",
12252
+ path: spec.path,
12253
+ handler: async (req, res) => {
12254
+ if (req.method !== spec.method) return json(res, 405, { error: "method not allowed" });
12255
+ if (!requireLoopback(req, res)) return;
12256
+ if (spec.ready !== void 0 && !spec.ready(res)) return;
12257
+ try {
12258
+ await run(req, res);
12259
+ } catch (error) {
12260
+ json(res, 500, { error: safeMessage(error) });
12261
+ }
12090
12262
  }
12091
- if (!requireLoopback(req, res)) return;
12263
+ });
12264
+ }
12265
+ /**
12266
+ * 带区域参数的路由:区域解析在 try 之外,与原来的顺序一致。
12267
+ * 不带区域参数的路由直接调 `raw`——区域参数会让 `requestRegion` 把一个
12268
+ * 合法读答成 400(`cli-live` 就是这种)。
12269
+ */
12270
+ function endpointRegion(spec, handle) {
12271
+ raw(spec, (req, res) => {
12092
12272
  const region = requestRegion(req, res);
12093
12273
  if (region === void 0) return;
12094
- const detail = fastDetailOf(req.url ?? "") ? "fast" : "full";
12095
- try {
12096
- json(res, 200, await workBuddyWebStatus(deps, region, { detail }));
12097
- } catch (error) {
12098
- json(res, 500, { error: safeMessage(error) });
12099
- }
12100
- }
12274
+ return handle(req, res, region);
12275
+ });
12276
+ }
12277
+ endpointRegion({
12278
+ path: WORKBUDDY_USAGE_PATH,
12279
+ method: "GET"
12280
+ }, async (req, res, region) => {
12281
+ json(res, 200, await workBuddyWebStatus(deps, region, { detail: fastDetailOf(req.url ?? "") ? "fast" : "full" }));
12101
12282
  });
12102
- const disposeAccountCredits = ctx.webServer.register({
12103
- kind: "exact",
12283
+ endpointRegion({
12104
12284
  path: WORKBUDDY_ACCOUNT_CREDITS_PATH,
12105
- handler: async (req, res) => {
12106
- if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
12107
- if (!requireLoopback(req, res)) return;
12108
- const region = requestRegion(req, res);
12109
- if (region === void 0) return;
12110
- try {
12111
- json(res, 200, { accounts: await workBuddyAccountCredits(deps, region) });
12112
- } catch (error) {
12113
- json(res, 500, { error: safeMessage(error) });
12114
- }
12115
- }
12285
+ method: "GET"
12286
+ }, async (_req, res, region) => {
12287
+ json(res, 200, { accounts: await workBuddyAccountCredits(deps, region) });
12116
12288
  });
12117
- const disposeAccounts = ctx.webServer.register({
12118
- kind: "exact",
12289
+ endpointRegion({
12119
12290
  path: WORKBUDDY_ACCOUNTS_REFRESH_PATH,
12120
- handler: async (req, res) => {
12121
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12122
- if (!requireLoopback(req, res)) return;
12123
- const region = requestRegion(req, res);
12124
- if (region === void 0) return;
12125
- try {
12126
- const store = deps.store(region);
12127
- const dismissalsCleared = await store.clearDismissals();
12128
- const accounts = await store.accounts();
12129
- deps.regionUsable?.(region, accounts.length > 0);
12130
- json(res, 200, {
12131
- accounts: accounts.map(toWebAccount),
12132
- dismissalsCleared
12133
- });
12134
- } catch (error) {
12135
- json(res, 500, { error: safeMessage(error) });
12136
- }
12137
- }
12291
+ method: "POST"
12292
+ }, async (_req, res, region) => {
12293
+ const store = deps.store(region);
12294
+ const dismissalsCleared = await store.clearDismissals();
12295
+ const accounts = await store.accounts();
12296
+ deps.regionUsable?.(region, accounts.length > 0);
12297
+ json(res, 200, {
12298
+ accounts: accounts.map(toWebAccount),
12299
+ dismissalsCleared
12300
+ });
12138
12301
  });
12139
- const disposeCheckin = ctx.webServer.register({
12140
- kind: "exact",
12302
+ endpointRegion({
12141
12303
  path: WORKBUDDY_CHECKIN_PATH,
12142
- handler: async (req, res) => {
12143
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12144
- if (!requireLoopback(req, res)) return;
12145
- const region = requestRegion(req, res);
12146
- if (region === void 0) return;
12147
- try {
12148
- const credential = await deps.store(region).resolve();
12149
- const current = await deps.client.fetchCheckinStatus(credential);
12150
- if (!current.active) return json(res, 409, { error: "check-in activity is not active" });
12151
- if (current.todayCheckedIn) return json(res, 200, {
12152
- alreadyCheckedIn: true,
12153
- checkin: current
12154
- });
12155
- json(res, 200, {
12156
- alreadyCheckedIn: false,
12157
- claim: await deps.client.claimDailyCheckin(credential),
12158
- checkin: await deps.client.fetchCheckinStatus(credential)
12159
- });
12160
- } catch (error) {
12161
- json(res, 500, { error: safeMessage(error) });
12162
- }
12163
- }
12304
+ method: "POST"
12305
+ }, async (_req, res, region) => {
12306
+ const credential = await deps.store(region).resolve();
12307
+ const current = await deps.client.fetchCheckinStatus(credential);
12308
+ if (!current.active) return json(res, 409, { error: "check-in activity is not active" });
12309
+ if (current.todayCheckedIn) return json(res, 200, {
12310
+ alreadyCheckedIn: true,
12311
+ checkin: current
12312
+ });
12313
+ json(res, 200, {
12314
+ alreadyCheckedIn: false,
12315
+ claim: await deps.client.claimDailyCheckin(credential),
12316
+ checkin: await deps.client.fetchCheckinStatus(credential)
12317
+ });
12164
12318
  });
12165
- const disposeBenefitClaim = ctx.webServer.register({
12166
- kind: "exact",
12319
+ endpointRegion({
12167
12320
  path: WORKBUDDY_BENEFIT_CLAIM_PATH,
12168
- handler: async (req, res) => {
12169
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12170
- if (!requireLoopback(req, res)) return;
12171
- const region = requestRegion(req, res);
12172
- if (region === void 0) return;
12173
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
12174
- const accountId = url.searchParams.get(WORKBUDDY_POOL_ACCOUNT_PARAM);
12175
- const kind = url.searchParams.get("kind");
12176
- if (accountId === null || accountId === "") return json(res, 400, { error: "accountId is required" });
12177
- if (kind !== "compensation" && kind !== "gift") return json(res, 400, { error: "kind must be compensation or gift" });
12178
- try {
12179
- const credential = await deps.store(region).credentialFor(accountId);
12180
- if (credential === void 0) return json(res, 404, { error: "no credential for this account" });
12181
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return json(res, 409, { error: "enterprise-account-unsupported" });
12182
- const target = (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind);
12183
- if (target === void 0) return json(res, 404, { error: "benefit not available on this account" });
12184
- if (target.claimed) return json(res, 409, {
12185
- error: "benefit already claimed",
12186
- benefit: target
12187
- });
12188
- if (!target.active) return json(res, 409, {
12189
- error: "benefit activity is not active",
12190
- benefit: target
12191
- });
12192
- await deps.client.claimBenefit(credential, kind);
12193
- deps.pool?.invalidateBenefit?.(region, accountId);
12194
- json(res, 200, {
12195
- claimed: true,
12196
- benefit: (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind) ?? target
12197
- });
12198
- } catch (error) {
12199
- json(res, 500, { error: safeMessage(error) });
12200
- }
12201
- }
12321
+ method: "POST"
12322
+ }, async (req, res, region) => {
12323
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
12324
+ const accountId = url.searchParams.get(WORKBUDDY_POOL_ACCOUNT_PARAM);
12325
+ const kind = url.searchParams.get("kind");
12326
+ if (accountId === null || accountId === "") return json(res, 400, { error: "accountId is required" });
12327
+ if (kind !== "compensation" && kind !== "gift") return json(res, 400, { error: "kind must be compensation or gift" });
12328
+ const credential = await deps.store(region).credentialFor(accountId);
12329
+ if (credential === void 0) return json(res, 404, { error: "no credential for this account" });
12330
+ if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return json(res, 409, { error: "enterprise-account-unsupported" });
12331
+ const target = (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind);
12332
+ if (target === void 0) return json(res, 404, { error: "benefit not available on this account" });
12333
+ if (target.claimed) return json(res, 409, {
12334
+ error: "benefit already claimed",
12335
+ benefit: target
12336
+ });
12337
+ if (!target.active) return json(res, 409, {
12338
+ error: "benefit activity is not active",
12339
+ benefit: target
12340
+ });
12341
+ await deps.client.claimBenefit(credential, kind);
12342
+ deps.pool?.invalidateBenefit?.(region, accountId);
12343
+ json(res, 200, {
12344
+ claimed: true,
12345
+ benefit: (await deps.client.fetchBenefits(credential)).find((benefit) => benefit.kind === kind) ?? target
12346
+ });
12202
12347
  });
12203
- const disposeRefresh = ctx.webServer.register({
12204
- kind: "exact",
12348
+ endpointRegion({
12205
12349
  path: WORKBUDDY_MODELS_REFRESH_PATH,
12206
- handler: async (req, res) => {
12207
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12208
- if (!requireLoopback(req, res)) return;
12209
- if (deps.discoverModels === void 0) return json(res, 503, { error: "model refresh unavailable" });
12210
- if (deps.persistModels === void 0) return json(res, 503, { error: "model refresh cannot be persisted" });
12211
- const region = requestRegion(req, res);
12212
- if (region === void 0) return;
12213
- try {
12214
- const models = await deps.discoverModels(region);
12215
- await deps.persistModels(region, models);
12216
- json(res, 200, { models: models.map((model) => toWebModel(model, deps.contextBudgets(region))) });
12217
- } catch (error) {
12218
- json(res, 500, { error: safeMessage(error) });
12219
- }
12220
- }
12350
+ method: "POST",
12351
+ ready: (res) => deps.discoverModels === void 0 ? (json(res, 503, { error: "model refresh unavailable" }), false) : deps.persistModels === void 0 ? (json(res, 503, { error: "model refresh cannot be persisted" }), false) : true
12352
+ }, async (_req, res, region) => {
12353
+ const models = await deps.discoverModels(region);
12354
+ await deps.persistModels(region, models);
12355
+ json(res, 200, { models: models.map((model) => toWebModel(model, deps.contextBudgets(region))) });
12221
12356
  });
12222
- const disposeMediaModels = ctx.webServer.register({
12223
- kind: "exact",
12357
+ endpointRegion({
12224
12358
  path: WORKBUDDY_MEDIA_MODELS_PATH,
12225
- handler: async (req, res) => {
12226
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12227
- if (!requireLoopback(req, res)) return;
12228
- if (deps.mediaModels === void 0) return json(res, 503, { error: "media model list unavailable" });
12229
- const region = requestRegion(req, res);
12230
- if (region === void 0) return;
12231
- try {
12232
- const refresh = new URL(req.url ?? "/", "http://localhost").searchParams.get("refresh") === "1";
12233
- json(res, 200, { models: (await deps.mediaModels(region, { refresh })).map((model) => ({
12234
- id: model.id,
12235
- name: model.name,
12236
- tags: [...model.tags]
12237
- })) });
12238
- } catch (error) {
12239
- json(res, 500, { error: safeMessage(error) });
12240
- }
12241
- }
12359
+ method: "POST",
12360
+ ready: (res) => deps.mediaModels !== void 0 ? true : (json(res, 503, { error: "media model list unavailable" }), false)
12361
+ }, async (req, res, region) => {
12362
+ const refresh = new URL(req.url ?? "/", "http://localhost").searchParams.get("refresh") === "1";
12363
+ json(res, 200, { models: (await deps.mediaModels(region, { refresh })).map((model) => ({
12364
+ id: model.id,
12365
+ name: model.name,
12366
+ tags: [...model.tags]
12367
+ })) });
12242
12368
  });
12243
- const disposeProbe = ctx.webServer.register({
12244
- kind: "exact",
12369
+ endpointRegion({
12245
12370
  path: WORKBUDDY_PROBE_PATH,
12246
- handler: async (req, res) => {
12247
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12248
- if (!requireLoopback(req, res)) return;
12249
- if (deps.probeModels === void 0) return json(res, 503, { error: "model probe unavailable" });
12250
- const region = requestRegion(req, res);
12251
- if (region === void 0) return;
12252
- try {
12253
- const body = await readJsonBody(req);
12254
- const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12255
- if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12256
- if (modelIds.length > 1) return json(res, 400, { error: "a probe accepts exactly one model" });
12257
- const results = [];
12258
- for (const modelId of modelIds) results.push(...await deps.probeModels(region, [modelId]));
12259
- json(res, 200, { results });
12260
- } catch (error) {
12261
- json(res, 500, { error: safeMessage(error) });
12262
- }
12263
- }
12371
+ method: "POST",
12372
+ ready: (res) => deps.probeModels !== void 0 ? true : (json(res, 503, { error: "model probe unavailable" }), false)
12373
+ }, async (req, res, region) => {
12374
+ const body = await readJsonBody(req);
12375
+ const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12376
+ if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12377
+ if (modelIds.length > 1) return json(res, 400, { error: "a probe accepts exactly one model" });
12378
+ const results = [];
12379
+ for (const modelId of modelIds) results.push(...await deps.probeModels(region, [modelId]));
12380
+ json(res, 200, { results });
12264
12381
  });
12265
- const disposeTps = ctx.webServer.register({
12266
- kind: "exact",
12382
+ endpointRegion({
12267
12383
  path: WORKBUDDY_TPS_PATH,
12268
- handler: async (req, res) => {
12269
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12270
- if (!requireLoopback(req, res)) return;
12271
- if (deps.measureTps === void 0) return json(res, 503, { error: "tps measurement unavailable" });
12272
- const region = requestRegion(req, res);
12273
- if (region === void 0) return;
12274
- try {
12275
- const body = await readJsonBody(req);
12276
- const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12277
- if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12278
- if (modelIds.length > 1) return json(res, 400, { error: "a tps measurement accepts exactly one model" });
12279
- const results = [];
12280
- for (const modelId of modelIds) results.push(...await deps.measureTps(region, [modelId]));
12281
- json(res, 200, { results });
12282
- } catch (error) {
12283
- json(res, 500, { error: safeMessage(error) });
12284
- }
12285
- }
12384
+ method: "POST",
12385
+ ready: (res) => deps.measureTps !== void 0 ? true : (json(res, 503, { error: "tps measurement unavailable" }), false)
12386
+ }, async (req, res, region) => {
12387
+ const body = await readJsonBody(req);
12388
+ const modelIds = Array.isArray(body.modelIds) ? body.modelIds.filter((id) => typeof id === "string" && id !== "") : [];
12389
+ if (modelIds.length === 0) return json(res, 400, { error: "modelIds must be a non-empty array of strings" });
12390
+ if (modelIds.length > 1) return json(res, 400, { error: "a tps measurement accepts exactly one model" });
12391
+ const results = [];
12392
+ for (const modelId of modelIds) results.push(...await deps.measureTps(region, [modelId]));
12393
+ json(res, 200, { results });
12286
12394
  });
12287
- const disposePool = ctx.webServer.register({
12395
+ route({
12288
12396
  kind: "exact",
12289
12397
  path: WORKBUDDY_POOL_PATH,
12290
12398
  handler: async (req, res) => {
@@ -12427,7 +12535,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12427
12535
  }
12428
12536
  }
12429
12537
  });
12430
- const disposeDiagWrite = ctx.webServer.register({
12538
+ route({
12431
12539
  kind: "exact",
12432
12540
  path: "/plugins/dsh-connect-workbuddy/__save",
12433
12541
  handler: async (req, res) => {
@@ -12514,35 +12622,26 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12514
12622
  }
12515
12623
  }
12516
12624
  });
12517
- const disposeOAuth = ctx.webServer.register({
12518
- kind: "exact",
12625
+ endpointRegion({
12519
12626
  path: WORKBUDDY_OAUTH_PATH,
12520
- handler: async (req, res) => {
12521
- if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
12522
- if (!requireLoopback(req, res)) return;
12523
- const region = requestRegion(req, res);
12524
- if (region === void 0) return;
12525
- const action = oauthActionOf(req.url ?? "/");
12526
- if (action === void 0) return json(res, 400, { error: "action must be start or poll" });
12527
- const oauth = deps.oauth;
12528
- if (oauth === void 0) return json(res, 503, {
12529
- reason: "oauth-unavailable",
12530
- error: "OAuth sign-in is not available in this build"
12531
- });
12532
- try {
12533
- if (action === "start") {
12534
- json(res, 200, await oauth.start(region));
12535
- return;
12536
- }
12537
- const body = await readJsonBody(req);
12538
- if (typeof body.loginId !== "string" || body.loginId === "") return json(res, 400, { error: "loginId must be a non-empty string" });
12539
- json(res, 200, await oauth.poll(region, body.loginId));
12540
- } catch (error) {
12541
- json(res, 500, { error: safeMessage(error) });
12542
- }
12627
+ method: "POST"
12628
+ }, async (req, res, region) => {
12629
+ const action = oauthActionOf(req.url ?? "/");
12630
+ if (action === void 0) return json(res, 400, { error: "action must be start or poll" });
12631
+ const oauth = deps.oauth;
12632
+ if (oauth === void 0) return json(res, 503, {
12633
+ reason: "oauth-unavailable",
12634
+ error: "OAuth sign-in is not available in this build"
12635
+ });
12636
+ if (action === "start") {
12637
+ json(res, 200, await oauth.start(region));
12638
+ return;
12543
12639
  }
12640
+ const body = await readJsonBody(req);
12641
+ if (typeof body.loginId !== "string" || body.loginId === "") return json(res, 400, { error: "loginId must be a non-empty string" });
12642
+ json(res, 200, await oauth.poll(region, body.loginId));
12544
12643
  });
12545
- const disposeTransfer = ctx.webServer.register({
12644
+ route({
12546
12645
  kind: "exact",
12547
12646
  path: WORKBUDDY_TRANSFER_PATH,
12548
12647
  handler: async (req, res) => {
@@ -12597,21 +12696,14 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12597
12696
  * leave a ghost pill describing a turn that already ended. Answering an
12598
12697
  * empty document keeps "off" inside the same code path as "no turns".
12599
12698
  */
12600
- const disposeCliLive = ctx.webServer.register({
12601
- kind: "exact",
12699
+ raw({
12602
12700
  path: WORKBUDDY_CLI_LIVE_PATH,
12603
- handler: (req, res) => {
12604
- if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
12605
- if (!requireLoopback(req, res)) return;
12606
- try {
12607
- json(res, 200, deps.cliLive?.() ?? {
12608
- turns: [],
12609
- serverTime: Date.now()
12610
- });
12611
- } catch (error) {
12612
- json(res, 500, { error: safeMessage(error) });
12613
- }
12614
- }
12701
+ method: "GET"
12702
+ }, (_req, res) => {
12703
+ json(res, 200, deps.cliLive?.() ?? {
12704
+ turns: [],
12705
+ serverTime: Date.now()
12706
+ });
12615
12707
  });
12616
12708
  /**
12617
12709
  * 设备头设置:档位切换 + 每账号的虚拟参数。
@@ -12620,7 +12712,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12620
12712
  * 都是**即时生效**——这里没有草稿,因为齿轮改的是"这台机器对外声称自己是谁",
12621
12713
  * 一个需要点保存才生效的设备身份,会让"我改完到底发出去的是什么"变成猜测。
12622
12714
  */
12623
- const disposeDeviceProfile = ctx.webServer.register({
12715
+ route({
12624
12716
  kind: "exact",
12625
12717
  path: WORKBUDDY_DEVICE_PROFILE_PATH,
12626
12718
  handler: async (req, res) => {
@@ -12719,7 +12811,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12719
12811
  * 放在 POST 后面不是形式主义——它会进浏览器历史、会被 proxy 记日志、会被截图,
12720
12812
  * 而 `GET` 是三者里最容易被动触发的(预取、刷新、插件间的探测)。
12721
12813
  */
12722
- const disposeDeviceSdk = ctx.webServer.register({
12814
+ route({
12723
12815
  kind: "exact",
12724
12816
  path: WORKBUDDY_DEVICE_SDK_PATH,
12725
12817
  handler: async (req, res) => {
@@ -12780,22 +12872,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12780
12872
  }
12781
12873
  });
12782
12874
  return () => {
12783
- disposeBenefitClaim();
12784
- disposeRefresh();
12785
- disposeMediaModels();
12786
- disposeCheckin();
12787
- disposeAccounts();
12788
- disposeUsage();
12789
- disposeAccountCredits();
12790
- disposeProbe();
12791
- disposeTps();
12792
- disposePool();
12793
- disposeOAuth();
12794
- disposeTransfer();
12795
- disposeDiagWrite();
12796
- disposeCliLive();
12797
- disposeDeviceProfile();
12798
- disposeDeviceSdk();
12875
+ for (const dispose of disposers) dispose();
12799
12876
  };
12800
12877
  }, "dsh-connect-workbuddy: Web status route");
12801
12878
  }
@@ -12924,6 +13001,22 @@ const regionStateConfig = z.object({
12924
13001
  enabledModelIds: z.array(z.string()).default([]),
12925
13002
  imageModelIds: z.array(z.string()).default([]),
12926
13003
  /**
13004
+ * Which text-to-image model this region uses, as picked in the card (issue #241).
13005
+ *
13006
+ * An EMPTY string means "no choice": the tool takes the group's first model,
13007
+ * which is whatever the upstream catalog lists first (`hunyuan-image-alpha` in
13008
+ * the CN region as of 2026-11-12). Set it to `hunyuan-image-v3.0` for output
13009
+ * with no watermark.
13010
+ *
13011
+ * Why a free string and not an enum: the watermark-free model is NOT in the
13012
+ * `/v3/config` catalog — it is the official CLI's own hard-coded fallback — so
13013
+ * an enum would have to hard-code a vendor id list that can change without
13014
+ * this plugin being released. The tool validates it against the choices it can
13015
+ * actually offer (`imageModelChoices`) and falls back silently when the id is
13016
+ * stale, exactly like `preferredVideoModels`.
13017
+ */
13018
+ preferredImageModel: z.string().default("").description("Text-to-image model for this region, picked in the card. Empty = the catalog's first model. Set \"hunyuan-image-v3.0\" for watermark-free output (CN region only; ~11.1 credits/image instead of ~6, and a smaller size limit)."),
13019
+ /**
12927
13020
  * Alternative CN gateway host (issue #220); see the interface field of the
12928
13021
  * same name. Empty = the built-in gateway.
12929
13022
  *
@@ -13350,28 +13443,28 @@ function apply(ctx, config) {
13350
13443
  * 卸载,而设置随时会变,所以目录每次 `probe` 现问一次。`deviceProfiles` 读盘有
13351
13444
  * 5 秒缓存,保存会立即失效它。
13352
13445
  *
13353
- * ⚠️ **总开关优先于预热**(`deviceSdkEnabled`):关掉就不建定时器、不预取。
13354
- * 留着 `createTuringSdk()` 本身是因为端口(`createDeviceSdkPort`)仍要能回答
13355
- * "这个功能被关掉了"——它读到的是 `disabled` 状态,而不是一块空白面板。
13356
- */
13357
- /**
13358
- * 总开关:**默认关**(`default(false)`)。
13359
- *
13360
- * 与档位默认值一致:档位默认「虚拟值」本来就不发这个 token,那么默认去发现
13361
- * SDK、起子进程、每 10 分钟取一次,取到的东西一次也用不上。更一般地说,一个
13362
- * 会碰用户机器上第三方原生模块的能力,默认该由用户主动打开。
13446
+ * 总开关只留**一份活真值**。曾经这里写 `const flag = unwrapVolatile(...) === true`
13447
+ * 把布尔在 apply 期求值一次传给句柄,而 `readEnabled()` 却每次现读活引用——
13448
+ * volatile 字段就地修改、插件不重挂,于是「勾选框是开的、probe 永远答 disabled」。
13449
+ * 现在两处共用 `deviceSdkEnabled()`。句柄即使关掉也保留,因为端口仍要能回答
13450
+ * "这个功能被关掉了"(`disabled`),而不是给一块空白面板。
13363
13451
  *
13364
- * `=== true` 而不是 `!== false`:`undefined`(老配置文件里没有这个字段)必须
13365
- * 落到"关",与 `default(false)` 同一个答案。写成 `!== false` 会让"未设置"和
13366
- * "显式开启"分叉,升级后老用户静默拿到与 schema 默认相反的行为。
13452
+ * `=== true`:`undefined`(老配置没有这一项)落到"关",与 `default(false)` 一致。
13367
13453
  */
13368
- const deviceSdkEnabled = unwrapVolatile(config.deviceSdkEnabled) === true;
13454
+ const deviceSdkEnabled = () => unwrapVolatile(config.deviceSdkEnabled) === true;
13369
13455
  const turing = createTuringSdk({
13370
13456
  productVersion: APP_VERSION,
13371
13457
  dirSource: () => deviceProfiles.sdkDir(),
13372
- enabled: deviceSdkEnabled
13458
+ get enabled() {
13459
+ return deviceSdkEnabled();
13460
+ }
13373
13461
  });
13374
- if (deviceSdkEnabled) turing.startAutoRefresh();
13462
+ /** 让预热链跟随开关:开则补建(内部幂等),关则立即拆除。 */
13463
+ const syncDeviceSdk = () => {
13464
+ if (deviceSdkEnabled()) turing.startAutoRefresh();
13465
+ else turing.stopAutoRefresh();
13466
+ };
13467
+ syncDeviceSdk();
13375
13468
  ctx.effect(() => () => {
13376
13469
  turing.stopAutoRefresh();
13377
13470
  });
@@ -13525,7 +13618,10 @@ function apply(ctx, config) {
13525
13618
  reportRefusal: (report) => {
13526
13619
  recordRefusal(report);
13527
13620
  },
13528
- prepareAccount: () => applyPoolSelection(region),
13621
+ prepareAccount: async (signal) => {
13622
+ await refreshDepletedPoolCredits(region, signal);
13623
+ if (!signal?.aborted) await applyPoolSelection(region);
13624
+ },
13529
13625
  failoverAccount: (triedAccountIds) => failoverAccountFor(region, triedAccountIds),
13530
13626
  failoverShortfall: () => explainPoolShortfall(region),
13531
13627
  onAccountFailure: (accountId, failure) => {
@@ -13963,87 +14059,75 @@ function apply(ctx, config) {
13963
14059
  declared: false
13964
14060
  })));
13965
14061
  };
13966
- let imageTools;
13967
- let disposeImageTool;
13968
- const syncImageTool = (value) => {
13969
- const wanted = imageToolRegionOf(value) !== void 0;
13970
- if (wanted && disposeImageTool === void 0 && imageTools !== void 0) {
13971
- disposeImageTool = registerWorkBuddyImageTool(imageTools, {
13972
- resolveCredential: async () => {
13973
- const live = current();
13974
- for (const region of REGION_KEYS) {
13975
- if (!regionEnabled(live, region)) continue;
13976
- if (regionStateOf(live, region).imageToolEnabled !== true) continue;
13977
- try {
13978
- return await stacks[region].store.resolve();
13979
- } catch {
13980
- continue;
13981
- }
13982
- }
13983
- },
13984
- listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13985
- generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
13986
- editImage: (credential, request, signal) => client.editImage(credential, request, signal),
13987
- logger: ctx.logger
14062
+ function mountOptionalTool(options) {
14063
+ let tools;
14064
+ let dispose;
14065
+ const sync = (value) => {
14066
+ const wanted = options.wanted(value);
14067
+ if (wanted && dispose === void 0 && tools !== void 0) {
14068
+ dispose = options.register(tools);
14069
+ return;
14070
+ }
14071
+ if (!wanted && dispose !== void 0) {
14072
+ dispose();
14073
+ dispose = void 0;
14074
+ }
14075
+ };
14076
+ ctx.inject(["tools"], (toolsCtx) => {
14077
+ tools = toolsCtx.tools;
14078
+ if (tools === void 0) return;
14079
+ sync(current());
14080
+ toolsCtx.effect(() => () => {
14081
+ dispose?.();
14082
+ dispose = void 0;
14083
+ tools = void 0;
13988
14084
  });
13989
- return;
13990
- }
13991
- if (!wanted && disposeImageTool !== void 0) {
13992
- disposeImageTool();
13993
- disposeImageTool = void 0;
13994
- }
13995
- };
13996
- ctx.inject(["tools"], (toolsCtx) => {
13997
- imageTools = toolsCtx.tools;
13998
- if (imageTools === void 0) return;
13999
- syncImageTool(current());
14000
- toolsCtx.effect(() => () => {
14001
- disposeImageTool?.();
14002
- disposeImageTool = void 0;
14003
- imageTools = void 0;
14004
14085
  });
14005
- });
14006
- let videoTools;
14007
- let disposeVideoTool;
14008
- const syncVideoTool = (value) => {
14009
- const wanted = videoToolRegionOf(value) !== void 0;
14010
- if (wanted && disposeVideoTool === void 0 && videoTools !== void 0) {
14011
- disposeVideoTool = registerWorkBuddyVideoTool(videoTools, {
14012
- resolveCredential: async () => {
14013
- const live = current();
14014
- for (const region of REGION_KEYS) {
14015
- if (!regionEnabled(live, region)) continue;
14016
- if (regionStateOf(live, region).videoToolEnabled !== true) continue;
14017
- try {
14018
- return await stacks[region].store.resolve();
14019
- } catch {
14020
- continue;
14021
- }
14022
- }
14023
- },
14024
- listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
14025
- submitVideo: (credential, request, signal) => client.submitVideo(credential, request, signal),
14026
- pollVideoTask: (credential, taskId, signal) => client.pollVideoTask(credential, taskId, signal),
14027
- preferredVideoModel: (credential, tag) => regionStateOf(current(), regionOf(credential.domain)).preferredVideoModels?.[tag],
14028
- downloadVideo: (credential, url, signal) => client.downloadVideo(credential, url, signal),
14029
- logger: ctx.logger
14030
- });
14031
- return;
14032
- }
14033
- if (!wanted && disposeVideoTool !== void 0) {
14034
- disposeVideoTool();
14035
- disposeVideoTool = void 0;
14086
+ return sync;
14087
+ }
14088
+ /**
14089
+ * 每次调用现挑区、现解析凭据:用户在两次调用之间换账号或关掉某区都要生效。
14090
+ * `optIn` 必须是该工具自己的逐区开关 —— 生图不能借用视频已授权的区,否则绕过
14091
+ * 用户按区做出的授权。
14092
+ */
14093
+ const toolCredential = (optIn) => async () => {
14094
+ const live = current();
14095
+ for (const region of REGION_KEYS) {
14096
+ if (!regionEnabled(live, region)) continue;
14097
+ if (regionStateOf(live, region)[optIn] !== true) continue;
14098
+ try {
14099
+ return await stacks[region].store.resolve();
14100
+ } catch {
14101
+ continue;
14102
+ }
14036
14103
  }
14037
14104
  };
14038
- ctx.inject(["tools"], (toolsCtx) => {
14039
- videoTools = toolsCtx.tools;
14040
- if (videoTools === void 0) return;
14041
- syncVideoTool(current());
14042
- toolsCtx.effect(() => () => {
14043
- disposeVideoTool?.();
14044
- disposeVideoTool = void 0;
14045
- videoTools = void 0;
14046
- });
14105
+ const syncImageTool = mountOptionalTool({
14106
+ wanted: (value) => imageToolRegionOf(value) !== void 0,
14107
+ register: (tools) => registerWorkBuddyImageTool(tools, {
14108
+ resolveCredential: toolCredential("imageToolEnabled"),
14109
+ listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
14110
+ generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
14111
+ editImage: (credential, request, signal) => client.editImage(credential, request, signal),
14112
+ preferredImageModel: (credential, tag) => {
14113
+ if (tag !== "text-to-image") return void 0;
14114
+ const picked = regionStateOf(current(), regionOf(credential.domain)).preferredImageModel;
14115
+ return picked === void 0 || picked === "" ? void 0 : picked;
14116
+ },
14117
+ logger: ctx.logger
14118
+ })
14119
+ });
14120
+ const syncVideoTool = mountOptionalTool({
14121
+ wanted: (value) => videoToolRegionOf(value) !== void 0,
14122
+ register: (tools) => registerWorkBuddyVideoTool(tools, {
14123
+ resolveCredential: toolCredential("videoToolEnabled"),
14124
+ listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
14125
+ submitVideo: (credential, request, signal) => client.submitVideo(credential, request, signal),
14126
+ pollVideoTask: (credential, taskId, signal) => client.pollVideoTask(credential, taskId, signal),
14127
+ preferredVideoModel: (credential, tag) => regionStateOf(current(), regionOf(credential.domain)).preferredVideoModels?.[tag],
14128
+ downloadVideo: (credential, url, signal) => client.downloadVideo(credential, url, signal),
14129
+ logger: ctx.logger
14130
+ })
14047
14131
  });
14048
14132
  let cliTools;
14049
14133
  let cliCommands;
@@ -14233,14 +14317,11 @@ function apply(ctx, config) {
14233
14317
  sdk: turing,
14234
14318
  mode: async () => (await readDeviceSettings()).mode,
14235
14319
  /**
14236
- * 总开关走插件配置(`Config.deviceSdkEnabled`),不走设备设置文件。
14237
- *
14238
- * `read` 取的是 `current()`——也就是宿主交给 `apply()` 的那份活的引用,
14239
- * 所以 `ctx.settings.update` 写完它就能读到新值(`asVolatile` 会就地改)。
14240
- * 回 `undefined` 让卡片把开关标成不可用,而不是把它画成"关"。
14320
+ * 总开关走插件配置(`Config.deviceSdkEnabled`),与 SDK 句柄的 `enabled`
14321
+ * getter 共用同一个 `deviceSdkEnabled()`,因此勾选框与 probe 不会分叉。
14241
14322
  */
14242
14323
  enabled: {
14243
- read: async () => unwrapVolatile(config.deviceSdkEnabled) !== false,
14324
+ read: async () => deviceSdkEnabled(),
14244
14325
  write: writeDeviceSdkEnabled
14245
14326
  }
14246
14327
  }),
@@ -14322,6 +14403,13 @@ function apply(ctx, config) {
14322
14403
  */
14323
14404
  preferredVideoModels: (region) => regionStateOf(current(), region).preferredVideoModels ?? {},
14324
14405
  /**
14406
+ * The text-to-image model chosen per region, for the card's picker (issue
14407
+ * #241). Read from the committed value like the switches above, so the
14408
+ * picker shows what the TOOL will actually use rather than the browser's
14409
+ * stale mirror of this namespace.
14410
+ */
14411
+ preferredImageModel: (region) => regionStateOf(current(), region).preferredImageModel ?? "",
14412
+ /**
14325
14413
  * Whether the optional CodeBuddy CLI route is mounted (`codebuddy_ask` tool
14326
14414
  * + `/codebuddy` command).
14327
14415
  *
@@ -14383,11 +14471,11 @@ function apply(ctx, config) {
14383
14471
  * token: the route passes only model ids and receives only outcomes.
14384
14472
  *
14385
14473
  * `quotaRefreshAtMs` is the region's nearest monthly refresh point, read from
14386
- * the SAME credit answer the card displays. It is the only cooldown this
14387
- * service ever states — an exhausted monthly resource that resets at a known
14388
- * time — so it is what makes "when can I use this again" answerable for an
14389
- * out-of-credit result. Every other limited outcome has no time anywhere, and
14390
- * the probe reports exactly that instead of inventing one.
14474
+ * the SAME credit answer the card displays. It is recorded beside an
14475
+ * out-of-credit result as upstream EVIDENCE, not as a recovery deadline:
14476
+ * check-in and top-ups can replenish credits long before it, so the views
14477
+ * name the replenishment action instead of rendering a countdown, and the
14478
+ * pool does not release the account when the moment passes.
14391
14479
  */
14392
14480
  async probeModels(region, modelIds, options) {
14393
14481
  let credential;
@@ -14545,17 +14633,18 @@ function apply(ctx, config) {
14545
14633
  * failure is simply omitted, which the card renders as unknown.
14546
14634
  */
14547
14635
  async checkedInToday(region) {
14548
- if (!poolPreferencesOf(current(), region).enabled) return {};
14636
+ if (region !== "cn" || !poolPreferencesOf(current(), region).enabled) return {};
14549
14637
  const store = stacks[region].store;
14550
14638
  const accounts = await store.accounts();
14551
14639
  const now = Date.now();
14552
14640
  const entries = await Promise.all(accounts.map(async (account) => {
14641
+ if (account.enterprise === true) return void 0;
14553
14642
  const cached = checkinStateCache[region]?.[account.id];
14554
14643
  if (cached !== void 0 && checkinReadingFresh(cached.atMs, now, CHECKIN_CACHE_MS)) return [account.id, cached.checkedIn];
14555
14644
  const credential = await store.credentialFor(account.id).catch(() => void 0);
14556
14645
  if (credential === void 0) return void 0;
14557
14646
  const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
14558
- if (status === void 0) return void 0;
14647
+ if (status === void 0 || !status.active) return void 0;
14559
14648
  checkinStateCache[region] = {
14560
14649
  ...checkinStateCache[region],
14561
14650
  [account.id]: {
@@ -14691,6 +14780,10 @@ function apply(ctx, config) {
14691
14780
  const cached = checkinStateCache[region];
14692
14781
  if (cached !== void 0) delete cached[row.accountId];
14693
14782
  }
14783
+ if (rows.some((row) => row.status !== "failed")) {
14784
+ await poolMembersOf(region);
14785
+ await applyPoolSelection(region);
14786
+ }
14694
14787
  return rows;
14695
14788
  },
14696
14789
  test: async (region, modelId, onRow) => {
@@ -14860,10 +14953,11 @@ function apply(ctx, config) {
14860
14953
  * The region's nearest monthly quota refresh, or undefined when unknown.
14861
14954
  *
14862
14955
  * The monthly resource (`CapacityType 4`) is the one package that never
14863
- * expires and resets on a cycle, so its `refreshAtMs` is a real answer to
14864
- * "when can I use this again" after the quota runs out. The probe passes it
14865
- * through; a failure to read it is not an error, because a probe without a
14866
- * cooldown is still a useful probe.
14956
+ * expires and resets on a cycle, so its `refreshAtMs` is the package's own
14957
+ * schedule. It is handed to a probe as EVIDENCE to store beside an
14958
+ * out-of-credit outcome — never as the moment the account becomes usable
14959
+ * again, because check-in and top-ups can land first. A failure to read it is
14960
+ * not an error: a probe that records no refresh point is still a useful probe.
14867
14961
  */
14868
14962
  const quotaRefreshOf = async (region, credential) => {
14869
14963
  try {
@@ -14968,11 +15062,10 @@ function apply(ctx, config) {
14968
15062
  * without fetching one.
14969
15063
  *
14970
15064
  * Credits are the ranking's second key, and they cost an upstream call per
14971
- * member. A chat request must never pay that: it happens on the hot path, and
14972
- * `fetchCredits` per member would turn one page of conversation into N extra
14973
- * requests. So the request path uses whatever the pool last read (the card's
14974
- * 60-second poll, a batch test, or a save) and simply skips the key when the
14975
- * snapshot is too old to speak for today's balances.
15065
+ * member. Normal ranking reuses the last UI/check-in snapshot and omits stale
15066
+ * balances rather than fetching all members for each chat. The separate,
15067
+ * rate-limited recovery check reads only accounts with recorded credit
15068
+ * failures; it does not refresh this whole-pool ranking snapshot.
14976
15069
  */
14977
15070
  const creditsSnapshot = {};
14978
15071
  /** How long a credits reading may steer routing. */
@@ -14984,9 +15077,9 @@ function apply(ctx, config) {
14984
15077
  * the probe store, plus the credits snapshot when it is fresh.
14985
15078
  *
14986
15079
  * The request path calls this on every chat completion, so it must not touch
14987
- * the network. `poolMembersOf` is the honest-but-expensive version (it fetches
14988
- * credits per member) and stays on the card's route, which is where those
14989
- * readings come from in the first place.
15080
+ * the network. `poolMembersOf` refreshes all members on explicit UI/check-in
15081
+ * paths. Before a request, `refreshDepletedPoolCredits` separately checks only
15082
+ * recorded credit failures, at most once per minute, even with no card open.
14990
15083
  */
14991
15084
  async function localPoolMembers(region) {
14992
15085
  const accounts = await poolMemberAccounts(region);
@@ -15007,6 +15100,64 @@ function apply(ctx, config) {
15007
15100
  });
15008
15101
  }
15009
15102
  /**
15103
+ * Recover depleted members without blocking requests that already have a usable
15104
+ * account. Concurrent callers share one balance read per region and minute.
15105
+ * When every member is excluded, a caller may wait for recovery; disconnecting
15106
+ * releases that caller without cancelling evidence needed by other requests.
15107
+ * Positive readings update existing ranking balances without extending the
15108
+ * lifetime of unrelated cached readings or overwriting a newer UI snapshot.
15109
+ */
15110
+ const depletedRefreshAt = {};
15111
+ const depletedRefreshInFlight = {};
15112
+ async function refreshDepletedPoolCredits(region, signal) {
15113
+ if (!poolPreferencesOf(current(), region).enabled || signal?.aborted) return;
15114
+ const members = await localPoolMembers(region);
15115
+ if (signal?.aborted) return;
15116
+ let task = depletedRefreshInFlight[region];
15117
+ if (task === void 0 && Date.now() >= (depletedRefreshAt[region] ?? 0)) {
15118
+ const depleted = members.filter((member) => member.probe?.outcome === "out-of-credit");
15119
+ if (depleted.length === 0) return;
15120
+ depletedRefreshAt[region] = Date.now() + 6e4;
15121
+ task = (async () => {
15122
+ const completed = (await Promise.all(depleted.map(async (member) => {
15123
+ const credential = await stacks[region].store.credentialFor(member.account.id).catch(() => void 0);
15124
+ if (credential === void 0) return void 0;
15125
+ const startedAtMs = Date.now();
15126
+ const credits = await client.fetchCredits(credential).catch(() => void 0);
15127
+ return credits === void 0 ? void 0 : {
15128
+ accountId: member.account.id,
15129
+ startedAtMs,
15130
+ total: credits.total,
15131
+ credits
15132
+ };
15133
+ }))).filter((reading) => reading !== void 0);
15134
+ await reconcilePoolCredits(region, completed);
15135
+ const snapshot = creditsSnapshot[region];
15136
+ if (snapshot !== void 0) {
15137
+ const updated = new Map(snapshot);
15138
+ for (const reading of completed) if ((creditsSnapshotAt[region] ?? 0) <= reading.startedAtMs) updated.set(reading.accountId, reading.credits);
15139
+ creditsSnapshot[region] = updated;
15140
+ }
15141
+ })().catch((error) => {
15142
+ ctx.logger.warn("dsh-connect-workbuddy: pool credit recovery failed", error);
15143
+ }).finally(() => {
15144
+ delete depletedRefreshInFlight[region];
15145
+ });
15146
+ depletedRefreshInFlight[region] = task;
15147
+ }
15148
+ if (task === void 0 || members.some((member) => exclusionOf(member.probe, Date.now()) === void 0)) return;
15149
+ if (signal === void 0) return task;
15150
+ await new Promise((resolve) => {
15151
+ const finish = () => {
15152
+ signal.removeEventListener("abort", finish);
15153
+ resolve();
15154
+ };
15155
+ signal.addEventListener("abort", finish, { once: true });
15156
+ if (signal.aborted) finish();
15157
+ task.then(finish, finish);
15158
+ });
15159
+ }
15160
+ /**
15010
15161
  * Record a failure a LIVE request hit, so the NEXT request starts from a
15011
15162
  * usable account.
15012
15163
  *
@@ -15023,23 +15174,13 @@ function apply(ctx, config) {
15023
15174
  * sideline a good account over a bad body.
15024
15175
  *
15025
15176
  * The reset time comes from the upstream's own words — the 429 body carries
15026
- * 「将在 … 重置」 — which `cooldownOf` parses. When it states no time, the store's
15027
- * own short window applies rather than a guess at a long one.
15028
- *
15029
- * THE QUOTA REFRESH POINT IS PASSED IN, and it is not decoration. This path
15030
- * used to omit `quotaRefreshAtMs` while the PROBE path supplied it, so one
15031
- * `out-of-credit` failure got two different answers depending on which door it
15032
- * arrived through: the probe said "the quota refreshes on the 1st" (a time the
15033
- * billing side states outright) while a live chat failure said "30 minutes
15034
- * from now" — a window the account cannot possibly clear, so the pool put it
15035
- * back and paid another refused round trip. Worse, the write below combines
15036
- * with the stored record, and the stored refresh point was being LOST in the
15037
- * process (see {@link mergePoolProbe}).
15038
- *
15039
- * Reading it costs one `fetchCredits`, affordable here but not on every
15040
- * failure: it runs only for `out-of-credit`, where the refresh point is the one
15041
- * honest answer and there is no cheaper source. Failing to read it is not an
15042
- * error — the fallback still applies.
15177
+ * 「将在 … 重置」 — which `cooldownOf` parses. Transient failures with no stated
15178
+ * time use the local short window; credit exhaustion requires balance evidence.
15179
+ *
15180
+ * The monthly package refresh is retained as upstream evidence, not as the
15181
+ * earliest recovery date: check-in and purchases can replenish credits sooner.
15182
+ * A later positive balance reading clears an older credit failure under the
15183
+ * store lock, without overwriting failures recorded during the query.
15043
15184
  *
15044
15185
  * The upstream's text is persisted alongside the outcome so the card can name
15045
15186
  * the reason. It is REDACTED first because this message is a raw upstream body:
@@ -15132,10 +15273,17 @@ function apply(ctx, config) {
15132
15273
  async function poolMembersOf(region) {
15133
15274
  const store = stacks[region].store;
15134
15275
  const accounts = await poolMemberAccounts(region);
15135
- const probes = await readPoolProbes(region);
15276
+ const recordedProbes = await readPoolProbes(region);
15277
+ const creditReadings = [];
15136
15278
  const rows = await Promise.all(accounts.map(async (account) => {
15137
15279
  const credential = await store.credentialFor(account.id).catch(() => void 0);
15280
+ const startedAtMs = Date.now();
15138
15281
  const credits = credential === void 0 ? void 0 : await client.fetchCredits(credential).catch(() => void 0);
15282
+ if (credits !== void 0) creditReadings.push({
15283
+ accountId: account.id,
15284
+ startedAtMs,
15285
+ total: credits.total
15286
+ });
15139
15287
  return {
15140
15288
  account: {
15141
15289
  id: account.id,
@@ -15147,13 +15295,16 @@ function apply(ctx, config) {
15147
15295
  expiringSoon: credits.expiringSoon,
15148
15296
  ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
15149
15297
  } },
15150
- ...probes[account.id] === void 0 ? {} : { probe: probes[account.id] },
15151
15298
  tokenExpiresAtMs: account.tokenExpiresAtMs
15152
15299
  };
15153
15300
  }));
15301
+ const probes = creditReadings.some((reading) => recordedProbes[reading.accountId]?.outcome === "out-of-credit") ? await reconcilePoolCredits(region, creditReadings) : recordedProbes;
15154
15302
  creditsSnapshot[region] = new Map(rows.filter((row) => row.credits !== void 0).map((row) => [row.account.id, row.credits]));
15155
15303
  creditsSnapshotAt[region] = Date.now();
15156
- return rows;
15304
+ return rows.map((row) => ({
15305
+ ...row,
15306
+ ...probes[row.account.id] === void 0 ? {} : { probe: probes[row.account.id] }
15307
+ }));
15157
15308
  }
15158
15309
  /**
15159
15310
  * The model a per-row test would use right now: the SAME resolution the
@@ -15323,6 +15474,10 @@ function apply(ctx, config) {
15323
15474
  const cached = checkinStateCache[region];
15324
15475
  if (cached !== void 0) delete cached[row.accountId];
15325
15476
  }
15477
+ if (rows.some((row) => row.status !== "failed")) {
15478
+ await poolMembersOf(region);
15479
+ await applyPoolSelection(region);
15480
+ }
15326
15481
  const folded = foldAttempt(state, rows, nowMs, targets.length + state.doneAccountIds.length);
15327
15482
  autoCheckinState[region] = folded;
15328
15483
  await writeAutoCheckinState(region, folded);
@@ -15412,6 +15567,7 @@ function apply(ctx, config) {
15412
15567
  ctx.on("loader/volatile-update", () => {
15413
15568
  applySelection(current());
15414
15569
  syncAutoCheckin();
15570
+ syncDeviceSdk();
15415
15571
  });
15416
15572
  applySelection(config);
15417
15573
  (async () => {