dsh-connect-workbuddy 5.21.4 → 5.23.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-CRS-1LBA.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
  /**
@@ -1285,13 +1287,18 @@ const WORKBUDDY_PROVIDERS = {
1285
1287
  *
1286
1288
  * pi-ai keeps a historical thinking block as `thinking` only when the message
1287
1289
  * that carried it names the SAME provider, api and model id as the request in
1288
- * flight (`transform-messages.js:68`); every other block is downgraded to plain
1289
- * `text` (`:88–96`) — downgraded, not dropped, which is why no byte count ever
1290
- * explained the 1.94× regional jump. The two gateways are two provider STRINGS
1291
- * for ONE model, so a transcript recorded in one region was replayed as text in
1292
- * the other, and issue #59's reporter measured exactly that: 708K → 1.374M on
1293
- * byte-identical history, and a compression request that could then never fit
1294
- * the window it was computed for.
1290
+ * flight (`transform-messages.js`, `isSameModel`); every other block is
1291
+ * downgraded to plain `text` — downgraded, not dropped, which is why no byte
1292
+ * count ever explained the 1.94× regional jump. The two gateways are two
1293
+ * provider STRINGS for ONE model, so a transcript recorded in one region was
1294
+ * replayed as text in the other, and issue #59's reporter measured exactly
1295
+ * that: 708K → 1.374M on byte-identical history, and a compression request
1296
+ * that could then never fit the window it was computed for.
1297
+ *
1298
+ * (pi-ai 1.3 changed the second half: a foreign block is now DISCARDED rather
1299
+ * than rewritten as text. The identity stamp is unaffected — it is what makes
1300
+ * the block count as same-model in the first place, and that comparison is
1301
+ * unchanged in every generation this plugin declares.)
1295
1302
  *
1296
1303
  * The stamp is NOT inert, and reading it as inert is what broke issue #75.
1297
1304
  * `provider` is the KEY pi-ai dispatches on: `requireProvider` resolves
@@ -1369,10 +1376,42 @@ const WORKBUDDY_PROVIDER_DISPLAY_NAMES = {
1369
1376
  /** Provider idle ceiling while one stream read is outstanding. */
1370
1377
  const WORKBUDDY_STREAM_IDLE_TIMEOUT_MS = 3e5;
1371
1378
  /**
1372
- * Image-request budgets at the dsh-llm-pi-ai defaults; the profile type made
1373
- * them required in 0.1.1-rc.2.
1379
+ * Image-request budgets for the route's `ResolvedPiAiProviderProfile`.
1380
+ *
1381
+ * The three byte/pixel budgets are the dsh-llm-pi-ai defaults (`0.1.1-rc.2`
1382
+ * made them required on the resolved profile).
1383
+ *
1384
+ * The two COUNT fields arrived with DSH 0.2.2 (`0.2.2-rc.1`), where
1385
+ * `dsh-llm-pi-ai` began enforcing a per-request image OCCURRENCE limit
1386
+ * (`maxRequestImages`, its own default 50) and the offload step that trims it
1387
+ * (`imageOffloadCountQuantum`, default `min(10, maxRequestImages)`). Both are
1388
+ * REQUIRED on the resolved profile, so this route must state a value; the
1389
+ * value is the plugin's decision, not a copy of the host's.
1390
+ *
1391
+ * WHY NOT 50. Until 0.2.2 this route had NO occurrence limit at all: the
1392
+ * adapter only ever passed the byte budget down (`toPiContextWithImages`
1393
+ * spreads `maxImages` only when it is defined), so a long session could carry
1394
+ * any number of images as long as the base64 payload fit. Adopting the host's
1395
+ * default would therefore NARROW this plugin's behaviour as a silent side
1396
+ * effect of a dependency bump — the kind of change that shows up as a user's
1397
+ * image-heavy session suddenly failing with `IMAGE_OFFLOAD_REQUIRED`.
1398
+ *
1399
+ * So both values are deliberately pinned far above any real request: they are
1400
+ * a TYPE requirement satisfied with "no practical limit", which keeps today's
1401
+ * behaviour byte-identical. `maxRequestImages` is a count of image
1402
+ * occurrences and the upstream gateway caps a request far below this on its
1403
+ * own; `imageOffloadCountQuantum` must not exceed `maxRequestImages`
1404
+ * (`dsh-llm-pi-ai` validates exactly that), so it is pinned to the same
1405
+ * giant value rather than to 10.
1406
+ *
1407
+ * If the gateway's real per-request image cap ever gets measured, THAT is the
1408
+ * number to put in `maxRequestImages` — with a comment saying where it came
1409
+ * from. Do not "borrow" the host's 50: it belongs to the host's own pi-ai
1410
+ * routes, not to WorkBuddy.
1374
1411
  */
