dsh-connect-workbuddy 5.21.4 → 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-Dq3ITRhF.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";
@@ -619,6 +619,7 @@ const REGION_MAP_FOREIGN_KEYS = /* @__PURE__ */ new Set([
619
619
  "enabledModelIds",
620
620
  "imageModelIds",
621
621
  "imageToolEnabled",
622
+ "preferredImageModel",
622
623
  "offModelIds",
623
624
  "contextBudgets",
624
625
  "defaultThinkingEfforts",
@@ -669,6 +670,7 @@ function slotConfigWeight(slot) {
669
670
  if (slot["enabled"] === false) weight += 1;
670
671
  if (slot["showCreditsInMainUi"] === false) weight += 1;
671
672
  if (slot["imageToolEnabled"] === true) weight += 1;
673
+ if (typeof slot["preferredImageModel"] === "string" && slot["preferredImageModel"] !== "") weight += 1;
672
674
  return weight;
673
675
  }
674
676
  /**
@@ -1478,8 +1480,12 @@ function workBuddyThinkingLevelMap(info) {
1478
1480
  * stamped field is what pi-ai resolves the provider BY (issue #75) — so every
1479
1481
  * key in {@link modelIdentityKeysOf} must be a key this route registers.
1480
1482
  */
1481
- function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1483
+ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY, midConvoSystemMessages = false) {
1482
1484
  const thinkingLevelMap = workBuddyThinkingLevelMap(info);
1485
+ const compat = midConvoSystemMessages ? {
1486
+ supportsReasoningEffort: thinkingLevelMap !== void 0,
1487
+ supportsMidConvoSystemMessages: true
1488
+ } : { supportsReasoningEffort: thinkingLevelMap !== void 0 };
1483
1489
  return {
1484
1490
  id: info.id,
1485
1491
  name: workBuddyDisplayName(info),
@@ -1492,7 +1498,7 @@ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1492
1498
  maxTokens: info.maxTokens,
1493
1499
  reasoning: thinkingLevelMap !== void 0,
1494
1500
  ...thinkingLevelMap === void 0 ? {} : { thinkingLevelMap },
1495
- compat: { supportsReasoningEffort: thinkingLevelMap !== void 0 }
1501
+ compat
1496
1502
  };
1497
1503
  }
1498
1504
  /**
@@ -2322,7 +2328,8 @@ function createWorkBuddyAdapter(options) {
2322
2328
  const generation = options.piAiGeneration ?? piAiRuntimeInfo().generation;
2323
2329
  const buildModels = () => {
2324
2330
  const baseUrl = `${shim.baseUrl()}/v1`;
2325
- 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));
2326
2333
  };
2327
2334
  const provider = {
2328
2335
  ...createProvider({
@@ -2960,7 +2967,8 @@ function installChannelContinue(mount) {
2960
2967
  * vendor, uniformly — 790 replay records in one real session held that value
2961
2968
  * and no other). Non-survivors are text by the time `:964–971` collects
2962
2969
  * `assistantText`, so they land in `assistantMsg.content` instead. This plugin
2963
- * 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
2964
2972
  * leaves `requiresThinkingAsText` at its `false` default (`:1270`), so the raw
2965
2973
  * field route is the live one rather than the fold-into-content route at `:983`.
2966
2974
  *
@@ -5863,9 +5871,12 @@ function createWorkBuddyShim(options) {
5863
5871
  writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
5864
5872
  return;
5865
5873
  }
5866
- await prepareAccount?.().catch((error) => {
5874
+ const controller = new AbortController();
5875
+ res.on("close", () => controller.abort());
5876
+ await prepareAccount?.(controller.signal).catch((error) => {
5867
5877
  logger?.warn("dsh-connect-workbuddy: pool account selection failed", error);
5868
5878
  });
5879
+ if (controller.signal.aborted) return;
5869
5880
  let credential;
5870
5881
  try {
5871
5882
  credential = await store.resolve();
@@ -5884,8 +5895,6 @@ function createWorkBuddyShim(options) {
5884
5895
  } catch (error) {
5885
5896
  logger?.warn("dsh-connect-workbuddy: body report failed", error);
5886
5897
  }
5887
- const controller = new AbortController();
5888
- res.on("close", () => controller.abort());
5889
5898
  const preferred = channelPerturbation === "always" || channelNeedsPerturbation ? perturbChannelFingerprints(prepared, channelPerturbation === "always") ?? prepared : prepared;
5890
5899
  let result = await client.chatStream(credential, preferred, controller.signal);
5891
5900
  if (channelNeedsPerturbation && !result.ok && result.kind === "channel_reject") {
@@ -6183,6 +6192,30 @@ const IMAGE_TOOL_TIMEOUT_MS = 18e4;
6183
6192
  const IMAGE_INPUT_TIMEOUT_MS = 3e4;
6184
6193
  /** 失败后的冷却:生图按张扣积分,连续重试会在几秒内烧掉几十积分。 */
6185
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
+ }
6186
6219
  function asRecord$1(value) {
6187
6220
  return typeof value === "object" && value !== null ? value : {};
6188
6221
  }