1375
1412
  const REQUEST_IMAGE_BUDGETS = {
1413
+ maxRequestImages: 1e6,
1414
+ imageOffloadCountQuantum: 1e6,
1376
1415
  maxRequestImageBytes: 20971520,
1377
1416
  requestImagePixelBudget: 4194304,
1378
1417
  requestImageMaxBytes: 1048576
@@ -1478,8 +1517,12 @@ function workBuddyThinkingLevelMap(info) {
1478
1517
  * stamped field is what pi-ai resolves the provider BY (issue #75) — so every
1479
1518
  * key in {@link modelIdentityKeysOf} must be a key this route registers.
1480
1519
  */
1481
- function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1520
+ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY, midConvoSystemMessages = false) {
1482
1521
  const thinkingLevelMap = workBuddyThinkingLevelMap(info);
1522
+ const compat = midConvoSystemMessages ? {
1523
+ supportsReasoningEffort: thinkingLevelMap !== void 0,
1524
+ supportsMidConvoSystemMessages: true
1525
+ } : { supportsReasoningEffort: thinkingLevelMap !== void 0 };
1483
1526
  return {
1484
1527
  id: info.id,
1485
1528
  name: workBuddyDisplayName(info),
@@ -1492,7 +1535,7 @@ function toPiModel(info, baseUrl, identity = WORKBUDDY_MODEL_IDENTITY) {
1492
1535
  maxTokens: info.maxTokens,
1493
1536
  reasoning: thinkingLevelMap !== void 0,
1494
1537
  ...thinkingLevelMap === void 0 ? {} : { thinkingLevelMap },
1495
- compat: { supportsReasoningEffort: thinkingLevelMap !== void 0 }
1538
+ compat
1496
1539
  };
1497
1540
  }
1498
1541
  /**
@@ -1730,7 +1773,8 @@ function transcript(context) {
1730
1773
  * ISSUE #102. pi-ai replays a thinking block as `thinking` only when the message
1731
1774
  * that produced it names the same `provider` / `api` / `model` as the request in
1732
1775
  * flight (`utils/transform-messages.js`, the `isSameModel` branch); everything
1733
- * else is flattened to `{type:'text', text: thinking}`.
1776
+ * else is flattened to `{type:'text', text: thinking}` — or, since pi-ai 1.3,
1777
+ * discarded outright. Either way the block stops being reasoning.
1734
1778
  *
1735
1779
  * The durable transcript the HOST hands back does not carry the identity. The
1736
1780
  * agent loop writes `source.provider = request.provider`, and `request.provider`
@@ -1825,8 +1869,8 @@ function blocksOf$1(message) {
1825
1869
  *
1826
1870
  * `requestModelId` closes the THIRD leg of pi-ai's own predicate. `isSameModel`
1827
1871
  * is `provider === … && api === … && model === model.id`
1828
- * (`transform-messages.js:68–70`); this function used to compare only the first
1829
- * two. The consequence was a blind spot the size of one whole route: a session
1872
+ * (`transform-messages.js`, and its line numbers move between releases, so this
1873
+ * file names the symbol); this function used to compare only the first two. The consequence was a blind spot the size of one whole route: a session
1830
1874
  * that switches MODELS inside one region — `hy3` → `deepseek-v4.1-flash`, both
1831
1875
  * served by this bundle, both stamped `provider: workbuddy` — keeps the provider
1832
1876
  * and api legs equal, so nothing here noticed, while pi-ai flattened every
@@ -1885,12 +1929,12 @@ function isCrossProviderAssistant(message, identity, ownedRoutes) {
1885
1929
  * Every foreign thinking block pi-ai would turn into visible prose (issue #147).
1886
1930
  *
1887
1931
  * THE DEFECT. pi-ai keeps a historical `thinking` block only while
1888
- * `isSameModel` holds — provider AND api AND model id all equal to the request
1889
- * (`transform-messages.js:68`). For everything else it does NOT drop the block:
1890
- * `:87–90` rewrites it to `{type:'text', text: thinking}`, which is the answer
1891
- * channel. A session that moved between providers therefore arrives with its
1892
- * other provider's working notes already spelled as prose, and the model reads
1893
- * that shape and copies it.
1932
+ * `isSameModel` holds — provider AND api AND model id all equal to the request.
1933
+ * For everything else, up to pi-ai 1.2, it did NOT drop the block: it rewrote
1934
+ * it to `{type:'text', text: thinking}`, which is the answer channel. A session
1935
+ * that moved between providers therefore arrives with the other provider's
1936
+ * working notes already spelled as prose, and the model reads that shape and
1937
+ * copies it.
1894
1938
  *
1895
1939
  * Issue #147 measured the consequence on a real 80-step turn: 56 assistant
1896
1940
  * messages carried an answer while their own `reasoning` was ≤ 1 character,
@@ -1904,6 +1948,14 @@ function isCrossProviderAssistant(message, identity, ownedRoutes) {
1904
1948
  * {@link dropForeignThinking} does, and the split keeps the DIAGNOSIS available
1905
1949
  * to surfaces that must not change bytes (the card, the reply notice).
1906
1950
  *
1951
+ * WHY IT STILL RUNS ON pi-ai 1.3+. That library now discards a foreign block
1952
+ * itself, so on paper this repair has nothing left to do. It stays because the
1953
+ * resolved pi-ai is a PER-PROCESS fact, not a package-level one: a nested copy
1954
+ * shadows the host's (issue #24 proved it), so the plugin cannot assume any
1955
+ * particular generation for the user in front of it. The repair is this
1956
+ * bundle's own guarantee — "another model's reasoning never reaches this
1957
+ * request" — and it is cheaper than reasoning about which copy is loaded.
1958
+ *
1907
1959
  * @param context - a pi-ai context, before or after `alignAssistantIdentities`.
1908
1960
  * @param identity - the identity this adapter stamps on its own models.
1909
1961
  * @param requestModelId - model id the request is addressed to, so the model
@@ -1965,7 +2017,9 @@ function foreignThinkingOf(context, identity = WORKBUDDY_MODEL_IDENTITY, request
1965
2017
  * - a block with NO signature is never emitted at all - it is dropped from the
1966
2018
  * request, not turned into prose;
1967
2019
  * - a block whose message fails `isSameModel` IS flattened into assistant prose
1968
- * (`transform-messages.js:88-96`), and that is the only real 'flattened' case.
2020
+ * (`transform-messages.js`, the `isSameModel` else-branch), and that is the
2021
+ * only real 'flattened' case — up to pi-ai 1.2. From 1.3 such a block is
2022
+ * discarded instead, which moves it into the second bullet's outcome.
1969
2023
  *
1970
2024
  * So the field is deliberately not surfaced to the user: `variant` reaches
1971
2025
  * nothing but the diagnostic callback, and a label that is wrong for two of the
@@ -2322,7 +2376,8 @@ function createWorkBuddyAdapter(options) {
2322
2376
  const generation = options.piAiGeneration ?? piAiRuntimeInfo().generation;
2323
2377
  const buildModels = () => {
2324
2378
  const baseUrl = `${shim.baseUrl()}/v1`;
2325
- return catalog.current().map((info) => toPiModel(info, baseUrl, modelIdentity));
2379
+ const midConvoSystemMessages = regionOfProvider(providerId) === "cn";
2380
+ return catalog.current().map((info) => toPiModel(info, baseUrl, modelIdentity, midConvoSystemMessages));
2326
2381
  };
2327
2382
  const provider = {
2328
2383
  ...createProvider({
@@ -2941,16 +2996,19 @@ function installChannelContinue(mount) {
2941
2996
  * history was labelled differently on the two sides.
2942
2997
  *
2943
2998
  * The labelling is pi-ai's replay — which assistant messages it lets survive as
2944
- * thinking at all. `transform-messages.js:68` (1.1.0, the version the host
2945
- * bundles) computes
2999
+ * thinking at all. `transform-messages.js` (1.1.0, the version the host bundled
3000
+ * when this report was written) computes
2946
3001
  *
2947
3002
  * isSameModel = assistantMsg.provider === model.provider
2948
3003
  * && assistantMsg.api === model.api
2949
3004
  * && assistantMsg.model === model.id;
2950
3005
  *
2951
- * and for a message that fails it, `:88–96` returns the surviving thinking as
2952
- * `{ type: "text", text: block.thinking }` — downgraded, not dropped — while
2953
- * `:76` drops redacted thinking and `:103` strips tool-call `thoughtSignature`.
3006
+ * and for a message that fails it, it returned the surviving thinking as
3007
+ * `{ type: "text", text: block.thinking }` — downgraded, not dropped — while it
3008
+ * dropped redacted thinking and stripped tool-call `thoughtSignature`. The
3009
+ * comparison is what this report explains and it is unchanged in every pi-ai
3010
+ * generation this plugin declares; only the ELSE branch moved, and pi-ai 1.3
3011
+ * now discards the block instead of rewriting it.
2954
3012
  * `buildParams` runs that transform at `openai-completions.js:896`, before
2955
3013
  * anything is assembled, so a thinking block only stays a thinking block when
2956
3014
  * its message was recorded under the same provider AND the same model id as the
@@ -2960,7 +3018,8 @@ function installChannelContinue(mount) {
2960
3018
  * vendor, uniformly — 790 replay records in one real session held that value
2961
3019
  * and no other). Non-survivors are text by the time `:964–971` collects
2962
3020
  * `assistantText`, so they land in `assistantMsg.content` instead. This plugin
2963
- * sets only `compat.supportsReasoningEffort` (`src/adapter.ts:200`), which
3021
+ * sets `compat.supportsReasoningEffort` and `compat.supportsMidConvoSystemMessages`
3022
+ * (`src/adapter.ts`), neither of which touches `requiresThinkingAsText`, which
2964
3023
  * leaves `requiresThinkingAsText` at its `false` default (`:1270`), so the raw
2965
3024
  * field route is the live one rather than the fold-into-content route at `:983`.
2966
3025
  *
@@ -5863,9 +5922,12 @@ function createWorkBuddyShim(options) {
5863
5922
  writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
5864
5923
  return;
5865
5924
  }
5866
- await prepareAccount?.().catch((error) => {
5925
+ const controller = new AbortController();
5926
+ res.on("close", () => controller.abort());
5927
+ await prepareAccount?.(controller.signal).catch((error) => {
5867
5928
  logger?.warn("dsh-connect-workbuddy: pool account selection failed", error);
5868
5929
  });
5930
+ if (controller.signal.aborted) return;
5869
5931
  let credential;
5870
5932
  try {
5871
5933
  credential = await store.resolve();
@@ -5884,8 +5946,6 @@ function createWorkBuddyShim(options) {
5884
5946
  } catch (error) {
5885
5947
  logger?.warn("dsh-connect-workbuddy: body report failed", error);
5886
5948
  }
5887
- const controller = new AbortController();
5888
- res.on("close", () => controller.abort());
5889
5949
  const preferred = channelPerturbation === "always" || channelNeedsPerturbation ? perturbChannelFingerprints(prepared, channelPerturbation === "always") ?? prepared : prepared;
5890
5950
  let result = await client.chatStream(credential, preferred, controller.signal);
5891
5951
  if (channelNeedsPerturbation && !result.ok && result.kind === "channel_reject") {
@@ -6183,6 +6243,30 @@ const IMAGE_TOOL_TIMEOUT_MS = 18e4;
6183
6243
  const IMAGE_INPUT_TIMEOUT_MS = 3e4;
6184
6244
  /** 失败后的冷却:生图按张扣积分,连续重试会在几秒内烧掉几十积分。 */
6185
6245
  const FAILURE_COOLDOWN_MS$1 = 3e4;
6246
+ /**
6247
+ * 选这次真正要用的模型。
6248
+ *
6249
+ * 优先级只有三级,且第二级「谁写的」决定写错了谁负责:
6250
+ *
6251
+ * 1. 调用方显式传的 `model`——写错就报错(`pickMediaModel` 会列出可用项)。
6252
+ * 2. 用户在卡片上选的偏好(`preferredImageModel`)——**只在没显式传时**生效,
6253
+ * 而且失效时静默回落,因为目录可能已经变过,一个过期偏好不该卡住一次生成。
6254
+ * 3. 组内第一个,也就是上游目录今天给的那条(默认 `hunyuan-image-alpha`)。
6255
+ *
6256
+ * 偏好只落在软约束这一侧,是因为它和 `model` 参数的区别是**谁写的**:参数是这次
6257
+ * 的调用者写的,偏好是用户上一次在卡片上点的。这与视频工具 `preferredVideoModel`
6258
+ * 的判据完全一致,两个工具不该有两套说法。
6259
+ */
6260
+ function resolveImageModel(models, requested, tag, deps, credential, region) {
6261
+ const choices = region === "cn" ? imageModelChoices(models, tag) : models.filter((model) => model.tags.includes(tag));
6262
+ const pinned = requested === void 0 ? deps.preferredImageModel?.(credential, tag) : void 0;
6263
+ try {
6264
+ return pickMediaModel(choices, requested ?? pinned, tag);
6265
+ } catch (error) {
6266
+ if (requested !== void 0 || pinned === void 0) throw error;
6267
+ return pickMediaModel(choices, void 0, tag);
6268
+ }
6269
+ }
6186
6270
  function asRecord$1(value) {
6187
6271
  return typeof value === "object" && value !== null ? value : {};
6188
6272
  }
@@ -6237,11 +6321,9 @@ function strictString$1(value, name) {
6237
6321
  }
6238
6322
  /** 「宽x高」——允许 `x` / `X` / 全角 `×`;不接受 `*`、空格、带单位。 */
6239
6323
  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;
6324
+ IMAGE_SIZE_LIMITS_WIDE.maxPixels;
6325
+ IMAGE_SIZE_LIMITS_WIDE.minEdge;
6326
+ IMAGE_SIZE_LIMITS_WIDE.maxEdge;
6245
6327
  /** 实测被上游拒绝的尺寸,报错时直接点出来,省得模型反复试。 */
6246
6328
  const KNOWN_BAD_SIZES = /* @__PURE__ */ new Set([
6247
6329
  "2560x2560",
@@ -6302,37 +6384,71 @@ function parseSizeSpec(value) {
6302
6384
  * 把解析好的尺寸规格落成一个真正要发给上游的值。
6303
6385
  *
6304
6386
  * 与 {@link parseSizeSpec} 分开,是因为这两件事的**时机**不同:格式错误要在收到
6305
- * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高。
6387
+ * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高、
6388
+ * 也要等**模型定下来**——两个模型的合法范围不一样(见 `imageSizeLimitsOf`)。
6306
6389
  *
6307
6390
  * 越界为什么由工具收、而不是让模型自己算:两条边(512–2560)与总像素
6308
6391
  * (≤4,194,304)是两个约束,手算要取「2560/长边」与「√(4194304/面积)」里更小的
6309
6392
  * 那个**再复查一遍**。要求模型在参数里做这种算术,实测会算出仍然越界的值
6310
6393
  * (2480x3508 → 1810x2560,边长合规但乘积 4,633,600 仍超)。收完之后把「动过什么」
6311
6394
  * 写进 hint,模型得据实转告用户,不能假装按用户给的尺寸出图。
6395
+ *
6396
+ * `limits` 来自**这一次选中的模型**,不是全局常量:v3.0 的边更短、像素更少,
6397
+ * 用 alpha 的范围替它算会得到上游 400(实测 `1024x1025` 就被拒)。
6398
+ */
6399
+ /**
6400
+ * `size: auto` 但量不出输入图 —— 这一步**不需要模型**,所以单独提出来。
6401
+ *
6402
+ * 报错时机是这里唯一的理由:模型的失败(目录里没这条模型)要花一次目录请求
6403
+ * 才能知道,而「你写了 auto 却没给图」在本地就能判。把它压到模型解析之后,
6404
+ * 一个纯参数错误就会被「目录里没有模型」盖掉,用户改完一处还得再撞第二处。
6312
6405
  */
6313
- function planImageSize(spec, input) {
6406
+ function missingAutoSizeInput() {
6407
+ throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6408
+ }
6409
+ /** `auto` 必须配一张量得出宽高的图;没有就报那条错误,否则原样返回。 */
6410
+ function requireAutoInput(input) {
6411
+ return input ?? missingAutoSizeInput();
6412
+ }
6413
+ function planImageSize(spec, input, limits) {
6314
6414
  if (spec.kind === "auto") {
6315
- if (input === void 0) throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6316
- const canvas = canvasForInput(input);
6415
+ const source = requireAutoInput(input);
6416
+ const canvas = canvasForInput(source, limits);
6317
6417
  const size = `${canvas.width}x${canvas.height}`;
6318
6418
  return {
6319
6419
  size,
6320
6420
  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},比例有变化`
6421
+ 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
6422
  };
6323
6423
  }
6324
6424
  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。`);
6425
+ if (isSizeInRange(width, height, normalized, limits)) return { size: `${width}x${height}` };
6426
+ const fitted = fitIntoRange(width, height, limits);
6427
+ if (fitted === void 0) throw inputImageError(`workbuddy image: 参数 size ${normalized} 的比例太极端,等比缩放放不进 ${describeLimits(limits)} 的范围内。请改成接近的常用档位:` + sampleSizesFor(limits) + "。");
6328
6428
  const direction = fitted.direction === "up" ? "放大" : "缩小";
6329
6429
  return {
6330
6430
  size: `${fitted.width}x${fitted.height}`,
6331
6431
  requested: normalized,
6332
- note: `你给的尺寸 ${normalized} 超出 ${MIN_IMAGE_EDGE}–${MAX_IMAGE_EDGE} 边长或 419 万像素上限,已等比${direction}到 ${fitted.width}x${fitted.height}`
6432
+ note: `你给的尺寸 ${normalized} 超出${describeLimits(limits)},已等比${direction}到 ${fitted.width}x${fitted.height}`
6333
6433
  };
6334
6434
  }
6335
6435
  /**
6436
+ * 一句话说清这次的上限,用在两条错误/提示里。
6437
+ *
6438
+ * 说「419 万」而不是「4,194,304」:hint 是要模型原样转述给用户的,像素数写全
6439
+ * 数字没人读得进去,而「约 419 万像素」既准确又够用。v3.0 的 104 万同理
6440
+ * (1048576/1e4 = 104.9 → 105,不是 1)。
6441
+ */
6442
+ function describeLimits(limits) {
6443
+ const wan = (limits.maxPixels / 1e4).toFixed(0);
6444
+ return ` ${limits.minEdge}–${limits.maxEdge} 边长或约 ${wan} 万像素上限`;
6445
+ }
6446
+ /** 这个范围内拿得出手的档位例子——按半径给出,别举一个会被拒的。 */
6447
+ function sampleSizesFor(limits) {
6448
+ if (limits.maxPixels <= 1048576) return "方图 1024x1024、竖图 768x1024、横图 1280x720";
6449
+ return "方图 1024x1024、竖图 1024x1536、横图 1536x1024、16:9 桌面 2560x1440、9:16 手机壁纸 1440x2560";
6450
+ }
6451
+ /**
6336
6452
  * 这些失败说明请求真的打到了上游、可能已经扣了积分,才值得进冷却。
6337
6453
  * 参数写错 / 未登录 / 目录里没有模型都还没花钱。
6338
6454
  */
@@ -6496,7 +6612,7 @@ function firstDimensions(inputs) {
6496
6612
  * 极端比例(比 5:1 还细长)等比缩放放不进范围时,退回按方向的常用档——宁可换
6497
6613
  * 比例,也不能报错让用户无从下手;`exact: false` 就是用来把这句实话写进 hint 的。
6498
6614
  */
6499
- function canvasForInput(input) {
6615
+ function canvasForInput(input, limits) {
6500
6616
  const orientation = orientationOf(input);
6501
6617
  if (orientation === "square") return {
6502
6618
  ...DEFAULT_SIZE_BY_ORIENTATION.square,
@@ -6507,12 +6623,12 @@ function canvasForInput(input) {
6507
6623
  const short = Math.max(1, Math.round(shortest * AUTO_LONG_EDGE / longest));
6508
6624
  const width = orientation === "landscape" ? AUTO_LONG_EDGE : short;
6509
6625
  const height = orientation === "landscape" ? short : AUTO_LONG_EDGE;
6510
- if (isSizeInRange(width, height, `${width}x${height}`)) return {
6626
+ if (isSizeInRange(width, height, `${width}x${height}`, limits)) return {
6511
6627
  width,
6512
6628
  height,
6513
6629
  exact: true
6514
6630
  };
6515
- const fitted = fitIntoRange(width, height);
6631
+ const fitted = fitIntoRange(width, height, limits);
6516
6632
  if (fitted !== void 0) return {
6517
6633
  width: fitted.width,
6518
6634
  height: fitted.height,
@@ -6524,11 +6640,11 @@ function canvasForInput(input) {
6524
6640
  };
6525
6641
  }
6526
6642
  /** 两个上限(长边 2560、总像素 419 万)同时满足时,把宽高按比例收进范围。 */
6527
- function shrinkProduct(width, height) {
6643
+ function shrinkProduct(width, height, limits) {
6528
6644
  let w = width;
6529
6645
  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));
6646
+ for (let round = 0; round < 4 && w * h > limits.maxPixels; round += 1) {
6647
+ const scale = Math.sqrt(limits.maxPixels / (w * h));
6532
6648
  w = Math.floor(w * scale);
6533
6649
  h = Math.floor(h * scale);
6534
6650
  }
@@ -6547,38 +6663,45 @@ function shrinkProduct(width, height) {
6547
6663
  * 返回 undefined 表示等比缩放解不出来(比例比 5:1 还极端:缩到长边 2560 时短边
6548
6664
  * 已经小于 512,抬到 512 时长边又超过 2560),交给调用方按方向换档。
6549
6665
  */
6550
- function fitIntoRange(width, height) {
6666
+ function fitIntoRange(width, height, limits) {
6667
+ const { minEdge, maxEdge, maxPixels } = limits;
6551
6668
  const longest = Math.max(width, height);
6552
6669
  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)),
6670
+ if (!(longest > maxEdge || width * height > maxPixels) && shortest < minEdge) {
6671
+ const scale = minEdge / shortest;
6672
+ if (longest * scale <= maxEdge) return {
6673
+ ...shrinkProduct(Math.round(width * scale), Math.round(height * scale), limits),
6557
6674
  direction: "up"
6558
6675
  };
6559
6676
  return;
6560
6677
  }
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 {
6678
+ const scale = Math.min(maxEdge / longest, Math.sqrt(maxPixels / (width * height)));
6679
+ const scaled = shrinkProduct(Math.floor(width * scale), Math.floor(height * scale), limits);
6680
+ if (scaled.width >= minEdge && scaled.height >= minEdge) return {
6564
6681
  ...scaled,
6565
6682
  direction: "down"
6566
6683
  };
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 {
6684
+ const extreme = minEdge / shortest;
6685
+ if (longest * extreme <= maxEdge) {
6686
+ const lifted = shrinkProduct(Math.round(width * extreme), Math.round(height * extreme), limits);
6687
+ if (lifted.width * lifted.height <= maxPixels) return {
6571
6688
  ...lifted,
6572
6689
  direction: "up"
6573
6690
  };
6574
6691
  }
6575
6692
  }
6576
- /** 一个尺寸是否直接可用:两条边在 512–2560,且宽乘高不超过 419 万。 */
6577
- function isSizeInRange(width, height, normalized) {
6693
+ /**
6694
+ * 一个尺寸能否**原样**发给这次选中的模型。
6695
+ *
6696
+ * 三个判据都跟着 `limits` 走,不是全局常量:v3.0 的边 2048 / 像素 1,048,576,
6697
+ * alpha 才是 2560 / 4,194,304。`KNOWN_BAD_SIZES` 是那个宽档下实测被拒的档位,
6698
+ * 窄档的边界由 `limits` 本身就够判,不必再叠一份。
6699
+ */
6700
+ function isSizeInRange(width, height, normalized, limits) {
6578
6701
  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;
6702
+ if (width < limits.minEdge || height < limits.minEdge) return false;
6703
+ if (width > limits.maxEdge || height > limits.maxEdge) return false;
6704
+ return width * height <= limits.maxPixels;
6582
6705
  }
6583
6706
  /**
6584
6707
  * 体积与空文件闸门——四种输入形态都从这里过,所以「空文件」和「超过 8 MB」的
@@ -6667,7 +6790,7 @@ function createImageTool(deps) {
6667
6790
  };
6668
6791
  return {
6669
6792
  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 时引用它并提醒尽快转存——本工具不负责下载或转存,要长期保存得用户自己点开链接另存。",
6793
+ 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
6794
  parameters: {
6672
6795
  type: "object",
6673
6796
  properties: {
@@ -6793,11 +6916,13 @@ function createImageTool(deps) {
6793
6916
  try {
6794
6917
  const models = await listModels(credential, signal);
6795
6918
  const resolved = images === void 0 ? void 0 : await Promise.all(images.map((image) => resolveImageInput(image, signal)));
6919
+ const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6796
6920
  const inputSize = resolved === void 0 ? void 0 : firstDimensions(resolved);
6797
- const plan = planImageSize(sizeSpec, inputSize);
6798
- const size = plan.size;
6921
+ if (sizeSpec.kind === "auto" && inputSize === void 0) missingAutoSizeInput();
6799
6922
  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);
6923
+ const model = resolveImageModel(models, requestedModel, inputs === void 0 ? IMAGE_TAG_TEXT_TO_IMAGE : IMAGE_TAG_IMAGE_TO_IMAGE, deps, credential, region);
6924
+ const plan = planImageSize(sizeSpec, inputSize, imageSizeLimitsOf(model.id));
6925
+ const size = plan.size;
6801
6926
  sent = true;
6802
6927
  const outcome = inputs === void 0 ? await deps.generateImage(credential, {
6803
6928
  model: model.id,
@@ -6810,17 +6935,17 @@ function createImageTool(deps) {
6810
6935
  image: inputs
6811
6936
  }, signal);
6812
6937
  const mode = inputs === void 0 ? "generate" : "edit";
6813
- const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6814
6938
  const regionLabel = region === "global" ? "国际版" : "国内版";
6815
6939
  const dimensionNote = plan.note === void 0 ? "" : `${plan.note}。`;
6816
6940
  const inputNote = inputSize === void 0 ? "" : `输入图第一张是 ${inputSize.width}x${inputSize.height}(${ORIENTATION_LABEL[orientationOf(inputSize)]})。`;
6941
+ const watermarkNote = isWatermarkFreeImageModel(model.id) ? "这个模型出图不带 WorkBuddy 水印(代价是单价更高、尺寸上限更小)。" : "这个模型出的图右下角带「AI生成 WORKBUDD>」水印——上游没有关闭它的参数;要无水印可在插件卡片里把生图模型选成 hunyuan-image-v3.0(更贵、尺寸上限更小)。";
6817
6942
  const value = {
6818
6943
  mode,
6819
6944
  region,
6820
6945
  size,
6821
6946
  model: model.id,
6822
6947
  prompt,
6823
- hint: `这张图来自 WorkBuddy ${regionLabel}(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"},尺寸 ${size})。` + inputNote + dimensionNote + (outcome.credit === void 0 ? "本次响应没带扣费字段,具体扣了多少以额度面板为准。" : `本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6948
+ hint: `这张图来自 WorkBuddy ${regionLabel}(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"},尺寸 ${size})。` + inputNote + dimensionNote + watermarkNote + (outcome.credit === void 0 ? "本次响应没带扣费字段,具体扣了多少以额度面板为准。" : `本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6824
6949
  };
6825
6950
  if (plan.requested !== void 0 && plan.requested !== size) value["requestedSize"] = plan.requested;
6826
6951
  if (outcome.url !== void 0) value["url"] = outcome.url;
@@ -9277,6 +9402,26 @@ function mountCommandSurface(runtime, commands) {
9277
9402
  return mountCodebuddyCommand(commands, runtime.deps);
9278
9403
  }
9279
9404
  //#endregion
9405
+ //#region src/cli-bridge/services.ts
9406
+ /**
9407
+ * Read one projection key through whichever face the Host offers.
9408
+ *
9409
+ * Extracted from the `ctx.inject(['sessionProjections'])` closure so the
9410
+ * PREFERENCE is testable: on a current Host `snapshot` must answer and
9411
+ * `stateOf` must never be called (it prints a deprecation warning the first
9412
+ * time it is), while an older Host that has only `stateOf` must still answer
9413
+ * instead of silently reporting "no directory".
9414
+ *
9415
+ * `undefined` means "the Host recorded nothing", which is the same signal both
9416
+ * faces give, and the ladder above treats it as such — it must NOT be confused
9417
+ * with a failure, or the header fallback would disappear. A throw is the
9418
+ * caller's to catch (the inject closure does).
9419
+ */
9420
+ function readProjectedState(reader, session, key) {
9421
+ if (typeof reader.snapshot === "function") return reader.snapshot(session, [key])?.values?.[key];
9422
+ return reader.stateOf?.(session, key);
9423
+ }
9424
+ //#endregion
9280
9425
  //#region src/probe.ts
9281
9426
  /**
9282
9427
  * How long to bench a MODEL that answered 14003 with no stated time.
@@ -9511,7 +9656,8 @@ function parseUpstreamResetAt(message) {
9511
9656
  return utcMs - offsetTotalMinutes * 6e4;
9512
9657
  }
9513
9658
  /**
9514
- * The cooldown the upstream stated, if it stated one.
9659
+ * The upstream reset metadata, if stated. A credit-package refresh timestamp
9660
+ * is retained for diagnostics; it is not a minimum wait or recovery evidence.
9515
9661
  *
9516
9662
  * Three sources, in order of authority:
9517
9663
  *
@@ -9522,13 +9668,13 @@ function parseUpstreamResetAt(message) {
9522
9668
  * this service: a 429 from the Chinese gateway carries code 6004 and a
9523
9669
  * `将在 … 重置` sentence, with no `Retry-After` header at all.
9524
9670
  * 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.
9671
+ * outcome. Check-in or a purchase can replenish credits earlier, so callers
9672
+ * must not render this metadata as a recovery countdown or release the
9673
+ * account when the timestamp passes.
9528
9674
  *
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.
9675
+ * A limited outcome with none of the three returns `{}`. Rate-limit views state
9676
+ * that no time was given; credit-exhaustion views name the replenishment action
9677
+ * instead. Neither view invents a countdown.
9532
9678
  *
9533
9679
  * An `ok` outcome ALWAYS returns `{}`, whatever headers or body came with it.
9534
9680
  * A successful probe has already answered "can this account serve right now?"
@@ -10157,7 +10303,7 @@ function exclusionOf(probe, nowMs) {
10157
10303
  case "failed": return retryDue(probe, nowMs) ? void 0 : "failed";
10158
10304
  case "rate-limited": return retryDue(probe, nowMs) ? void 0 : "rate-limited";
10159
10305
  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";
10306
+ case "out-of-credit": return "out-of-credit";
10161
10307
  case "policy-rejected": return;
10162
10308
  case "channel-rejected": return;
10163
10309
  default: return "unusable";
@@ -10166,11 +10312,10 @@ function exclusionOf(probe, nowMs) {
10166
10312
  /**
10167
10313
  * Whether an account's cooldown has elapsed (or was never stated).
10168
10314
  *
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.
10315
+ * Transient failures without a stated retry time use the local short window.
10316
+ * Credit exhaustion is cleared by later positive balance evidence or an explicit
10317
+ * successful pool test; ordinary chat success does not update the probe store.
10318
+ * It does not call this helper.
10174
10319
  *
10175
10320
  * `fallbackMs` lets one outcome carry a SHORTER clock than the generic one: the
10176
10321
  * model-scoped throttle is upstream's own "about a minute", and applying the
@@ -10181,6 +10326,30 @@ function retryDue(probe, nowMs, fallbackMs = POOL_UNKNOWN_COOLDOWN_MS) {
10181
10326
  return nowMs >= (probe.retryAtMs ?? probe.atMs + fallbackMs);
10182
10327
  }
10183
10328
  /**
10329
+ * When an EXCLUDED account becomes a candidate again, in epoch ms.
10330
+ *
10331
+ * Same arithmetic as {@link retryDue} — deliberately, so the two can never
10332
+ * disagree about when an account is back: this answers "at what instant", that
10333
+ * one answers "is that instant past". Two separate clocks would let the card
10334
+ * say "recovers at 14:05" while the ranking still refuses it at 14:06.
10335
+ *
10336
+ * `Infinity` when time cannot fix the account: a rejected token and a
10337
+ * restricted or banned account are states a cooldown cannot repair, so they
10338
+ * sort after everything that merely has to wait (`exclusionOf` gives them no
10339
+ * cooldown at all — this mirrors that, rather than inventing one).
10340
+ */
10341
+ function recoversAtOf(probe, excludedBy, fallbackMs = POOL_UNKNOWN_COOLDOWN_MS) {
10342
+ if (probe === void 0) return Number.POSITIVE_INFINITY;
10343
+ switch (excludedBy) {
10344
+ case "rate-limited":
10345
+ case "unavailable":
10346
+ case "failed": return probe.retryAtMs ?? probe.atMs + fallbackMs;
10347
+ case "model-busy": return probe.retryAtMs ?? probe.atMs + 12e4;
10348
+ case "out-of-credit": return probe.retryAtMs ?? Number.POSITIVE_INFINITY;
10349
+ default: return Number.POSITIVE_INFINITY;
10350
+ }
10351
+ }
10352
+ /**
10184
10353
  * Rank a pool's members best-first.
10185
10354
  *
10186
10355
  * The rule, in priority order — this is the whole feature:
@@ -10251,11 +10420,13 @@ function rankPool(members, nowMs, orderAccountIds) {
10251
10420
  _atRisk: (member.credits?.expiringSoon ?? 0) > 0,
10252
10421
  _expiringAmount: member.credits?.expiringSoon ?? 0,
10253
10422
  _expiring: member.credits?.nearestExpiryMs ?? Number.POSITIVE_INFINITY,
10254
- _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0
10423
+ _tokenExpiresAtMs: member.tokenExpiresAtMs ?? 0,
10424
+ _recoversAt: excludedBy === void 0 ? Number.POSITIVE_INFINITY : recoversAtOf(member.probe, excludedBy)
10255
10425
  };
10256
10426
  });
10257
10427
  rows.sort((left, right) => {
10258
10428
  if (left._usable !== right._usable) return left._usable ? -1 : 1;
10429
+ if (!left._usable && !right._usable && left._recoversAt !== right._recoversAt) return left._recoversAt - right._recoversAt;
10259
10430
  if (left._atRisk !== right._atRisk) return left._atRisk ? -1 : 1;
10260
10431
  if (left._order !== right._order) return left._order - right._order;
10261
10432
  if (left._atRisk && right._atRisk && left._expiring !== right._expiring) return left._expiring - right._expiring;
@@ -11036,18 +11207,24 @@ function knownProbeSource(value) {
11036
11207
  * The two writers describe the same account at different moments and carry
11037
11208
  * different fields:
11038
11209
  *
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.
11210
+ * - `test-batch` measures the TARGET MODEL deliberately, and it is the writer
11211
+ * that can attach the monthly refresh point (`retryAtMs` with
11212
+ * `retrySource: 'quota-refresh'`) — recorded as upstream evidence about the
11213
+ * PACKAGE's cycle, not as the moment the account becomes usable again.
11042
11214
  * - `live-request` reports what a real chat request just hit. It often carries
11043
11215
  * 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.
11216
+ * therefore DELETE that recorded point.
11045
11217
  *
11046
11218
  * Measured consequence of the spread, on a real `14018` account: the probe
11047
11219
  * 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.
11220
+ * record without that field, and the card then said the upstream gave no time at
11221
+ * all — while the correct value was in the file one write earlier.
11222
+ *
11223
+ * NOTE that recovery no longer follows from this field: credit exhaustion is
11224
+ * cleared by a later positive balance read, not by the timestamp passing (see
11225
+ * `reconcilePoolCredits` and `exclusionOf`). The point is inherited because it is
11226
+ * upstream evidence worth keeping, and losing it would silently downgrade a
11227
+ * recorded fact to "the upstream said nothing".
11051
11228
  *
11052
11229
  * So `retryAtMs` is INHERITED when the update does not state one, and every
11053
11230
  * other field is the update's (the newer measurement owns `outcome`, `atMs`,
@@ -11106,6 +11283,39 @@ async function writePoolProbes(region, updates) {
11106
11283
  });
11107
11284
  } catch {}
11108
11285
  }
11286
+ /**
11287
+ * 只有失败记录写入之后发起的余额查询,才能解除积分耗尽状态。
11288
+ * 持锁重读可避免较早的查询结果覆盖并发请求刚记录的新失败;其他异常保持原样。
11289
+ * 删除失败记录只表示余额恢复,不会伪造一次成功的模型测试。
11290
+ * 恢复后界面会显示“未测试”:这里删除的是最近失败记录,存储结构没有保留此前
11291
+ * 成功测试的历史,余额到账也不能证明某个模型可用;再次测试才会产生新的结论。
11292
+ */
11293
+ async function reconcilePoolCredits(region, readings) {
11294
+ const path = workbuddyPoolStorePath(region);
11295
+ try {
11296
+ return await withFileLock(path, async () => {
11297
+ const probes = await readPoolProbes(region);
11298
+ let changed = false;
11299
+ for (const reading of readings) {
11300
+ const probe = probes[reading.accountId];
11301
+ if (probe?.outcome !== "out-of-credit" || probe.atMs >= reading.startedAtMs) continue;
11302
+ if (!Number.isFinite(reading.total) || reading.total <= 0) continue;
11303
+ delete probes[reading.accountId];
11304
+ changed = true;
11305
+ }
11306
+ if (changed) await writeFileAtomic(path, `${JSON.stringify({
11307
+ version: STORE_FORMAT_VERSION$1,
11308
+ probes
11309
+ }, null, 2)}\n`, {
11310
+ mode: 384,
11311
+ dirMode: 448
11312
+ });
11313
+ return probes;
11314
+ });
11315
+ } catch {
11316
+ return readPoolProbes(region);
11317
+ }
11318
+ }
11109
11319
  //#endregion
11110
11320
  //#region src/auto-checkin.ts
11111
11321
  /**
@@ -11799,6 +12009,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11799
12009
  const imageToolEnabled = deps.imageToolEnabled?.(region) ?? false;
11800
12010
  const videoToolEnabled = deps.videoToolEnabled?.(region) ?? false;
11801
12011
  const preferredVideoModels = deps.preferredVideoModels?.(region) ?? {};
12012
+ const preferredImageModel = deps.preferredImageModel?.(region) ?? "";
11802
12013
  const cliBridgeEnabled = deps.cliBridgeEnabled?.() === true;
11803
12014
  const sidebarPanelEnabled = deps.sidebarPanelEnabled?.() === true;
11804
12015
  /**
@@ -11831,6 +12042,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11831
12042
  imageToolEnabled,
11832
12043
  videoToolEnabled,
11833
12044
  preferredVideoModels,
12045
+ preferredImageModel,
11834
12046
  cliBridgeEnabled,
11835
12047
  sidebarPanelEnabled,
11836
12048
  pollIntervalMs,
@@ -11857,6 +12069,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11857
12069
  imageToolEnabled,
11858
12070
  videoToolEnabled,
11859
12071
  preferredVideoModels,
12072
+ preferredImageModel,
11860
12073
  cliBridgeEnabled,
11861
12074
  sidebarPanelEnabled,
11862
12075
  pollIntervalMs,
@@ -11886,6 +12099,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11886
12099
  imageToolEnabled,
11887
12100
  videoToolEnabled,
11888
12101
  preferredVideoModels,
12102
+ preferredImageModel,
11889
12103
  cliBridgeEnabled,
11890
12104
  sidebarPanelEnabled,
11891
12105
  pollIntervalMs,
@@ -12858,6 +13072,22 @@ const regionStateConfig = z.object({
12858
13072
  enabledModelIds: z.array(z.string()).default([]),
12859
13073
  imageModelIds: z.array(z.string()).default([]),
12860
13074
  /**
13075
+ * Which text-to-image model this region uses, as picked in the card (issue #241).
13076
+ *
13077
+ * An EMPTY string means "no choice": the tool takes the group's first model,
13078
+ * which is whatever the upstream catalog lists first (`hunyuan-image-alpha` in
13079
+ * the CN region as of 2026-11-12). Set it to `hunyuan-image-v3.0` for output
13080
+ * with no watermark.
13081
+ *
13082
+ * Why a free string and not an enum: the watermark-free model is NOT in the
13083
+ * `/v3/config` catalog — it is the official CLI's own hard-coded fallback — so
13084
+ * an enum would have to hard-code a vendor id list that can change without
13085
+ * this plugin being released. The tool validates it against the choices it can
13086
+ * actually offer (`imageModelChoices`) and falls back silently when the id is
13087
+ * stale, exactly like `preferredVideoModels`.
13088
+ */
13089
+ 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)."),
13090
+ /**
12861
13091
  * Alternative CN gateway host (issue #220); see the interface field of the
12862
13092
  * same name. Empty = the built-in gateway.
12863
13093
  *
@@ -13459,7 +13689,10 @@ function apply(ctx, config) {
13459
13689
  reportRefusal: (report) => {
13460
13690
  recordRefusal(report);
13461
13691
  },
13462
- prepareAccount: () => applyPoolSelection(region),
13692
+ prepareAccount: async (signal) => {
13693
+ await refreshDepletedPoolCredits(region, signal);
13694
+ if (!signal?.aborted) await applyPoolSelection(region);
13695
+ },
13463
13696
  failoverAccount: (triedAccountIds) => failoverAccountFor(region, triedAccountIds),
13464
13697
  failoverShortfall: () => explainPoolShortfall(region),
13465
13698
  onAccountFailure: (accountId, failure) => {
@@ -13947,6 +14180,11 @@ function apply(ctx, config) {
13947
14180
  listMediaModels: (credential, signal) => client.fetchMediaModels(credential, signal),
13948
14181
  generateImage: (credential, request, signal) => client.generateImage(credential, request, signal),
13949
14182
  editImage: (credential, request, signal) => client.editImage(credential, request, signal),
14183
+ preferredImageModel: (credential, tag) => {
14184
+ if (tag !== "text-to-image") return void 0;
14185
+ const picked = regionStateOf(current(), regionOf(credential.domain)).preferredImageModel;
14186
+ return picked === void 0 || picked === "" ? void 0 : picked;
14187
+ },
13950
14188
  logger: ctx.logger
13951
14189
  })
13952
14190
  });
@@ -14017,7 +14255,7 @@ function apply(ctx, config) {
14017
14255
  });
14018
14256
  ctx.inject(["sessionProjections"], (projectionCtx) => {
14019
14257
  const reader = projectionCtx.sessionProjections;
14020
- if (reader === void 0 || typeof reader.stateOf !== "function") return;
14258
+ if (reader === void 0 || typeof reader.snapshot !== "function" && typeof reader.stateOf !== "function") return;
14021
14259
  /**
14022
14260
  * The one place the projection key is spelled out.
14023
14261
  *
@@ -14039,7 +14277,7 @@ function apply(ctx, config) {
14039
14277
  cliDirectoryOf = (session) => {
14040
14278
  let state;
14041
14279
  try {
14042
- state = reader.stateOf(session, WORKING_DIRECTORY_PROJECTION_KEY);
14280
+ state = readProjectedState(reader, session, WORKING_DIRECTORY_PROJECTION_KEY);
14043
14281
  } catch {
14044
14282
  return null;
14045
14283
  }
@@ -14236,6 +14474,13 @@ function apply(ctx, config) {
14236
14474
  */
14237
14475
  preferredVideoModels: (region) => regionStateOf(current(), region).preferredVideoModels ?? {},
14238
14476
  /**
14477
+ * The text-to-image model chosen per region, for the card's picker (issue
14478
+ * #241). Read from the committed value like the switches above, so the
14479
+ * picker shows what the TOOL will actually use rather than the browser's
14480
+ * stale mirror of this namespace.
14481
+ */
14482
+ preferredImageModel: (region) => regionStateOf(current(), region).preferredImageModel ?? "",
14483
+ /**
14239
14484
  * Whether the optional CodeBuddy CLI route is mounted (`codebuddy_ask` tool
14240
14485
  * + `/codebuddy` command).
14241
14486
  *
@@ -14297,11 +14542,11 @@ function apply(ctx, config) {
14297
14542
  * token: the route passes only model ids and receives only outcomes.
14298
14543
  *
14299
14544
  * `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.
14545
+ * the SAME credit answer the card displays. It is recorded beside an
14546
+ * out-of-credit result as upstream EVIDENCE, not as a recovery deadline:
14547
+ * check-in and top-ups can replenish credits long before it, so the views
14548
+ * name the replenishment action instead of rendering a countdown, and the
14549
+ * pool does not release the account when the moment passes.
14305
14550
  */
14306
14551
  async probeModels(region, modelIds, options) {
14307
14552
  let credential;
@@ -14459,17 +14704,18 @@ function apply(ctx, config) {
14459
14704
  * failure is simply omitted, which the card renders as unknown.
14460
14705
  */
14461
14706
  async checkedInToday(region) {
14462
- if (!poolPreferencesOf(current(), region).enabled) return {};
14707
+ if (region !== "cn" || !poolPreferencesOf(current(), region).enabled) return {};
14463
14708
  const store = stacks[region].store;
14464
14709
  const accounts = await store.accounts();
14465
14710
  const now = Date.now();
14466
14711
  const entries = await Promise.all(accounts.map(async (account) => {
14712
+ if (account.enterprise === true) return void 0;
14467
14713
  const cached = checkinStateCache[region]?.[account.id];
14468
14714
  if (cached !== void 0 && checkinReadingFresh(cached.atMs, now, CHECKIN_CACHE_MS)) return [account.id, cached.checkedIn];
14469
14715
  const credential = await store.credentialFor(account.id).catch(() => void 0);
14470
14716
  if (credential === void 0) return void 0;
14471
14717
  const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
14472
- if (status === void 0) return void 0;
14718
+ if (status === void 0 || !status.active) return void 0;
14473
14719
  checkinStateCache[region] = {
14474
14720
  ...checkinStateCache[region],
14475
14721
  [account.id]: {
@@ -14605,6 +14851,10 @@ function apply(ctx, config) {
14605
14851
  const cached = checkinStateCache[region];
14606
14852
  if (cached !== void 0) delete cached[row.accountId];
14607
14853
  }
14854
+ if (rows.some((row) => row.status !== "failed")) {
14855
+ await poolMembersOf(region);
14856
+ await applyPoolSelection(region);
14857
+ }
14608
14858
  return rows;
14609
14859
  },
14610
14860
  test: async (region, modelId, onRow) => {
@@ -14774,10 +15024,11 @@ function apply(ctx, config) {
14774
15024
  * The region's nearest monthly quota refresh, or undefined when unknown.
14775
15025
  *
14776
15026
  * 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.
15027
+ * expires and resets on a cycle, so its `refreshAtMs` is the package's own
15028
+ * schedule. It is handed to a probe as EVIDENCE to store beside an
15029
+ * out-of-credit outcome — never as the moment the account becomes usable
15030
+ * again, because check-in and top-ups can land first. A failure to read it is
15031
+ * not an error: a probe that records no refresh point is still a useful probe.
14781
15032
  */
14782
15033
  const quotaRefreshOf = async (region, credential) => {
14783
15034
  try {
@@ -14882,11 +15133,10 @@ function apply(ctx, config) {
14882
15133
  * without fetching one.
14883
15134
  *
14884
15135
  * 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.
15136
+ * member. Normal ranking reuses the last UI/check-in snapshot and omits stale
15137
+ * balances rather than fetching all members for each chat. The separate,
15138
+ * rate-limited recovery check reads only accounts with recorded credit
15139
+ * failures; it does not refresh this whole-pool ranking snapshot.
14890
15140
  */
14891
15141
  const creditsSnapshot = {};
14892
15142
  /** How long a credits reading may steer routing. */
@@ -14898,9 +15148,9 @@ function apply(ctx, config) {
14898
15148
  * the probe store, plus the credits snapshot when it is fresh.
14899
15149
  *
14900
15150
  * 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.
15151
+ * the network. `poolMembersOf` refreshes all members on explicit UI/check-in
15152
+ * paths. Before a request, `refreshDepletedPoolCredits` separately checks only
15153
+ * recorded credit failures, at most once per minute, even with no card open.
14904
15154
  */
14905
15155
  async function localPoolMembers(region) {
14906
15156
  const accounts = await poolMemberAccounts(region);
@@ -14921,6 +15171,64 @@ function apply(ctx, config) {
14921
15171
  });
14922
15172
  }
14923
15173
  /**
15174
+ * Recover depleted members without blocking requests that already have a usable
15175
+ * account. Concurrent callers share one balance read per region and minute.
15176
+ * When every member is excluded, a caller may wait for recovery; disconnecting
15177
+ * releases that caller without cancelling evidence needed by other requests.
15178
+ * Positive readings update existing ranking balances without extending the
15179
+ * lifetime of unrelated cached readings or overwriting a newer UI snapshot.
15180
+ */
15181
+ const depletedRefreshAt = {};
15182
+ const depletedRefreshInFlight = {};
15183
+ async function refreshDepletedPoolCredits(region, signal) {
15184
+ if (!poolPreferencesOf(current(), region).enabled || signal?.aborted) return;
15185
+ const members = await localPoolMembers(region);
15186
+ if (signal?.aborted) return;
15187
+ let task = depletedRefreshInFlight[region];
15188
+ if (task === void 0 && Date.now() >= (depletedRefreshAt[region] ?? 0)) {
15189
+ const depleted = members.filter((member) => member.probe?.outcome === "out-of-credit");
15190
+ if (depleted.length === 0) return;
15191
+ depletedRefreshAt[region] = Date.now() + 6e4;
15192
+ task = (async () => {
15193
+ const completed = (await Promise.all(depleted.map(async (member) => {
15194
+ const credential = await stacks[region].store.credentialFor(member.account.id).catch(() => void 0);
15195
+ if (credential === void 0) return void 0;
15196
+ const startedAtMs = Date.now();
15197
+ const credits = await client.fetchCredits(credential).catch(() => void 0);
15198
+ return credits === void 0 ? void 0 : {
15199
+ accountId: member.account.id,
15200
+ startedAtMs,
15201
+ total: credits.total,
15202
+ credits
15203
+ };
15204
+ }))).filter((reading) => reading !== void 0);
15205
+ await reconcilePoolCredits(region, completed);
15206
+ const snapshot = creditsSnapshot[region];
15207
+ if (snapshot !== void 0) {
15208
+ const updated = new Map(snapshot);
15209
+ for (const reading of completed) if ((creditsSnapshotAt[region] ?? 0) <= reading.startedAtMs) updated.set(reading.accountId, reading.credits);
15210
+ creditsSnapshot[region] = updated;
15211
+ }
15212
+ })().catch((error) => {
15213
+ ctx.logger.warn("dsh-connect-workbuddy: pool credit recovery failed", error);
15214
+ }).finally(() => {
15215
+ delete depletedRefreshInFlight[region];
15216
+ });
15217
+ depletedRefreshInFlight[region] = task;
15218
+ }
15219
+ if (task === void 0 || members.some((member) => exclusionOf(member.probe, Date.now()) === void 0)) return;
15220
+ if (signal === void 0) return task;
15221
+ await new Promise((resolve) => {
15222
+ const finish = () => {
15223
+ signal.removeEventListener("abort", finish);
15224
+ resolve();
15225
+ };
15226
+ signal.addEventListener("abort", finish, { once: true });
15227
+ if (signal.aborted) finish();
15228
+ task.then(finish, finish);
15229
+ });
15230
+ }
15231
+ /**
14924
15232
  * Record a failure a LIVE request hit, so the NEXT request starts from a
14925
15233
  * usable account.
14926
15234
  *
@@ -14937,23 +15245,13 @@ function apply(ctx, config) {
14937
15245
  * sideline a good account over a bad body.
14938
15246
  *
14939
15247
  * 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.
15248
+ * 「将在 … 重置」 — which `cooldownOf` parses. Transient failures with no stated
15249
+ * time use the local short window; credit exhaustion requires balance evidence.
15250
+ *
15251
+ * The monthly package refresh is retained as upstream evidence, not as the
15252
+ * earliest recovery date: check-in and purchases can replenish credits sooner.
15253
+ * A later positive balance reading clears an older credit failure under the
15254
+ * store lock, without overwriting failures recorded during the query.
14957
15255
  *
14958
15256
  * The upstream's text is persisted alongside the outcome so the card can name
14959
15257
  * the reason. It is REDACTED first because this message is a raw upstream body:
@@ -15046,10 +15344,17 @@ function apply(ctx, config) {
15046
15344
  async function poolMembersOf(region) {
15047
15345
  const store = stacks[region].store;
15048
15346
  const accounts = await poolMemberAccounts(region);
15049
- const probes = await readPoolProbes(region);
15347
+ const recordedProbes = await readPoolProbes(region);
15348
+ const creditReadings = [];
15050
15349
  const rows = await Promise.all(accounts.map(async (account) => {
15051
15350
  const credential = await store.credentialFor(account.id).catch(() => void 0);
15351
+ const startedAtMs = Date.now();
15052
15352
  const credits = credential === void 0 ? void 0 : await client.fetchCredits(credential).catch(() => void 0);
15353
+ if (credits !== void 0) creditReadings.push({
15354
+ accountId: account.id,
15355
+ startedAtMs,
15356
+ total: credits.total
15357
+ });
15053
15358
  return {
15054
15359
  account: {
15055
15360
  id: account.id,
@@ -15061,13 +15366,16 @@ function apply(ctx, config) {
15061
15366
  expiringSoon: credits.expiringSoon,
15062
15367
  ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
15063
15368
  } },
15064
- ...probes[account.id] === void 0 ? {} : { probe: probes[account.id] },
15065
15369
  tokenExpiresAtMs: account.tokenExpiresAtMs
15066
15370
  };
15067
15371
  }));
15372
+ const probes = creditReadings.some((reading) => recordedProbes[reading.accountId]?.outcome === "out-of-credit") ? await reconcilePoolCredits(region, creditReadings) : recordedProbes;
15068
15373
  creditsSnapshot[region] = new Map(rows.filter((row) => row.credits !== void 0).map((row) => [row.account.id, row.credits]));
15069
15374
  creditsSnapshotAt[region] = Date.now();
15070
- return rows;
15375
+ return rows.map((row) => ({
15376
+ ...row,
15377
+ ...probes[row.account.id] === void 0 ? {} : { probe: probes[row.account.id] }
15378
+ }));
15071
15379
  }
15072
15380
  /**
15073
15381
  * The model a per-row test would use right now: the SAME resolution the
@@ -15237,6 +15545,10 @@ function apply(ctx, config) {
15237
15545
  const cached = checkinStateCache[region];
15238
15546
  if (cached !== void 0) delete cached[row.accountId];
15239
15547
  }
15548
+ if (rows.some((row) => row.status !== "failed")) {
15549
+ await poolMembersOf(region);
15550
+ await applyPoolSelection(region);
15551
+ }
15240
15552
  const folded = foldAttempt(state, rows, nowMs, targets.length + state.doneAccountIds.length);
15241
15553
  autoCheckinState[region] = folded;
15242
15554
  await writeAutoCheckinState(region, folded);