@@ -6237,11 +6270,9 @@ function strictString$1(value, name) {
6237
6270
  }
6238
6271
  /** 「宽x高」——允许 `x` / `X` / 全角 `×`;不接受 `*`、空格、带单位。 */
6239
6272
  const SIZE_PATTERN = /^[0-9]+[xX×][0-9]+$/;
6240
- /** 上游实测上限:总像素约 419 万(见 docs/IMAGE_GEN.md「尺寸与比例」)。 */
6241
- const MAX_IMAGE_PIXELS = 4194304;
6242
- /** 边长支持范围。上限 2560 来自实测通过的最大长边(2560x1440 / 2560x1600)。 */
6243
- const MIN_IMAGE_EDGE = 512;
6244
- const MAX_IMAGE_EDGE = 2560;
6273
+ IMAGE_SIZE_LIMITS_WIDE.maxPixels;
6274
+ IMAGE_SIZE_LIMITS_WIDE.minEdge;
6275
+ IMAGE_SIZE_LIMITS_WIDE.maxEdge;
6245
6276
  /** 实测被上游拒绝的尺寸,报错时直接点出来,省得模型反复试。 */
6246
6277
  const KNOWN_BAD_SIZES = /* @__PURE__ */ new Set([
6247
6278
  "2560x2560",
@@ -6302,37 +6333,71 @@ function parseSizeSpec(value) {
6302
6333
  * 把解析好的尺寸规格落成一个真正要发给上游的值。
6303
6334
  *
6304
6335
  * 与 {@link parseSizeSpec} 分开,是因为这两件事的**时机**不同:格式错误要在收到
6305
- * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高。
6336
+ * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高、
6337
+ * 也要等**模型定下来**——两个模型的合法范围不一样(见 `imageSizeLimitsOf`)。
6306
6338
  *
6307
6339
  * 越界为什么由工具收、而不是让模型自己算:两条边(512–2560)与总像素
6308
6340
  * (≤4,194,304)是两个约束,手算要取「2560/长边」与「√(4194304/面积)」里更小的
6309
6341
  * 那个**再复查一遍**。要求模型在参数里做这种算术,实测会算出仍然越界的值
6310
6342
  * (2480x3508 → 1810x2560,边长合规但乘积 4,633,600 仍超)。收完之后把「动过什么」
6311
6343
  * 写进 hint,模型得据实转告用户,不能假装按用户给的尺寸出图。
6344
+ *
6345
+ * `limits` 来自**这一次选中的模型**,不是全局常量:v3.0 的边更短、像素更少,
6346
+ * 用 alpha 的范围替它算会得到上游 400(实测 `1024x1025` 就被拒)。
6347
+ */
6348
+ /**
6349
+ * `size: auto` 但量不出输入图 —— 这一步**不需要模型**,所以单独提出来。
6350
+ *
6351
+ * 报错时机是这里唯一的理由:模型的失败(目录里没这条模型)要花一次目录请求
6352
+ * 才能知道,而「你写了 auto 却没给图」在本地就能判。把它压到模型解析之后,
6353
+ * 一个纯参数错误就会被「目录里没有模型」盖掉,用户改完一处还得再撞第二处。
6312
6354
  */
6313
- function planImageSize(spec, input) {
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) {
6314
6363
  if (spec.kind === "auto") {
6315
- if (input === void 0) throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6316
- const canvas = canvasForInput(input);
6364
+ const source = requireAutoInput(input);
6365
+ const canvas = canvasForInput(source, limits);
6317
6366
  const size = `${canvas.width}x${canvas.height}`;
6318
6367
  return {
6319
6368
  size,
6320
6369
  requested: "auto",
6321
- 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},比例有变化`
6322
6371
  };
6323
6372
  }
6324
6373
  const { width, height, normalized } = spec;
6325
- if (isSizeInRange(width, height, normalized)) return { size: `${width}x${height}` };
6326
- const fitted = fitIntoRange(width, height);
6327
- 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) + "。");
6328
6377
  const direction = fitted.direction === "up" ? "放大" : "缩小";
6329
6378
  return {
6330
6379
  size: `${fitted.width}x${fitted.height}`,
6331
6380
  requested: normalized,
6332
- 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}`
6333
6382
  };
6334
6383
  }
6335
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
+ /**
6336
6401
  * 这些失败说明请求真的打到了上游、可能已经扣了积分,才值得进冷却。
6337
6402
  * 参数写错 / 未登录 / 目录里没有模型都还没花钱。
6338
6403
  */
@@ -6496,7 +6561,7 @@ function firstDimensions(inputs) {
6496
6561
  * 极端比例(比 5:1 还细长)等比缩放放不进范围时,退回按方向的常用档——宁可换
6497
6562
  * 比例,也不能报错让用户无从下手;`exact: false` 就是用来把这句实话写进 hint 的。
6498
6563
  */
6499
- function canvasForInput(input) {
6564
+ function canvasForInput(input, limits) {
6500
6565
  const orientation = orientationOf(input);
6501
6566
  if (orientation === "square") return {
6502
6567
  ...DEFAULT_SIZE_BY_ORIENTATION.square,
@@ -6507,12 +6572,12 @@ function canvasForInput(input) {
6507
6572
  const short = Math.max(1, Math.round(shortest * AUTO_LONG_EDGE / longest));
6508
6573
  const width = orientation === "landscape" ? AUTO_LONG_EDGE : short;
6509
6574
  const height = orientation === "landscape" ? short : AUTO_LONG_EDGE;
6510
- if (isSizeInRange(width, height, `${width}x${height}`)) return {
6575
+ if (isSizeInRange(width, height, `${width}x${height}`, limits)) return {
6511
6576
  width,
6512
6577
  height,
6513
6578
  exact: true
6514
6579
  };
6515
- const fitted = fitIntoRange(width, height);
6580
+ const fitted = fitIntoRange(width, height, limits);
6516
6581
  if (fitted !== void 0) return {
6517
6582
  width: fitted.width,
6518
6583
  height: fitted.height,
@@ -6524,11 +6589,11 @@ function canvasForInput(input) {
6524
6589
  };
6525
6590
  }
6526
6591
  /** 两个上限(长边 2560、总像素 419 万)同时满足时,把宽高按比例收进范围。 */
6527
- function shrinkProduct(width, height) {
6592
+ function shrinkProduct(width, height, limits) {
6528
6593
  let w = width;
6529
6594
  let h = height;
6530
- for (let round = 0; round < 4 && w * h > MAX_IMAGE_PIXELS; round += 1) {
6531
- 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));
6532
6597
  w = Math.floor(w * scale);
6533
6598
  h = Math.floor(h * scale);
6534
6599
  }
@@ -6547,38 +6612,45 @@ function shrinkProduct(width, height) {
6547
6612
  * 返回 undefined 表示等比缩放解不出来(比例比 5:1 还极端:缩到长边 2560 时短边
6548
6613
  * 已经小于 512,抬到 512 时长边又超过 2560),交给调用方按方向换档。
6549
6614
  */
6550
- function fitIntoRange(width, height) {
6615
+ function fitIntoRange(width, height, limits) {
6616
+ const { minEdge, maxEdge, maxPixels } = limits;
6551
6617
  const longest = Math.max(width, height);
6552
6618
  const shortest = Math.min(width, height);
6553
- if (!(longest > MAX_IMAGE_EDGE || width * height > MAX_IMAGE_PIXELS) && shortest < MIN_IMAGE_EDGE) {
6554
- const scale = MIN_IMAGE_EDGE / shortest;
6555
- if (longest * scale <= MAX_IMAGE_EDGE) return {
6556
- ...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),
6557
6623
  direction: "up"
6558
6624
  };
6559
6625
  return;
6560
6626
  }
6561
- const scale = Math.min(MAX_IMAGE_EDGE / longest, Math.sqrt(MAX_IMAGE_PIXELS / (width * height)));
6562
- const scaled = shrinkProduct(Math.floor(width * scale), Math.floor(height * scale));
6563
- 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 {
6564
6630
  ...scaled,
6565
6631
  direction: "down"
6566
6632
  };
6567
- const extreme = MIN_IMAGE_EDGE / shortest;
6568
- if (longest * extreme <= MAX_IMAGE_EDGE) {
6569
- const lifted = shrinkProduct(Math.round(width * extreme), Math.round(height * extreme));
6570
- 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 {
6571
6637
  ...lifted,
6572
6638
  direction: "up"
6573
6639
  };
6574
6640
  }
6575
6641
  }
6576
- /** 一个尺寸是否直接可用:两条边在 512–2560,且宽乘高不超过 419 万。 */
6577
- 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) {
6578
6650
  if (KNOWN_BAD_SIZES.has(normalized)) return false;
6579
- if (width < MIN_IMAGE_EDGE || height < MIN_IMAGE_EDGE) return false;
6580
- if (width > MAX_IMAGE_EDGE || height > MAX_IMAGE_EDGE) return false;
6581
- 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;
6582
6654
  }
6583
6655
  /**
6584
6656
  * 体积与空文件闸门——四种输入形态都从这里过,所以「空文件」和「超过 8 MB」的
@@ -6667,7 +6739,7 @@ function createImageTool(deps) {
6667
6739
  };
6668
6740
  return {
6669
6741
  name: WORKBUDDY_IMAGE_TOOL_NAME,
6670
- 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 时引用它并提醒尽快转存——本工具不负责下载或转存,要长期保存得用户自己点开链接另存。",
6671
6743
  parameters: {
6672
6744
  type: "object",
6673
6745
  properties: {
@@ -6793,11 +6865,13 @@ function createImageTool(deps) {
6793
6865
  try {
6794
6866
  const models = await listModels(credential, signal);
6795
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";
6796
6869
  const inputSize = resolved === void 0 ? void 0 : firstDimensions(resolved);
6797
- const plan = planImageSize(sizeSpec, inputSize);
6798
- const size = plan.size;
6870
+ if (sizeSpec.kind === "auto" && inputSize === void 0) missingAutoSizeInput();
6799
6871
  const inputs = resolved?.map((input) => input.dataUrl);
6800
- 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;
6801
6875
  sent = true;
6802
6876
  const outcome = inputs === void 0 ? await deps.generateImage(credential, {
6803
6877
  model: model.id,
@@ -6810,17 +6884,17 @@ function createImageTool(deps) {
6810
6884
  image: inputs
6811
6885
  }, signal);
6812
6886
  const mode = inputs === void 0 ? "generate" : "edit";
6813
- const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6814
6887
  const regionLabel = region === "global" ? "国际版" : "国内版";
6815
6888
  const dimensionNote = plan.note === void 0 ? "" : `${plan.note}。`;
6816
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(更贵、尺寸上限更小)。";
6817
6891
  const value = {
6818
6892
  mode,
6819
6893
  region,
6820
6894
  size,
6821
6895
  model: model.id,
6822
6896
  prompt,
6823
- 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 小时失效;要长期保留请及时下载。"
6824
6898
  };
6825
6899
  if (plan.requested !== void 0 && plan.requested !== size) value["requestedSize"] = plan.requested;
6826
6900
  if (outcome.url !== void 0) value["url"] = outcome.url;
@@ -9511,7 +9585,8 @@ function parseUpstreamResetAt(message) {
9511
9585
  return utcMs - offsetTotalMinutes * 6e4;
9512
9586
  }
9513
9587
  /**
9514
- * 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.
9515
9590
  *
9516
9591
  * Three sources, in order of authority:
9517
9592
  *
@@ -9522,13 +9597,13 @@ function parseUpstreamResetAt(message) {
9522
9597
  * this service: a 429 from the Chinese gateway carries code 6004 and a
9523
9598
  * `将在 … 重置` sentence, with no `Retry-After` header at all.
9524
9599
  * 3. The region's monthly quota refresh point, but ONLY for an out-of-credit
9525
- * outcome. A quota that resets at a known time is the one case where "when
9526
- * can I use this again" has a real answer even without a header — and it is
9527
- * 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.
9528
9603
  *
9529
- * A limited outcome with none of the three returns `{}`, which the card renders
9530
- * as "the upstream did not say when". That remains the honest answer for a
9531
- * 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.
9532
9607
  *
9533
9608
  * An `ok` outcome ALWAYS returns `{}`, whatever headers or body came with it.
9534
9609
  * A successful probe has already answered "can this account serve right now?"
@@ -10157,7 +10232,7 @@ function exclusionOf(probe, nowMs) {
10157
10232
  case "failed": return retryDue(probe, nowMs) ? void 0 : "failed";
10158
10233
  case "rate-limited": return retryDue(probe, nowMs) ? void 0 : "rate-limited";
10159
10234
  case "model-busy": return retryDue(probe, nowMs, 12e4) ? void 0 : "model-busy";
10160
- case "out-of-credit": return retryDue(probe, nowMs) ? void 0 : "out-of-credit";
10235
+ case "out-of-credit": return "out-of-credit";
10161
10236
  case "policy-rejected": return;
10162
10237
  case "channel-rejected": return;
10163
10238
  default: return "unusable";
@@ -10166,11 +10241,10 @@ function exclusionOf(probe, nowMs) {
10166
10241
  /**
10167
10242
  * Whether an account's cooldown has elapsed (or was never stated).
10168
10243
  *
10169
- * The fallback is the ONLY thing a transient outcome relies on: `cooldownOf`
10170
- * attaches `retryAtMs` for a rate limit or a drained quota, never for a
10171
- * transport failure, so `atMs + POOL_UNKNOWN_COOLDOWN_MS` is what brings those
10172
- * back. That is deliberate — the alternative is a permanent exclusion decided by
10173
- * 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.
10174
10248
  *
10175
10249
  * `fallbackMs` lets one outcome carry a SHORTER clock than the generic one: the
10176
10250
  * model-scoped throttle is upstream's own "about a minute", and applying the
@@ -10181,6 +10255,30 @@ function retryDue(probe, nowMs, fallbackMs = POOL_UNKNOWN_COOLDOWN_MS) {
10181
10255
  return nowMs >= (probe.retryAtMs ?? probe.atMs + fallbackMs);
10182
10256
  }
10183
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
+ /**
10184
10282
  * Rank a pool's members best-first.
10185
10283
  *
10186
10284
  * The rule, in priority order — this is the whole feature:
@@ -10251,11 +10349,13 @@ function rankPool(members, nowMs, orderAccountIds) {
10251
10349
  _atRisk: (member.credits?.expiringSoon ?? 0) > 0,
10252
10350
  _expiringAmount: member.credits?.expiringSoon ?? 0,
10253
10351
  _expiring: member.credits?.nearestExpiryMs ?? Number.POSITIVE_INFINITY,
10254
- _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0
10352
+ _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0,
10353
+ _recoversAt: excludedBy === void 0 ? Number.POSITIVE_INFINITY : recoversAtOf(member.probe, excludedBy)
10255
10354
  };
10256
10355
  });
10257
10356
  rows.sort((left, right) => {
10258
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;
10259
10359
  if (left._atRisk !== right._atRisk) return left._atRisk ? -1 : 1;
10260
10360
  if (left._order !== right._order) return left._order - right._order;
10261
10361
  if (left._atRisk && right._atRisk && left._expiring !== right._expiring) return left._expiring - right._expiring;
@@ -11036,18 +11136,24 @@ function knownProbeSource(value) {
11036
11136
  * The two writers describe the same account at different moments and carry
11037
11137
  * different fields:
11038
11138
  *
11039
- * - `test-batch` measures the TARGET MODEL deliberately, so it is the only
11040
- * writer that can produce a refresh point (`retryAtMs` with
11041
- * `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.
11042
11143
  * - `live-request` reports what a real chat request just hit. It often carries
11043
11144
  * no `retryAtMs` at all (a transport blip names no time), and a spread would
11044
- * therefore DELETE the refresh point the probe had already resolved.
11145
+ * therefore DELETE that recorded point.
11045
11146
  *
11046
11147
  * Measured consequence of the spread, on a real `14018` account: the probe
11047
11148
  * recorded "quota refreshes 2026-11-01", the next live failure rewrote the
11048
- * record without that field, and the pool then reported "retry in about 30
11049
- * minutes" — putting an exhausted account back into rotation to be refused
11050
- * 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".
11051
11157
  *
11052
11158
  * So `retryAtMs` is INHERITED when the update does not state one, and every
11053
11159
  * other field is the update's (the newer measurement owns `outcome`, `atMs`,
@@ -11106,6 +11212,39 @@ async function writePoolProbes(region, updates) {
11106
11212
  });
11107
11213
  } catch {}
11108
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
+ }
11109
11248
  //#endregion
11110
11249
  //#region src/auto-checkin.ts
11111
11250
  /**
@@ -11799,6 +11938,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11799
11938
  const imageToolEnabled = deps.imageToolEnabled?.(region) ?? false;
11800
11939
  const videoToolEnabled = deps.videoToolEnabled?.(region) ?? false;
11801
11940
  const preferredVideoModels = deps.preferredVideoModels?.(region) ?? {};
11941
+ const preferredImageModel = deps.preferredImageModel?.(region) ?? "";
11802
11942
  const cliBridgeEnabled = deps.cliBridgeEnabled?.() === true;
11803
11943
  const sidebarPanelEnabled = deps.sidebarPanelEnabled?.() === true;
11804
11944
  /**
@@ -11831,6 +11971,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11831
11971
  imageToolEnabled,
11832
11972
  videoToolEnabled,
11833
11973
  preferredVideoModels,
11974
+ preferredImageModel,
11834
11975
  cliBridgeEnabled,
11835
11976
  sidebarPanelEnabled,
11836
11977
  pollIntervalMs,
@@ -11857,6 +11998,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11857
11998
  imageToolEnabled,
11858
11999
  videoToolEnabled,
11859
12000
  preferredVideoModels,
12001
+ preferredImageModel,
11860
12002
  cliBridgeEnabled,
11861
12003
  sidebarPanelEnabled,
11862
12004
  pollIntervalMs,
@@ -11886,6 +12028,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11886
12028
  imageToolEnabled,
11887
12029
  videoToolEnabled,
11888
12030
  preferredVideoModels,
12031
+ preferredImageModel,
11889
12032
  cliBridgeEnabled,
11890
12033
  sidebarPanelEnabled,
11891
12034
  pollIntervalMs,
@@ -12858,6 +13001,22 @@ const regionStateConfig = z.object({
12858
13001
  enabledModelIds: z.array(z.string()).default([]),
12859
13002
  imageModelIds: z.array(z.string()).default([]),
12860
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
+ /**
12861
13020
  * Alternative CN gateway host (issue #220); see the interface field of the
12862
13021
  * same name. Empty = the built-in gateway.
12863
13022
  *
@@ -13459,7 +13618,10 @@ function apply(ctx, config) {
13459
13618
  reportRefusal: (report) => {
13460
13619
  recordRefusal(report);
13461
13620
  },
13462
- prepareAccount: () => applyPoolSelection(region),
13621
+ prepareAccount: async (signal) => {
13622
+ await refreshDepletedPoolCredits(region, signal);
13623
+ if (!signal?.aborted) await applyPoolSelection(region);
13624
+ },
13463
13625
  failoverAccount: (triedAccountIds) => failoverAccountFor(region, triedAccountIds),
13464
13626
  failoverShortfall: () => explainPoolShortfall(region),
13465
13627
  onAccountFailure: (accountId, failure) => {
@@ -13947,6 +14109,11 @@ function apply(ctx, config) {
13947
14109
  listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13948
14110
  generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
13949
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
+ },
13950
14117
  logger: ctx.logger
13951
14118
  })
13952
14119
  });
@@ -14236,6 +14403,13 @@ function apply(ctx, config) {
14236
14403
  */
14237
14404
  preferredVideoModels: (region) => regionStateOf(current(), region).preferredVideoModels ?? {},
14238
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
+ /**
14239
14413
  * Whether the optional CodeBuddy CLI route is mounted (`codebuddy_ask` tool
14240
14414
  * + `/codebuddy` command).
14241
14415
  *
@@ -14297,11 +14471,11 @@ function apply(ctx, config) {
14297
14471
  * token: the route passes only model ids and receives only outcomes.
14298
14472
  *
14299
14473
  * `quotaRefreshAtMs` is the region's nearest monthly refresh point, read from
14300
- * the SAME credit answer the card displays. It is the only cooldown this
14301
- * service ever states — an exhausted monthly resource that resets at a known
14302
- * time — so it is what makes "when can I use this again" answerable for an
14303
- * out-of-credit result. Every other limited outcome has no time anywhere, and
14304
- * 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.
14305
14479
  */
14306
14480
  async probeModels(region, modelIds, options) {
14307
14481
  let credential;
@@ -14459,17 +14633,18 @@ function apply(ctx, config) {
14459
14633
  * failure is simply omitted, which the card renders as unknown.
14460
14634
  */
14461
14635
  async checkedInToday(region) {
14462
- if (!poolPreferencesOf(current(), region).enabled) return {};
14636
+ if (region !== "cn" || !poolPreferencesOf(current(), region).enabled) return {};
14463
14637
  const store = stacks[region].store;
14464
14638
  const accounts = await store.accounts();
14465
14639
  const now = Date.now();
14466
14640
  const entries = await Promise.all(accounts.map(async (account) => {
14641
+ if (account.enterprise === true) return void 0;
14467
14642
  const cached = checkinStateCache[region]?.[account.id];
14468
14643
  if (cached !== void 0 && checkinReadingFresh(cached.atMs, now, CHECKIN_CACHE_MS)) return [account.id, cached.checkedIn];
14469
14644
  const credential = await store.credentialFor(account.id).catch(() => void 0);
14470
14645
  if (credential === void 0) return void 0;
14471
14646
  const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
14472
- if (status === void 0) return void 0;
14647
+ if (status === void 0 || !status.active) return void 0;
14473
14648
  checkinStateCache[region] = {
14474
14649
  ...checkinStateCache[region],
14475
14650
  [account.id]: {
@@ -14605,6 +14780,10 @@ function apply(ctx, config) {
14605
14780
  const cached = checkinStateCache[region];
14606
14781
  if (cached !== void 0) delete cached[row.accountId];
14607
14782
  }
14783
+ if (rows.some((row) => row.status !== "failed")) {
14784
+ await poolMembersOf(region);
14785
+ await applyPoolSelection(region);
14786
+ }
14608
14787
  return rows;
14609
14788
  },
14610
14789
  test: async (region, modelId, onRow) => {
@@ -14774,10 +14953,11 @@ function apply(ctx, config) {
14774
14953
  * The region's nearest monthly quota refresh, or undefined when unknown.
14775
14954
  *
14776
14955
  * The monthly resource (`CapacityType 4`) is the one package that never
14777
- * expires and resets on a cycle, so its `refreshAtMs` is a real answer to
14778
- * "when can I use this again" after the quota runs out. The probe passes it
14779
- * through; a failure to read it is not an error, because a probe without a
14780
- * 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.
14781
14961
  */
14782
14962
  const quotaRefreshOf = async (region, credential) => {
14783
14963
  try {
@@ -14882,11 +15062,10 @@ function apply(ctx, config) {
14882
15062
  * without fetching one.
14883
15063
  *
14884
15064
  * Credits are the ranking's second key, and they cost an upstream call per
14885
- * member. A chat request must never pay that: it happens on the hot path, and
14886
- * `fetchCredits` per member would turn one page of conversation into N extra
14887
- * requests. So the request path uses whatever the pool last read (the card's
14888
- * 60-second poll, a batch test, or a save) and simply skips the key when the
14889
- * 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.
14890
15069
  */
14891
15070
  const creditsSnapshot = {};
14892
15071
  /** How long a credits reading may steer routing. */
@@ -14898,9 +15077,9 @@ function apply(ctx, config) {
14898
15077
  * the probe store, plus the credits snapshot when it is fresh.
14899
15078
  *
14900
15079
  * The request path calls this on every chat completion, so it must not touch
14901
- * the network. `poolMembersOf` is the honest-but-expensive version (it fetches
14902
- * credits per member) and stays on the card's route, which is where those
14903
- * 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.
14904
15083
  */
14905
15084
  async function localPoolMembers(region) {
14906
15085
  const accounts = await poolMemberAccounts(region);
@@ -14921,6 +15100,64 @@ function apply(ctx, config) {
14921
15100
  });
14922
15101
  }
14923
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
+ /**
14924
15161
  * Record a failure a LIVE request hit, so the NEXT request starts from a
14925
15162
  * usable account.
14926
15163
  *
@@ -14937,23 +15174,13 @@ function apply(ctx, config) {
14937
15174
  * sideline a good account over a bad body.
14938
15175
  *
14939
15176
  * The reset time comes from the upstream's own words — the 429 body carries
14940
- * 「将在 … 重置」 — which `cooldownOf` parses. When it states no time, the store's
14941
- * own short window applies rather than a guess at a long one.
14942
- *
14943
- * THE QUOTA REFRESH POINT IS PASSED IN, and it is not decoration. This path
14944
- * used to omit `quotaRefreshAtMs` while the PROBE path supplied it, so one
14945
- * `out-of-credit` failure got two different answers depending on which door it
14946
- * arrived through: the probe said "the quota refreshes on the 1st" (a time the
14947
- * billing side states outright) while a live chat failure said "30 minutes
14948
- * from now" — a window the account cannot possibly clear, so the pool put it
14949
- * back and paid another refused round trip. Worse, the write below combines
14950
- * with the stored record, and the stored refresh point was being LOST in the
14951
- * process (see {@link mergePoolProbe}).
14952
- *
14953
- * Reading it costs one `fetchCredits`, affordable here but not on every
14954
- * failure: it runs only for `out-of-credit`, where the refresh point is the one
14955
- * honest answer and there is no cheaper source. Failing to read it is not an
14956
- * 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.
14957
15184
  *
14958
15185
  * The upstream's text is persisted alongside the outcome so the card can name
14959
15186
  * the reason. It is REDACTED first because this message is a raw upstream body:
@@ -15046,10 +15273,17 @@ function apply(ctx, config) {
15046
15273
  async function poolMembersOf(region) {
15047
15274
  const store = stacks[region].store;
15048
15275
  const accounts = await poolMemberAccounts(region);
15049
- const probes = await readPoolProbes(region);
15276
+ const recordedProbes = await readPoolProbes(region);
15277
+ const creditReadings = [];
15050
15278
  const rows = await Promise.all(accounts.map(async (account) => {
15051
15279
  const credential = await store.credentialFor(account.id).catch(() => void 0);
15280
+ const startedAtMs = Date.now();
15052
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
+ });
15053
15287
  return {
15054
15288
  account: {
15055
15289
  id: account.id,
@@ -15061,13 +15295,16 @@ function apply(ctx, config) {
15061
15295
  expiringSoon: credits.expiringSoon,
15062
15296
  ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
15063
15297
  } },
15064
- ...probes[account.id] === void 0 ? {} : { probe: probes[account.id] },
15065
15298
  tokenExpiresAtMs: account.tokenExpiresAtMs
15066
15299
  };
15067
15300
  }));
15301
+ const probes = creditReadings.some((reading) => recordedProbes[reading.accountId]?.outcome === "out-of-credit") ? await reconcilePoolCredits(region, creditReadings) : recordedProbes;
15068
15302
  creditsSnapshot[region] = new Map(rows.filter((row) => row.credits !== void 0).map((row) => [row.account.id, row.credits]));
15069
15303
  creditsSnapshotAt[region] = Date.now();
15070
- return rows;
15304
+ return rows.map((row) => ({
15305
+ ...row,
15306
+ ...probes[row.account.id] === void 0 ? {} : { probe: probes[row.account.id] }
15307
+ }));
15071
15308
  }
15072
15309
  /**
15073
15310
  * The model a per-row test would use right now: the SAME resolution the
@@ -15237,6 +15474,10 @@ function apply(ctx, config) {
15237
15474
  const cached = checkinStateCache[region];
15238
15475
  if (cached !== void 0) delete cached[row.accountId];
15239
15476
  }
15477
+ if (rows.some((row) => row.status !== "failed")) {
15478
+ await poolMembersOf(region);
15479
+ await applyPoolSelection(region);
15480
+ }
15240
15481
  const folded = foldAttempt(state, rows, nowMs, targets.length + state.doneAccountIds.length);
15241
15482
  autoCheckinState[region] = folded;
15242
15483
  await writeAutoCheckinState(region, folded);