dsh-connect-workbuddy 5.17.0 → 5.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as WorkBuddyCredentialRejectedError, A as WORKBUDDY_AUTH_FILENAME, At as VIDEO_TAG_TEXT_TO_VIDEO, B as isEncryptedCredentialError, Bt as imageDataUrl, C as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Cn as writeFileAtomic, Ct as defaultOffModelIds, D as fallbackModelsFor, Dt as recordRefusal, E as deriveCatalog, Et as offRefused, F as authFileName, Ft as DEFAULT_IMAGE_SIZE, G as workbuddyAccountId, Gt as sniffImageMime, H as legacyWorkbuddyOwnAuthPath, Ht as isBareBase64Image, I as defaultDesktopAuthCandidates, It as IMAGE_TAG_IMAGE_TO_IMAGE, J as APP_VERSION, Jt as pruneTempDir, K as workbuddyOwnAuthPath, Kt as parseQueueAnswer, L as defaultDesktopAuthDirs, Lt as IMAGE_TAG_TEXT_TO_IMAGE, Mt as parseSupportedSecondsRange, N as WorkBuddyCredentialStore, Nt as pickVideoModel, O as withoutRouters, Ot as withEffectiveOff, P as WorkBuddyEncryptedCredentialError, Pt as resolveVideoParams, Q as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, R as defaultDesktopAuthPath, Rt as MAX_INPUT_IMAGE_BYTES, S as FALLBACK_WORKBUDDY_MODELS, Sn as withFileLock, St as REFUSES_OFF_MODEL_IDS, T as applyContextBudgets, Tt as offDefaultFor, U as parseWorkBuddyAuth, Ut as parseImageDataUrl, V as isVaultAccountId, Vt as imageMimeForPath, W as preferredAccountName, Wt as pickMediaModel, X as CREDENTIAL_REJECTED_CODE, Xt as imageDefaultFor, Y as CONTEXT_OVERFLOW_MARKER, Yt as NATIVE_MODALITY_BY_MODEL_ID, Zt as nativeModalityOf, _ as isDeviceMode, _n as openEncryptedField, _t as prepareChatBody, a as readHostHeartbeat, at as forceNeutralHead, b as saveDeviceSdkSettings, bt as rewriteSessionTitleModel, c as WORKBUDDY_CONNECT_VERSION, cn as deriveAtRestKey, ct as isCredentialRejectedError, dn as findWorkbuddyAppExecutable, dt as modelIdOfBody, et as WorkBuddyUpstreamClient, f as piAiRuntimeInfo, ft as openingEvidenceOfBody, g as describeDerivedDevices, gn as macosNestedAppBundles, gt as perturbChannelFingerprints, h as createDeviceProfileLookup, hn as macosBundleExecutable, ht as parseUpstreamModel, i as processStartTimeMs, j as WORKBUDDY_AUTH_FILE_ENV, jt as WorkBuddyVideoError, k as ENCRYPTED_CREDENTIAL_CODE, kt as VIDEO_TAG_IMAGE_TO_VIDEO, l as createFileRosterSeenStore, ln as deriveAtRestKeyId, lt as isFirstMessageGateBody, m as createTuringSdk, mn as isWorkbuddyBundle, mt as parseReasoning, n as clearHostHeartbeat, nt as classifyUpstreamError, o as workbuddyHostHeartbeatPath, on as WORKBUDDY_APP_EXECUTABLE_ENV, ot as isContextTooLongBody, p as createDeviceSdkPort, pn as isEncryptedFieldWrapper, pt as parseCreditMultiplier, qt as queueNoticeText, r as isHeartbeatProcessAlive, rn as isDeviceId, rt as declaredTools, s as writeHostHeartbeat, sn as clearAtRestKeyCache, st as isConversationIdGateBody, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as channelGateMemberOf, un as fetchAtRestKeyPayload, ut as knownRegionOf, v as readDeviceSettings, vn as readAtRestKey, vt as regionOf, w as WorkBuddyCatalog, wt as lastRefusalFor, x as setDeviceMode, xn as resolveDshHome, xt as attachBusyLevels, y as saveDeviceProfile, yn as workbuddyAppExecutableCandidates, yt as requestEvidenceOf, z as hasEncryptedCredentialFields, zt as WorkBuddyImageError } from "./host-heartbeat-09tOJATV.js";
1
+ import { $ as WorkBuddyCredentialRejectedError, A as WORKBUDDY_AUTH_FILENAME, At as VIDEO_TAG_TEXT_TO_VIDEO, B as isEncryptedCredentialError, Bt as imageMimeForPath, C as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Ct as defaultOffModelIds, D as fallbackModelsFor, Dt as recordRefusal, E as deriveCatalog, Et as offRefused, F as authFileName, Ft as IMAGE_TAG_IMAGE_TO_IMAGE, G as workbuddyAccountId, Gt as parseQueueAnswer, H as legacyWorkbuddyOwnAuthPath, Ht as parseImageDataUrl, I as defaultDesktopAuthCandidates, It as IMAGE_TAG_TEXT_TO_IMAGE, J as APP_VERSION, Jt as NATIVE_MODALITY_BY_MODEL_ID, K as workbuddyOwnAuthPath, Kt as queueNoticeText, L as defaultDesktopAuthDirs, Lt as MAX_INPUT_IMAGE_BYTES, Mt as parseSupportedSecondsRange, N as WorkBuddyCredentialStore, Nt as pickVideoModel, O as withoutRouters, Ot as withEffectiveOff, P as WorkBuddyEncryptedCredentialError, Pt as resolveVideoParams, Q as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, R as defaultDesktopAuthPath, Rt as WorkBuddyImageError, S as FALLBACK_WORKBUDDY_MODELS, Sn as writeFileAtomic, St as REFUSES_OFF_MODEL_IDS, T as applyContextBudgets, Tt as offDefaultFor, U as parseWorkBuddyAuth, Ut as pickMediaModel, V as isVaultAccountId, Vt as isBareBase64Image, W as preferredAccountName, Wt as sniffImageMime, X as CREDENTIAL_REJECTED_CODE, Xt as nativeModalityOf, Y as CONTEXT_OVERFLOW_MARKER, Yt as imageDefaultFor, _ as isDeviceMode, _n as readAtRestKey, _t as prepareChatBody, a as readHostHeartbeat, an as WORKBUDDY_APP_EXECUTABLE_ENV, at as forceNeutralHead, b as saveDeviceSdkSettings, bn as resolveDshHome, bt as rewriteSessionTitleModel, c as WORKBUDDY_CONNECT_VERSION, cn as deriveAtRestKeyId, ct as isCredentialRejectedError, dt as modelIdOfBody, et as WorkBuddyUpstreamClient, f as piAiRuntimeInfo, fn as isEncryptedFieldWrapper, ft as openingEvidenceOfBody, g as describeDerivedDevices, gn as openEncryptedField, gt as perturbChannelFingerprints, h as createDeviceProfileLookup, hn as macosNestedAppBundles, ht as parseUpstreamModel, i as processStartTimeMs, j as WORKBUDDY_AUTH_FILE_ENV, jt as WorkBuddyVideoError, k as ENCRYPTED_CREDENTIAL_CODE, kt as VIDEO_TAG_IMAGE_TO_VIDEO, l as createFileRosterSeenStore, ln as fetchAtRestKeyPayload, lt as isFirstMessageGateBody, m as createTuringSdk, mn as macosBundleExecutable, mt as parseReasoning, n as clearHostHeartbeat, nn as isDeviceId, nt as classifyUpstreamError, o as workbuddyHostHeartbeatPath, on as clearAtRestKeyCache, ot as isContextTooLongBody, p as createDeviceSdkPort, pn as isWorkbuddyBundle, pt as parseCreditMultiplier, qt as pruneTempDir, r as isHeartbeatProcessAlive, rt as declaredTools, s as writeHostHeartbeat, sn as deriveAtRestKey, st as isConversationIdGateBody, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as channelGateMemberOf, un as findWorkbuddyAppExecutable, ut as knownRegionOf, v as readDeviceSettings, vn as workbuddyAppExecutableCandidates, vt as regionOf, w as WorkBuddyCatalog, wt as lastRefusalFor, x as setDeviceMode, xn as withFileLock, xt as attachBusyLevels, y as saveDeviceProfile, yt as requestEvidenceOf, z as hasEncryptedCredentialFields, zt as imageDataUrl } from "./host-heartbeat-DFqDsnte.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";
@@ -248,7 +248,7 @@ function isUnconfiguredFallbackSnapshot(saved, region) {
248
248
  const fallbackIds = fallback.map((model) => model.id);
249
249
  const savedIds = saved.map((model) => model.id);
250
250
  if (!fallbackIds.every((id, index) => id === savedIds[index])) return false;
251
- return saved.every((model) => model.reasoning === void 0);
251
+ return saved.every((model) => model.reasoning === void 0 && model.creditMultiplier === void 0);
252
252
  }
253
253
  /**
254
254
  * The roster the runtime serves for a region.
@@ -1182,10 +1182,13 @@ const THINKING_LEVELS$1 = [
1182
1182
  /**
1183
1183
  * The tier this bundle assumed before issue #179, and the last-resort fallback.
1184
1184
  *
1185
- * Kept as the final fallback rather than becoming dead: a model that declares
1186
- * `canDisableThinking` only (no tier list) still needs an explicit tier the way
1187
- * it always did, and #83's fix — never leave the choice to pi-ai — must survive
1188
- * this feature.
1185
+ * Kept alive as the ROUTE-WIDE dispatch fallback in `profileFor` (issue #83's
1186
+ * fix — never leave the choice to pi-ai — must survive this feature). It is
1187
+ * deliberately NOT part of `defaultEffortFor` any more: it is a single constant
1188
+ * for a roster whose vocabularies disagree, so as a per-model default it can
1189
+ * name a tier a model does not declare (host: UNSUPPORTED_REASONING_EFFORT), or
1190
+ * one that is NOT the tier the upstream declared as that model's default. The
1191
+ * per-model answer is resolved by `defaultEffortFor` instead.
1189
1192
  */
1190
1193
  const WORKBUDDY_DEFAULT_EFFORT = "high";
1191
1194
  /**
@@ -1205,7 +1208,8 @@ function declaredEfforts(reasoning) {
1205
1208
  *
1206
1209
  * @param model - the catalog entry, carrying the upstream's own declaration.
1207
1210
  * @param saved - the user's per-model choice, keyed by model id; an absent (or
1208
- * unsupported, or stale) entry falls through to the upstream default.
1211
+ * unsupported, or stale) entry falls through to the upstream default, then to
1212
+ * this model's own MIDDLE tier (never its weakest one).
1209
1213
  * @returns a tier the model declares, or `undefined` when it declares none — in
1210
1214
  * which case the adapter's existing `off` normalization (issue #90) is still
1211
1215
  * the right answer and this module must not invent one.
@@ -1217,8 +1221,7 @@ function defaultEffortFor(model, saved = {}) {
1217
1221
  if (typeof asked === "string" && declared.includes(asked)) return asked;
1218
1222
  const upstreamDefault = model.reasoning?.defaultEffort;
1219
1223
  if (typeof upstreamDefault === "string" && declared.includes(upstreamDefault)) return upstreamDefault;
1220
- if (declared.includes("high")) return WORKBUDDY_DEFAULT_EFFORT;
1221
- return declared[0];
1224
+ return declared[Math.floor(declared.length / 2)];
1222
1225
  }
1223
1226
  //#endregion
1224
1227
  //#region src/adapter.ts
@@ -3417,6 +3420,9 @@ const BLOCK_TAGS = ["tool_calls", "invoke"];
3417
3420
  * should also remove everything up to its matching close. An INVENTED name is
3418
3421
  * not here on purpose: `<|DSML| validate>` brackets nothing, so removing it
3419
3422
  * means removing the tag and nothing else.
3423
+ *
3424
+ * `calls` is here because a REAL capture wrote the wrapper's closer that way.
3425
+ * See {@link CANONICAL_TAG_NAMES} for the defect that disagreement caused.
3420
3426
  */
3421
3427
  const KEYWORD_TAGS = [
3422
3428
  "tool_calls",
@@ -3427,11 +3433,31 @@ const KEYWORD_TAGS = [
3427
3433
  "calls",
3428
3434
  "tool"
3429
3435
  ];
3430
- /** Tag names normalised to their canonical spelling. */
3436
+ /**
3437
+ * Tag names normalised to their canonical spelling.
3438
+ *
3439
+ * WHY `calls` IS MAPPED HERE (issue #207). Pairing is decided by comparing the
3440
+ * NORMALISED names ({@link findMatchingClose}: `tag.name === open.name`), so a
3441
+ * closer spelled `calls` could never match an opener spelling `tool_calls`:
3442
+ * the block read as never closed, was held to end of stream, and gate 4 then
3443
+ * rolled the whole thing back into visible prose.
3444
+ *
3445
+ * That is not a hypothetical spelling. `docs/DSML-LEAK-RESEARCH.md` records a
3446
+ * REAL captured block whose closing tag is `</|DSML|| calls>` — the document
3447
+ * knew the closer could be abbreviated while this table did not. The two
3448
+ * spellings are also inconsistent WITHIN this file: {@link KEYWORD_TAGS}
3449
+ * already lists `calls`, because {@link stripMarkup} has to know it is markup,
3450
+ * while pairing did not. Two tables disagreeing about one spelling was the
3451
+ * whole defect.
3452
+ *
3453
+ * `git log -S"'calls', 'tool_calls'"` is empty: this mapping never existed, so
3454
+ * no release ever behaved differently.
3455
+ */
3431
3456
  const CANONICAL_TAG_NAMES = /* @__PURE__ */ new Map([
3432
3457
  ["tool_calls", "tool_calls"],
3433
3458
  ["tool-calls", "tool_calls"],
3434
3459
  ["toolcalls", "tool_calls"],
3460
+ ["calls", "tool_calls"],
3435
3461
  ["invoke", "invoke"],
3436
3462
  ["parameter", "parameter"]
3437
3463
  ]);
@@ -3440,8 +3466,17 @@ const CANONICAL_TAG_NAMES = /* @__PURE__ */ new Map([
3440
3466
  *
3441
3467
  * `<toolcalls>` without the marker is somebody's HTML, not the model's markup;
3442
3468
  * the marker is what makes the misspelling meaningful.
3469
+ *
3470
+ * `calls` belongs here for the same reason, and more strongly: it is an ordinary
3471
+ * English word that also appears in HTML (`<calls>`) and in prose about
3472
+ * telephones, so normalising a BARE `<calls>` would turn somebody's own text
3473
+ * into the model's protocol and start deleting what follows it.
3443
3474
  */
3444
- const MARKER_ONLY_TAG_NAMES = /* @__PURE__ */ new Set(["tool-calls", "toolcalls"]);
3475
+ const MARKER_ONLY_TAG_NAMES = /* @__PURE__ */ new Set([
3476
+ "tool-calls",
3477
+ "toolcalls",
3478
+ "calls"
3479
+ ]);
3445
3480
  /** Fence markers at the start of a line. */
3446
3481
  const FENCE_MARKERS = ["```", "~~~"];
3447
3482
  /**
@@ -4023,6 +4058,77 @@ function stripStray(text, seen) {
4023
4058
  return cleaned;
4024
4059
  }
4025
4060
  /**
4061
+ * Drop lone marker CLOSERS from a response that never opened a block
4062
+ * (issue #207).
4063
+ *
4064
+ * THE DEFECT. `stripStray` runs only behind {@link DsmlStreamBuffer.debris()},
4065
+ * and that flag means "this response WITHHELD a block". A response that never
4066
+ * opened one therefore never reached the sweep, so the shape below — captured
4067
+ * in the wild, and quoted verbatim in the issue — went out as prose:
4068
+ *
4069
+ * ```text
4070
+ * </|DSML| parameter>
4071
+ * </|DSML| invoke>
4072
+ * </|DSML| calls>
4073
+ * ```
4074
+ *
4075
+ * The inconsistency was inside the module: {@link hasProse} already classified
4076
+ * those bytes as NON-prose (it goes through `stripMarkup`), so the classifier
4077
+ * said "residue" and the writer printed it.
4078
+ *
4079
+ * WHY PRESENCE, NOT DEPTH PAIRING. The first two attempts at this (both
4080
+ * recorded in the issue) counted depth by tag name, and both deleted the
4081
+ * CLOSER OF A BLOCK THAT WAS ONLY BEING SHOWN: a gate-4-refused block's opener
4082
+ * can be a forged name (`<|DSML| validate>`), which by name never matches its
4083
+ * own `</|DSML| calls>` closer, so the depth hit zero early. A presence flag
4084
+ * cannot make that mistake: if ANY marked opener appeared in the response, not
4085
+ * one lone closer is touched, and the whole gate-4 verbatim guarantee is kept.
4086
+ *
4087
+ * THE RESULT IS STRICTER THAN BEFORE, not looser. The old rule was "once a
4088
+ * block was withheld, delete every stray tag afterwards"; this one is "delete
4089
+ * nothing if any opener was ever seen". In the overlap — withheld block, then
4090
+ * lone tags — the old code deleted and this one does not.
4091
+ *
4092
+ * Fences and code spans are still skipped (through `stripMarkup`), because a
4093
+ * user asking what this markup means is quoting it on purpose.
4094
+ */
4095
+ function stripLoneClosers(text, seen, openerSeen) {
4096
+ if (openerSeen) return text;
4097
+ const cleaned = stripMarkup(text);
4098
+ if (cleaned !== text) seen.reason ??= "stray-markup";
4099
+ return cleaned;
4100
+ }
4101
+ /**
4102
+ * Does `text` contain any MARKED OPENING tag, whatever it is called?
4103
+ *
4104
+ * The question behind issue #207's presence flag. Keyed on the marker rather
4105
+ * than on {@link BLOCK_TAGS}, because the shape that motivated it —
4106
+ * `<|DSML| validate>` — wears an invented name and is not a block opener, yet
4107
+ * it opens a construct whose closer must survive.
4108
+ *
4109
+ * Scans outside fenced/inline-code spans, so a user quoting the markup inside a
4110
+ * code block does not set the flag (and therefore does not disable the cleaning
4111
+ * of real debris elsewhere in the same response).
4112
+ */
4113
+ function hasMarkedOpener(text) {
4114
+ const spans = ignoredSpans(text);
4115
+ const cursor = { at: 0 };
4116
+ let index = 0;
4117
+ while (index < text.length) {
4118
+ const skipped = skipIgnored(spans, index, cursor);
4119
+ if (skipped !== index) {
4120
+ index = skipped;
4121
+ continue;
4122
+ }
4123
+ if (text.charAt(index) === "<") {
4124
+ const tag = scanTag(text, index);
4125
+ if (tag !== void 0 && tag.marked && !tag.closing) return true;
4126
+ }
4127
+ index += 1;
4128
+ }
4129
+ return false;
4130
+ }
4131
+ /**
4026
4132
  * Drop a marker-bearing tag fragment that the stream held and can never finish.
4027
4133
  *
4028
4134
  * {@link holdFrom} keeps back a tail that could still become a block opener, so
@@ -4195,9 +4301,51 @@ var DsmlStreamBuffer = class {
4195
4301
  withheldOnce = false;
4196
4302
  /** Whether the one notice allowed per response has gone out. See `takeWithheld`. */
4197
4303
  noticeSent = false;
4304
+ /**
4305
+ * Whether this response has produced any MARKED opening tag, at any point
4306
+ * (issue #207).
4307
+ *
4308
+ * Deliberately NOT the same flag as {@link withheldOnce}. `withheldOnce` means
4309
+ * "a block was removed", and the debris sweep used it as a PROXY for "this
4310
+ * response's marker text is protocol debris rather than the answer". The two
4311
+ * are not the same question, and a response that leaked lone closers without
4312
+ * ever withholding a block was the case that fell between them:
4313
+ * `hasProse()` already counted those closers as non-prose (it runs
4314
+ * `stripMarkup`), while the output path forwarded them — the classifier said
4315
+ * "residue" and the writer said "text".
4316
+ *
4317
+ * Deliberately ANY marked opener rather than a {@link BLOCK_TAGS} one: the
4318
+ * captured shape `<|DSML| validate>` wears an invented name, so it is not a
4319
+ * block opener and would not set a block-only flag — yet it is precisely the
4320
+ * tag whose closer a name-based sweep would mutilate. "The model started
4321
+ * writing protocol markup" is the question, and that is answered by the
4322
+ * MARKER, not by the name.
4323
+ *
4324
+ * Tracked across chunks because a chunk boundary is not a response boundary.
4325
+ */
4326
+ openerSeen = false;
4198
4327
  constructor(gate) {
4199
4328
  this.gate = gate;
4200
4329
  }
4330
+ /**
4331
+ * Stop recovering calls, but keep cleaning the text (issue #207).
4332
+ *
4333
+ * Called when the upstream has already produced a STRUCTURED call. The reason
4334
+ * to stand down is sound — recovering markup into a second call channel after
4335
+ * the client already got a real one hands it two answers to the same question
4336
+ * — but the shim used to implement it by bypassing this buffer entirely, so
4337
+ * "no more calls" silently became "no more cleaning either" and every marker
4338
+ * after the native call went out as prose.
4339
+ *
4340
+ * Scrub mode keeps the text half: blocks are still located and removed, but
4341
+ * {@link parseBlock} is never consulted, so no call can be produced. Removal
4342
+ * is reported as debris rather than tallied as a withheld invocation — see
4343
+ * {@link scrubPending}.
4344
+ */
4345
+ standDown() {
4346
+ this.nativeCalls = true;
4347
+ }
4348
+ nativeCalls = false;
4201
4349
  /** Feed one `delta.content` chunk; returns text and any call it completed. */
4202
4350
  add(chunk) {
4203
4351
  this.pending += chunk;
@@ -4212,9 +4360,18 @@ var DsmlStreamBuffer = class {
4212
4360
  withheld: false
4213
4361
  };
4214
4362
  }
4363
+ this.openerSeen ||= hasMarkedOpener(this.pending);
4215
4364
  for (;;) {
4216
4365
  const found = findFirstOpener(this.pending, ignoredSpans(this.pending));
4217
4366
  if (found === void 0) break;
4367
+ this.openerSeen = true;
4368
+ if (this.nativeCalls) {
4369
+ const head = stripMarkup(this.pending.slice(0, found.open.start)).trimEnd();
4370
+ if (head !== "") parts.push(head);
4371
+ this.pending = this.pending.slice(found.close === void 0 ? found.open.start : found.close.end + 1);
4372
+ if (found.close === void 0) return finish(parts, calls, this.takeWithheld());
4373
+ continue;
4374
+ }
4218
4375
  const head = this.stripDebris(this.pending.slice(0, found.open.start));
4219
4376
  if (head !== "") parts.push(head);
4220
4377
  if (found.close === void 0) {
@@ -4243,9 +4400,9 @@ var DsmlStreamBuffer = class {
4243
4400
  this.withHeld.reason ??= "unnamed-invoke";
4244
4401
  text = "";
4245
4402
  }
4246
- if (this.debris()) {
4247
- text = dropUnfinishedMarkerTail(text, this.withHeld);
4248
- text = stripStray(text, this.withHeld);
4403
+ if (this.openerSeen || this.debris()) {
4404
+ text = dropUnfinishedMarkerTail(text, this.nativeCalls ? {} : this.withHeld);
4405
+ text = this.nativeCalls ? stripMarkup(text) : stripLoneClosers(text, this.withHeld, this.openerSeen);
4249
4406
  }
4250
4407
  const state = this.takeWithheld();
4251
4408
  const outcome = {
@@ -4257,13 +4414,26 @@ var DsmlStreamBuffer = class {
4257
4414
  return outcome;
4258
4415
  }
4259
4416
  /**
4260
- * Apply the debris sweep, but only to a response that has withheld something.
4417
+ * Apply the debris sweep, but only where it is provably debris.
4418
+ *
4419
+ * Three states, in order:
4261
4420
  *
4262
- * See {@link withheldOnce}: before the first withhold, marker text in the
4263
- * prose is the caller's to show, not this layer's to delete.
4421
+ * - SCRUB MODE (issue #207): nothing is being recovered, so every
4422
+ * marker-bearing tag is debris by definition.
4423
+ * - A block was withheld: the text left around removed blocks is residue by
4424
+ * construction, so the full sweep applies.
4425
+ * - Nothing was withheld AND no opener ever appeared: only lone CLOSERS are
4426
+ * unambiguously debris — this is the case the issue reports, where the
4427
+ * old proxy (`debris()`) could never be true and the bytes went out raw.
4428
+ *
4429
+ * A response that never withheld anything but DID open a block keeps its text
4430
+ * untouched: gate 4 promises the refused block is shown verbatim, and its
4431
+ * forged-name opener is exactly the shape a name-based sweep would mutilate.
4264
4432
  */
4265
4433
  stripDebris(text) {
4266
- return this.debris() ? stripStray(text, this.withHeld) : text;
4434
+ if (this.nativeCalls) return stripMarkup(text);
4435
+ if (this.debris()) return stripStray(text, this.withHeld);
4436
+ return stripLoneClosers(text, this.withHeld, this.openerSeen);
4267
4437
  }
4268
4438
  /** Has anything been withheld from this response, yet or already? */
4269
4439
  debris() {
@@ -4832,6 +5002,7 @@ var RecoveryStream = class {
4832
5002
  const nativeCalls = delta["tool_calls"];
4833
5003
  if (Array.isArray(nativeCalls) && nativeCalls.length > 0) {
4834
5004
  this.nativeCallsSeen = true;
5005
+ this.buffer?.standDown();
4835
5006
  this.windowOpened = true;
4836
5007
  this.flushNotice();
4837
5008
  this.send(frame, false);
@@ -4846,7 +5017,7 @@ var RecoveryStream = class {
4846
5017
  this.send(frame, reason !== "");
4847
5018
  return;
4848
5019
  }
4849
- if (this.buffer === void 0 || this.nativeCallsSeen) {
5020
+ if (this.buffer === void 0) {
4850
5021
  this.windowOpened = true;
4851
5022
  this.flushNotice();
4852
5023
  this.closeWindow();
@@ -5118,9 +5289,20 @@ function clippedUpstreamText(text, limit) {
5118
5289
  * later turn will fail the same way until that line is changed.
5119
5290
  *
5120
5291
  * Each entry also says whether the plugin's own neutralisation already covers
5121
- * it. An entry marked "not in the plugin's list" is the actionable one: that
5122
- * opening goes on the wire verbatim, so either the host wrote it or the
5123
- * gateway's list grew.
5292
+ * it. An entry marked "not in the plugin's list" is the actionable one: either
5293
+ * the host wrote it or the gateway's list grew.
5294
+ *
5295
+ * WHAT THAT MARKER MAY NOT SAY (issue #213). It used to read 「网关可能新增了
5296
+ * 词条」, and a reporter read it as "this opening went out verbatim" — then
5297
+ * reported that the three `assistant` openings the gate had named were never
5298
+ * neutralised at all. They were: `forceNeutralHead` puts the head in front of
5299
+ * every scanned opening regardless of the list (since 4.15.1), so the request
5300
+ * that was refused for the third time had heads on all of them. The marker
5301
+ * describes the FIRST attempt and only the opening's FIRST LINE; the gateway
5302
+ * matches an exact substring anywhere in the text, so a first line that is
5303
+ * absent from the snapshot says nothing about the message as a whole. Both of
5304
+ * those are stated in the reply's closing sentence, which is the part a
5305
+ * reporter actually quotes back at us.
5124
5306
  *
5125
5307
  * Capped at {@link CHANNEL_EVIDENCE_LIMIT} entries: a session can carry dozens
5126
5308
  * of system/assistant messages, and a wall of them would bury the one that
@@ -5131,7 +5313,7 @@ function channelEvidenceText(bodyJson) {
5131
5313
  if (entries.length === 0) return "(请求里没有可读的 system 或 assistant 消息开头。)";
5132
5314
  const shown = entries.slice(0, CHANNEL_EVIDENCE_LIMIT);
5133
5315
  const rendered = shown.map((entry) => {
5134
- const label = entry.neutralized ? "(插件已加中性头)" : "(不在插件已知名单里,网关可能新增了词条)";
5316
+ const label = entry.neutralized ? "(插件已加中性头)" : "(不在插件已知名单里,仅指首行)";
5135
5317
  const span = entry.closing === void 0 ? `,共 ${entry.textLength} 字` : `,首尾为「${entry.closing}」,共 ${entry.textLength} 字`;
5136
5318
  return `「${entry.role}:${entry.opening}${span}」${label}`;
5137
5319
  }).join("、");
@@ -5706,7 +5888,7 @@ function createWorkBuddyShim(options) {
5706
5888
  const said = detail?.rawMsg ?? detail?.displayMsg;
5707
5889
  const echo = said === void 0 ? "" : `上游的 msg 是「${said}」,`;
5708
5890
  const memberNote = member === "headers" ? `${echo}但本次请求已经带上了会话 id 三件套(X-Conversation-ID / -Request-ID / -Message-ID),所以这条措辞是上游误报;` : member === "first_message" ? `${echo}但本次请求的首条消息就是 system;` : member === "prompt" ? isConversationIdGateBody(result.message) ? `${echo}但本次请求已经带上了会话 id 三件套(X-Conversation-ID / -Request-ID / -Message-ID),所以这条措辞是上游误报,实际被拒的是请求内容;` : isFirstMessageGateBody(result.message) ? `${echo}但本次请求的首条消息就是 system,所以这条措辞是上游误报,实际被拒的是请求内容;` : "" : `${echo}它属于 11128 这一族但没点名是哪一道门,插件按渠道校验统一处理;`;
5709
- const message = `workbuddy 上游失败:${failoverReasonText(result)}(http ${result.status})${note}${stamp}。${memberNote}${evidence}该请求被 WorkBuddy 网关的渠道校验拦截,上游把它描述成「不是官方客户端发出的」,但那是误导性文案:网关匹配的是每一条 system 与 assistant 消息的开头,与账号、积分、额度、网络都无关,换账号或换区域也不会改变结果。插件已对已知的第三方 agent 指纹做归一化` + retryNote + ";若上面标着「不在插件已知名单里」的开头来自宿主或其他插件,请修改该提示;新的指纹可反馈到 issue 里";
5891
+ const message = `workbuddy 上游失败:${failoverReasonText(result)}(http ${result.status})${note}${stamp}。${memberNote}${evidence}该请求被 WorkBuddy 网关的渠道校验拦截,上游把它描述成「不是官方客户端发出的」,但那是误导性文案:网关扫描每一条 system 与 assistant 消息(开头做前缀匹配,正文做精确子串匹配),与账号、积分、额度、网络都无关,换账号或换区域也不会改变结果。插件已对已知的第三方 agent 指纹做归一化` + retryNote + (retriedWithForcedHead ? ";这次重试里每一条被扫描消息都已经加了中性头,仍然被拒,说明卡点不在这些开头本身" : "") + "。上面标着「不在插件已知名单里」的,只说明该消息的首行不是已知指纹,既不表示这条消息没被处理,也不表示它一定有问题;如果这些消息确实有问题,命中的更可能是中段的某一句。请把这条报错整段反馈到 issue 里——首行之外的线索只能从完整请求里找";
5710
5892
  writeOpenAIError(res, KIND_STATUS[result.kind], result.kind, message, hostErrorCode(result.kind));
5711
5893
  return;
5712
5894
  }
@@ -5812,6 +5994,149 @@ function asNonEmptyString$1(value) {
5812
5994
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5813
5995
  }
5814
5996
  /**
5997
+ * 把工具参数 `image` 规整成输入图列表。
5998
+ *
5999
+ * 返回 undefined 表示「没给图」(文生图);字符串数组 → 多张(上游
6000
+ * `/v2/images/edits` 的 `image` 字段本来就收数组)。
6001
+ *
6002
+ * 只收数组:一张图也写成 `["/abs/path.png"]`。早先的 schema 是
6003
+ * `type: ['string', 'array']`,联合类型在只认单 type 的 function-calling 上游
6004
+ * 会被压平或整段丢掉,模型也会写出 `image: "a.png"` 这种半对半错的值;
6005
+ * 现在统一成数组,类型不对就明说,不去猜调用方想表达什么。
6006
+ *
6007
+ * 畸形输入(字符串 / 数字 / 对象 / 布尔、空数组,或数组里混了非字符串 / 空串)抛
6008
+ * INVALID_ARGS——绝不能像更早那样把「不是单个字符串」当「没给图」,那会让
6009
+ * 参考图被悄悄丢掉、工具静默退回文生图,生成的画面跟 prompt 毫无关系。
6010
+ */
6011
+ function asImageList(value) {
6012
+ if (value === void 0 || value === null) return void 0;
6013
+ if (Array.isArray(value)) {
6014
+ if (value.length === 0) throw inputImageError("workbuddy image: image 收到了空数组。纯文生图请把 image 字段整个省略,不要传 [];要改图就给至少一张,如 [\"/abs/a.png\"]。");
6015
+ const items = [];
6016
+ for (const item of value) {
6017
+ if (typeof item !== "string" || item.trim() === "") throw inputImageError("workbuddy image: image 数组的每个元素都必须是非空字符串(本地路径 / file:// / http(s) / data URL / 裸 base64)。");
6018
+ items.push(item.trim());
6019
+ }
6020
+ return items;
6021
+ }
6022
+ if (typeof value === "string") throw inputImageError(`workbuddy image: image 必须是字符串数组,一张图也要写成数组。收到的是字符串 ${JSON.stringify(value.slice(0, 40))},请改写成 ["${value.slice(0, 40)}"]。`);
6023
+ throw inputImageError("workbuddy image: image 必须是字符串数组(如 [\"/abs/a.png\"] 或 [\"/abs/a.png\", \"/abs/b.png\"]),元素是本地路径 / file:// / http(s) / data URL / 裸 base64。");
6024
+ }
6025
+ /**
6026
+ * 可选字符串参数(size / model):undefined/null/空串 → 未提供;其它类型
6027
+ * (数字 / 数组 / 对象 / 布尔)→ INVALID_ARGS。
6028
+ *
6029
+ * 旧行为把类型不对的值静默丢掉、回落到默认值:`model: ["hy-image-3.0"]`
6030
+ * 会安静地用默认模型扣积分,`size: 1024` 安静地用默认尺寸——与 image 数组
6031
+ * 被静默丢掉切回文生图是同一族错误,只是后果轻些。类型写错就明说,
6032
+ * 不要替调用方猜一个默认值。
6033
+ *
6034
+ * size 还要再过一道格式关(见 {@link parseSizeSpec}):schema 里的 pattern
6035
+ * 只是给模型的提示,宿主不代校验,真正拦住「2K」「1024」「1024*1024」的是这里。
6036
+ */
6037
+ function strictString$1(value, name) {
6038
+ if (value === void 0 || value === null) return void 0;
6039
+ if (typeof value !== "string") throw inputImageError(`workbuddy image: 参数 ${name} 必须是字符串(或不填),实际是${Array.isArray(value) ? "数组" : typeof value}。`);
6040
+ return value.trim() === "" ? void 0 : value.trim();
6041
+ }
6042
+ /** 「宽x高」——允许 `x` / `X` / 全角 `×`;不接受 `*`、空格、带单位。 */
6043
+ const SIZE_PATTERN = /^[0-9]+[xX×][0-9]+$/;
6044
+ /** 上游实测上限:总像素约 419 万(见 docs/IMAGE_GEN.md「尺寸与比例」)。 */
6045
+ const MAX_IMAGE_PIXELS = 4194304;
6046
+ /** 边长支持范围。上限 2560 来自实测通过的最大长边(2560x1440 / 2560x1600)。 */
6047
+ const MIN_IMAGE_EDGE = 512;
6048
+ const MAX_IMAGE_EDGE = 2560;
6049
+ /** 实测被上游拒绝的尺寸,报错时直接点出来,省得模型反复试。 */
6050
+ const KNOWN_BAD_SIZES = /* @__PURE__ */ new Set([
6051
+ "2560x2560",
6052
+ "3072x3072",
6053
+ "4096x4096"
6054
+ ]);
6055
+ /** 本工具真正认的参数——与 `parameters.properties` 一一对应。 */
6056
+ const ALLOWED_ARGS$1 = /* @__PURE__ */ new Set([
6057
+ "prompt",
6058
+ "size",
6059
+ "image",
6060
+ "model"
6061
+ ]);
6062
+ /**
6063
+ * 拒掉 schema 里没有的参数。
6064
+ *
6065
+ * `additionalProperties: false` 只是写在 schema 里给模型看的,宿主把
6066
+ * `parameters` 原样投影、不代校验,execute 照样会收到 `ratio: '16:9'` 这种
6067
+ * 从别的生图工具(agnes 那边就叫 ratio / n / return_base64)串过来的字段。
6068
+ * 静默忽略的后果是模型以为改的比例生效了、其实出的是默认方图,所以这里明说。
6069
+ */
6070
+ function rejectUnknownArgs$1(record) {
6071
+ const unknown = Object.keys(record).filter((key) => !ALLOWED_ARGS$1.has(key));
6072
+ if (unknown.length === 0) return;
6073
+ throw inputImageError(`workbuddy image: 本工具没有 ${unknown.map((key) => `「${key}」`).join("、")} 参数,只有 prompt、size、image、model 四个。比例 / 横竖用 size 的「宽x高」(size 必填);要几张图就调用几次(一次一张)。`);
6074
+ }
6075
+ /**
6076
+ * 解析 size:必填、必须写成「宽x高」或 `auto`。
6077
+ *
6078
+ * **必填**是因为以前不填就静默按 1024x1024 出方图,模型于是学会了「什么都不写、
6079
+ * 让它自己猜」——要竖版壁纸也出方图,用户还看不出是哪一步丢的。
6080
+ *
6081
+ * 这里只管**格式**,不管范围:越界不报错,交给 {@link planImageSize} 等比收进
6082
+ * 范围(那条路要等输入图量过宽高,见那边的说明)。
6083
+ *
6084
+ * `parameters.pattern` 只是写给模型看的,宿主把 `parameters` 原样投影、不代校验,
6085
+ * execute 收到的可能是 `"2K"` / `1024`(已由 {@link strictString} 拦下)/ `"1024*1024"`。
6086
+ * 这些猜不出调用方到底想要多大的输入仍然直接 INVALID_ARGS(本地免费)。
6087
+ */
6088
+ function parseSizeSpec(value) {
6089
+ const raw = strictString$1(value, "size");
6090
+ if (raw === void 0) throw inputImageError("workbuddy image: 参数 size 必填,写成「宽x高」的像素数,改图也可以写 auto。方图 1024x1024、竖图 1024x1536、横图 1536x1024、16:9 桌面 2560x1440、9:16 手机壁纸 1440x2560。比例由它决定,不填不会替你猜。");
6091
+ const normalized = raw.toLowerCase();
6092
+ if (normalized === "auto") return { kind: "auto" };
6093
+ if (!SIZE_PATTERN.test(normalized)) throw inputImageError(`workbuddy image: 参数 size 必须写成「宽x高」的像素数或 auto,收到的是 ${JSON.stringify(raw)}。例如 1024x1024(方图)、1024x1536(竖图)、1536x1024(横图)、2560x1440(16:9)。不要写「2K」「4K」「高清」这类档位,也不要只写一个边长。`);
6094
+ const [widthPart = "", heightPart = ""] = normalized.split(/[xX×]/);
6095
+ const width = Number(widthPart);
6096
+ const height = Number(heightPart);
6097
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw inputImageError(`workbuddy image: 参数 size 的宽高必须是正整数,收到的是 ${JSON.stringify(raw)}。`);
6098
+ return {
6099
+ kind: "fixed",
6100
+ width,
6101
+ height,
6102
+ normalized
6103
+ };
6104
+ }
6105
+ /**
6106
+ * 把解析好的尺寸规格落成一个真正要发给上游的值。
6107
+ *
6108
+ * 与 {@link parseSizeSpec} 分开,是因为这两件事的**时机**不同:格式错误要在收到
6109
+ * 参数的第一时间就报(本地免费),而 `auto` 与越界缩放都要等输入图量过宽高。
6110
+ *
6111
+ * 越界为什么由工具收、而不是让模型自己算:两条边(512–2560)与总像素
6112
+ * (≤4,194,304)是两个约束,手算要取「2560/长边」与「√(4194304/面积)」里更小的
6113
+ * 那个**再复查一遍**。要求模型在参数里做这种算术,实测会算出仍然越界的值
6114
+ * (2480x3508 → 1810x2560,边长合规但乘积 4,633,600 仍超)。收完之后把「动过什么」
6115
+ * 写进 hint,模型得据实转告用户,不能假装按用户给的尺寸出图。
6116
+ */
6117
+ function planImageSize(spec, input) {
6118
+ if (spec.kind === "auto") {
6119
+ if (input === void 0) throw inputImageError("workbuddy image: size 写了 auto,但这一次量不出输入图的宽高(没有给 image,或给的图格式认不出来),没法替你挑画布。请直接写具体尺寸:方图 1024x1024、竖图 1024x1536、横图 1536x1024。");
6120
+ const canvas = canvasForInput(input);
6121
+ const size = `${canvas.width}x${canvas.height}`;
6122
+ return {
6123
+ size,
6124
+ requested: "auto",
6125
+ 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},比例有变化`
6126
+ };
6127
+ }
6128
+ const { width, height, normalized } = spec;
6129
+ if (isSizeInRange(width, height, normalized)) return { size: `${width}x${height}` };
6130
+ const fitted = fitIntoRange(width, height);
6131
+ 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。`);
6132
+ const direction = fitted.direction === "up" ? "放大" : "缩小";
6133
+ return {
6134
+ size: `${fitted.width}x${fitted.height}`,
6135
+ requested: normalized,
6136
+ note: `你给的尺寸 ${normalized} 超出 ${MIN_IMAGE_EDGE}–${MAX_IMAGE_EDGE} 边长或 419 万像素上限,已等比${direction}到 ${fitted.width}x${fitted.height}`
6137
+ };
6138
+ }
6139
+ /**
5815
6140
  * 这些失败说明请求真的打到了上游、可能已经扣了积分,才值得进冷却。
5816
6141
  * 参数写错 / 未登录 / 目录里没有模型都还没花钱。
5817
6142
  */
@@ -5863,6 +6188,202 @@ function inputImageError(message) {
5863
6188
  }
5864
6189
  const INLINE_BASE64_LABEL = "(内联 base64)";
5865
6190
  const INLINE_DATA_URL_LABEL = "(内联 data URL)";
6191
+ /** 方图容差:长短边之差不到长边的 5% 就算方图(比如 1000x1010)。 */
6192
+ const SQUARE_TOLERANCE = .05;
6193
+ const ORIENTATION_LABEL = {
6194
+ landscape: "横图",
6195
+ portrait: "竖图",
6196
+ square: "方图"
6197
+ };
6198
+ /** `size: "auto"` 的输出长边:够 1080P 用,又离 419 万像素上限还远。 */
6199
+ const AUTO_LONG_EDGE = 1536;
6200
+ /** 方向兜底档位:改图写了 auto 但比例极端到算不出画布、或干脆量不出宽高时用。 */
6201
+ const DEFAULT_SIZE_BY_ORIENTATION = {
6202
+ landscape: {
6203
+ width: 1536,
6204
+ height: 1024
6205
+ },
6206
+ portrait: {
6207
+ width: 1024,
6208
+ height: 1536
6209
+ },
6210
+ square: {
6211
+ width: 1024,
6212
+ height: 1024
6213
+ }
6214
+ };
6215
+ /**
6216
+ * 从图片字节里读像素宽高。
6217
+ *
6218
+ * 为什么值得自己解析:改图时 `size` 是**输出画布**,最合理的默认值由输入图的
6219
+ * 方向决定;但上游不回传输入尺寸,模型也读不到本地文件。早几版的描述要求模型
6220
+ * 「按原图比例挑一档」——那是在要求它猜,两个评审子代理都判这条不可执行。
6221
+ * 现在在把输入图读成字节的同一处顺手解出宽高,模型直接被告知真实方向。
6222
+ *
6223
+ * 只读文件头里的两个整数:不解码像素、不校验 CRC。认不出(或头不完整)就返回
6224
+ * undefined,让调用方退回方向兜底——「量不出尺寸」不该变成一次失败。
6225
+ *
6226
+ * 覆盖 PNG(IHDR)、JPEG(任一 SOF 段)、GIF(逻辑屏幕描述符)、WEBP
6227
+ * (VP8 / VP8L / VP8X 三种子格式)。
6228
+ */
6229
+ function parseImageDimensions(bytes) {
6230
+ const at = (index) => bytes[index] ?? 0;
6231
+ const u16be = (index) => at(index) << 8 | at(index + 1);
6232
+ const u16le = (index) => at(index) | at(index + 1) << 8;
6233
+ const u24le = (index) => at(index) | at(index + 1) << 8 | at(index + 2) << 16;
6234
+ const u32be = (index) => at(index) * 16777216 + (at(index + 1) << 16) + (at(index + 2) << 8) + at(index + 3);
6235
+ const u32le = (index) => (at(index) | at(index + 1) << 8 | at(index + 2) << 16) + at(index + 3) * 16777216;
6236
+ const positive = (width, height) => width > 0 && height > 0 ? {
6237
+ width,
6238
+ height
6239
+ } : void 0;
6240
+ if (bytes.length >= 24 && at(0) === 137 && at(1) === 80 && at(2) === 78 && at(3) === 71) return positive(u32be(16), u32be(20));
6241
+ if (at(0) === 255 && at(1) === 216) {
6242
+ let offset = 2;
6243
+ while (offset + 8 < bytes.length) {
6244
+ if (at(offset) !== 255) {
6245
+ offset += 1;
6246
+ continue;
6247
+ }
6248
+ const marker = at(offset + 1);
6249
+ if (marker === 1 || marker === 216 || marker >= 208 && marker <= 215) {
6250
+ offset += 2;
6251
+ continue;
6252
+ }
6253
+ const length = u16be(offset + 2);
6254
+ if (length < 2) return void 0;
6255
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) return positive(u16be(offset + 7), u16be(offset + 5));
6256
+ offset += 2 + length;
6257
+ }
6258
+ return;
6259
+ }
6260
+ if (at(0) === 71 && at(1) === 73 && at(2) === 70) return positive(u16le(6), u16le(8));
6261
+ if (bytes.length >= 30 && at(0) === 82 && at(1) === 73 && at(2) === 70 && at(3) === 70 && at(8) === 87 && at(9) === 69 && at(10) === 66 && at(11) === 80) {
6262
+ const chunk = String.fromCharCode(at(12), at(13), at(14), at(15));
6263
+ if (chunk === "VP8 ") {
6264
+ if (at(23) !== 157 || at(24) !== 1 || at(25) !== 42) return void 0;
6265
+ return positive(u16le(26) & 16383, u16le(28) & 16383);
6266
+ }
6267
+ if (chunk === "VP8L") {
6268
+ const bits = u32le(21);
6269
+ return positive((bits & 16383) + 1, (bits >> 14 & 16383) + 1);
6270
+ }
6271
+ if (chunk === "VP8X") return positive(u24le(24) + 1, u24le(27) + 1);
6272
+ return;
6273
+ }
6274
+ }
6275
+ /** 由宽高判方向——改图据此挑输出画布。 */
6276
+ function orientationOf(dimensions) {
6277
+ const longest = Math.max(dimensions.width, dimensions.height);
6278
+ if (longest - Math.min(dimensions.width, dimensions.height) <= longest * SQUARE_TOLERANCE) return "square";
6279
+ return dimensions.width > dimensions.height ? "landscape" : "portrait";
6280
+ }
6281
+ /**
6282
+ * 取第一张**量得出宽高**的输入图的尺寸。
6283
+ *
6284
+ * 用第一张不是因为「第一张最重要」,而是因为多张横竖混用时必须有个确定的判据:
6285
+ * 描述里已经写着「多张按第一张定」,这里就跟它对齐。第一张解析不出来就顺延到
6286
+ * 下一张,总比直接放弃好——认不出格式的图(比如上游还没见过的)不该让整次改图
6287
+ * 失去参照。
6288
+ */
6289
+ function firstDimensions(inputs) {
6290
+ for (const input of inputs) if (input.dimensions !== void 0) return input.dimensions;
6291
+ }
6292
+ /**
6293
+ * 按输入图的比例定输出画布(`size: "auto"`)。
6294
+ *
6295
+ * 长边固定 {@link AUTO_LONG_EDGE}、短边同比算——这是「改图别改版式」的落点:模型
6296
+ * 看不到原图多大,让它自己按比例挑档等于让它猜(1600x900 该写 2560x1440 还是
6297
+ * 1536x864?)。方图走 1024x1024:1536x1536 会顶到 235 万像素,比上游常用档大,
6298
+ * 方图的短边也没有信息增益。
6299
+ *
6300
+ * 极端比例(比 5:1 还细长)等比缩放放不进范围时,退回按方向的常用档——宁可换
6301
+ * 比例,也不能报错让用户无从下手;`exact: false` 就是用来把这句实话写进 hint 的。
6302
+ */
6303
+ function canvasForInput(input) {
6304
+ const orientation = orientationOf(input);
6305
+ if (orientation === "square") return {
6306
+ ...DEFAULT_SIZE_BY_ORIENTATION.square,
6307
+ exact: true
6308
+ };
6309
+ const longest = Math.max(input.width, input.height);
6310
+ const shortest = Math.min(input.width, input.height);
6311
+ const short = Math.max(1, Math.round(shortest * AUTO_LONG_EDGE / longest));
6312
+ const width = orientation === "landscape" ? AUTO_LONG_EDGE : short;
6313
+ const height = orientation === "landscape" ? short : AUTO_LONG_EDGE;
6314
+ if (isSizeInRange(width, height, `${width}x${height}`)) return {
6315
+ width,
6316
+ height,
6317
+ exact: true
6318
+ };
6319
+ const fitted = fitIntoRange(width, height);
6320
+ if (fitted !== void 0) return {
6321
+ width: fitted.width,
6322
+ height: fitted.height,
6323
+ exact: true
6324
+ };
6325
+ return {
6326
+ ...DEFAULT_SIZE_BY_ORIENTATION[orientation],
6327
+ exact: false
6328
+ };
6329
+ }
6330
+ /** 两个上限(长边 2560、总像素 419 万)同时满足时,把宽高按比例收进范围。 */
6331
+ function shrinkProduct(width, height) {
6332
+ let w = width;
6333
+ let h = height;
6334
+ for (let round = 0; round < 4 && w * h > MAX_IMAGE_PIXELS; round += 1) {
6335
+ const scale = Math.sqrt(MAX_IMAGE_PIXELS / (w * h));
6336
+ w = Math.floor(w * scale);
6337
+ h = Math.floor(h * scale);
6338
+ }
6339
+ return {
6340
+ width: w,
6341
+ height: h
6342
+ };
6343
+ }
6344
+ /**
6345
+ * 把一个越界尺寸等比缩/放到合法范围。
6346
+ *
6347
+ * 两条边(512–2560)与总像素(≤4,194,304)是两个约束,必须同时满足:只按长边缩
6348
+ * 会把 2480x3508 变成 1810x2560(边长都对、乘积 4,633,600 仍越界)。所以缩放比取
6349
+ * 「2560/长边」与「√(4194304/(宽×高))」里更小的那个。
6350
+ *
6351
+ * 返回 undefined 表示等比缩放解不出来(比例比 5:1 还极端:缩到长边 2560 时短边
6352
+ * 已经小于 512,抬到 512 时长边又超过 2560),交给调用方按方向换档。
6353
+ */
6354
+ function fitIntoRange(width, height) {
6355
+ const longest = Math.max(width, height);
6356
+ const shortest = Math.min(width, height);
6357
+ if (!(longest > MAX_IMAGE_EDGE || width * height > MAX_IMAGE_PIXELS) && shortest < MIN_IMAGE_EDGE) {
6358
+ const scale = MIN_IMAGE_EDGE / shortest;
6359
+ if (longest * scale <= MAX_IMAGE_EDGE) return {
6360
+ ...shrinkProduct(Math.round(width * scale), Math.round(height * scale)),
6361
+ direction: "up"
6362
+ };
6363
+ return;
6364
+ }
6365
+ const scale = Math.min(MAX_IMAGE_EDGE / longest, Math.sqrt(MAX_IMAGE_PIXELS / (width * height)));
6366
+ const scaled = shrinkProduct(Math.floor(width * scale), Math.floor(height * scale));
6367
+ if (scaled.width >= MIN_IMAGE_EDGE && scaled.height >= MIN_IMAGE_EDGE) return {
6368
+ ...scaled,
6369
+ direction: "down"
6370
+ };
6371
+ const extreme = MIN_IMAGE_EDGE / shortest;
6372
+ if (longest * extreme <= MAX_IMAGE_EDGE) {
6373
+ const lifted = shrinkProduct(Math.round(width * extreme), Math.round(height * extreme));
6374
+ if (lifted.width * lifted.height <= MAX_IMAGE_PIXELS) return {
6375
+ ...lifted,
6376
+ direction: "up"
6377
+ };
6378
+ }
6379
+ }
6380
+ /** 一个尺寸是否直接可用:两条边在 512–2560,且宽乘高不超过 419 万。 */
6381
+ function isSizeInRange(width, height, normalized) {
6382
+ if (KNOWN_BAD_SIZES.has(normalized)) return false;
6383
+ if (width < MIN_IMAGE_EDGE || height < MIN_IMAGE_EDGE) return false;
6384
+ if (width > MAX_IMAGE_EDGE || height > MAX_IMAGE_EDGE) return false;
6385
+ return width * height <= MAX_IMAGE_PIXELS;
6386
+ }
5866
6387
  /**
5867
6388
  * 体积与空文件闸门——四种输入形态都从这里过,所以「空文件」和「超过 8 MB」的
5868
6389
  * 文案只有一份。
@@ -5889,8 +6410,13 @@ async function resolveImageInput(value, signal) {
5889
6410
  if (text.startsWith("data:")) {
5890
6411
  const parsed = parseImageDataUrl(text);
5891
6412
  if (parsed === void 0) throw inputImageError("workbuddy image: image 看起来是 data URL,但格式不对(需要 data:image/*;base64,...)。");
5892
- assertInputImageBytes(Buffer.from(parsed.base64, "base64").byteLength, INLINE_DATA_URL_LABEL);
5893
- return text;
6413
+ const bytes = Buffer.from(parsed.base64, "base64");
6414
+ assertInputImageBytes(bytes.byteLength, INLINE_DATA_URL_LABEL);
6415
+ const dimensions = parseImageDimensions(new Uint8Array(bytes));
6416
+ return dimensions === void 0 ? { dataUrl: text } : {
6417
+ dataUrl: text,
6418
+ dimensions
6419
+ };
5894
6420
  }
5895
6421
  if (/^https?:\/\//i.test(text)) {
5896
6422
  let response;
@@ -5900,9 +6426,9 @@ async function resolveImageInput(value, signal) {
5900
6426
  throw inputImageError(`workbuddy image: 下载输入图失败(${text}):` + (error instanceof Error ? error.message : String(error)));
5901
6427
  }
5902
6428
  if (!response.ok) throw inputImageError(`workbuddy image: 下载输入图失败(HTTP ${response.status}):${text}`);
5903
- return encodeInputImage(new Uint8Array(await response.arrayBuffer()), response.headers.get("content-type") ?? void 0, text);
6429
+ return encodeResolvedImage(new Uint8Array(await response.arrayBuffer()), response.headers.get("content-type") ?? void 0, text);
5904
6430
  }
5905
- if (isBareBase64Image(text)) return encodeInputImage(new Uint8Array(Buffer.from(text, "base64")), void 0, INLINE_BASE64_LABEL);
6431
+ if (isBareBase64Image(text)) return encodeResolvedImage(new Uint8Array(Buffer.from(text, "base64")), void 0, INLINE_BASE64_LABEL);
5906
6432
  const path = text.startsWith("file:") ? fileURLToPath(text) : text;
5907
6433
  let bytes;
5908
6434
  try {
@@ -5910,14 +6436,19 @@ async function resolveImageInput(value, signal) {
5910
6436
  } catch (error) {
5911
6437
  throw inputImageError(`workbuddy image: 读不到输入图「${path}」:` + (error instanceof Error ? error.message : String(error)));
5912
6438
  }
5913
- return encodeInputImage(new Uint8Array(bytes), void 0, path);
6439
+ return encodeResolvedImage(new Uint8Array(bytes), void 0, path);
5914
6440
  }
5915
- /** 校验体积、定出 mime,再把字节编成 data URL。 */
5916
- function encodeInputImage(bytes, contentType, source) {
6441
+ /** 校验体积、定出 mime,把字节编成 data URL,并顺手量宽高。 */
6442
+ function encodeResolvedImage(bytes, contentType, source) {
5917
6443
  assertInputImageBytes(bytes.byteLength, source);
5918
6444
  const declared = contentType?.split(";")[0]?.trim().toLowerCase();
5919
6445
  const mime = declared !== void 0 && declared.startsWith("image/") ? declared : imageMimeForPath(source) ?? sniffImageMime(bytes);
5920
- return imageDataUrl(mime, Buffer.from(bytes).toString("base64"));
6446
+ const dataUrl = imageDataUrl(mime, Buffer.from(bytes).toString("base64"));
6447
+ const dimensions = parseImageDimensions(bytes);
6448
+ return dimensions === void 0 ? { dataUrl } : {
6449
+ dataUrl,
6450
+ dimensions
6451
+ };
5921
6452
  }
5922
6453
  /**
5923
6454
  * 造出工具定义。
@@ -5940,28 +6471,32 @@ function createImageTool(deps) {
5940
6471
  };
5941
6472
  return {
5942
6473
  name: WORKBUDDY_IMAGE_TOOL_NAME,
5943
- description: "用当前账号的 WorkBuddy 生图能力画一张图。不填 image 是文生图(用该区带 text-to-image 标签的模型);填了 image 是改图(用带 image-to-image 标签的模型)。国内区与国际区都可用,模型取自该区产品配置(国内区文生图 hunyuan-image-alpha、改图 hunyuan-image-alpha-edit;国际区 hy-image-3.5 同时带这两个标签,以该区目录为准)。每张图会真实消耗 WorkBuddy 积分,单价随区域与模型不同,以返回结果里的 credit 为准;不要在没必要时调用,也不要为了试错连续调用。返回的是 COS 签名 URL,约 24 小时后失效;需要展示给用户时,用 markdown 图片语法引用该 URL。",
6474
+ 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 时引用它并提醒尽快转存——本工具不负责下载或转存,要长期保存得用户自己点开链接另存。",
5944
6475
  parameters: {
5945
6476
  type: "object",
5946
6477
  properties: {
5947
6478
  prompt: {
5948
6479
  type: "string",
5949
- description: "画面描述(中文或英文都可以)。写清楚主体、风格、构图、光线。"
6480
+ minLength: 1,
6481
+ description: "画面描述(中文或英文都可以)。写清楚主体、风格、构图、光线;改图时还要写明哪些要保持原样、哪些要改。这里只写「画什么」,比例交给 size。"
5950
6482
  },
5951
6483
  size: {
5952
6484
  type: "string",
5953
- description: `图片尺寸,写成「宽x高」(像素)。比例由宽高决定,不限于方图。常用三档:方图 1024x1024、竖图 1024x1536、横图 1536x1024。要大图就按「总像素 419 万以内」放,出的是真实像素不是插值放大:2048x2048(4.19MP,方形上限)、2048x1536、2560x1440(16:9 桌面壁纸)、2560x1600。竖版同理,把长边放到 2048–2560 那一档。超过这个量级会被上游直接拒绝、不会悄悄降级(2560x2560、3072x3072、4096x4096 都失败),所以不要填 4K 尺寸,也不要指望传大数字能拿到更多细节。不填默认 ${DEFAULT_IMAGE_SIZE}(方图)。用户要竖版 / 横版 / 手机壁纸 / 封面 / 高清大图时,改这里的宽高,不要只在 prompt 里说。`
6485
+ pattern: "^([0-9]+[xX×][0-9]+|auto)$",
6486
+ description: "必填,二选一:一是「宽x高」的像素数(如 1024x1024、1024x1536、1536x1024),二是 auto。改图要保住原版式就写 auto:工具会量出第一张输入图的宽高、按同比例定画布,不用你猜原图多大。写像素数时只写「数字 + x」(X、× 也收,工具会规整成小写)。用户说的「2K」「4K」「高清」「9:16」这类档位词和比例词都先按工具描述里的表换成像素数,也不要只写一个边长。上限是两条边各 512–2560、宽乘高不超过 4,194,304(约 419 万,2048x2048 正好顶格):写超了不会报错,工具会等比缩/放并在 hint 里说明,用户说的数可以照写。唯一的例外是比例比 5:1 还细长(如 2560x400):缩不出合法值时会在本地报错、不扣积分。"
5954
6487
  },
5955
6488
  image: {
5956
- type: "string",
5957
- description: "输入图,可选。填了就是改图(image-to-image);不填就是文生图。接受本地绝对路径、file:// URL、http(s) URL、data URL 或裸 base64。上限 8 MB,不做缩放或格式转换。"
6489
+ type: "array",
6490
+ items: { type: "string" },
6491
+ minItems: 1,
6492
+ description: "输入图数组,可选。填了就是改图(image-to-image);纯文生图请整个省略本字段,不要传空数组([] 会被拒)。一张图也要写成数组:[\"/abs/path.png\"];Windows 路径写成 [\"C:\\\\abs\\\\a.png\"],本工具收的是结构化参数,直接写真实路径 C:\\Users\\me\\a.png 就行,反斜杠不用翻倍;只有在手写 JSON 文本时,一个反斜杠才要写成两个。多张参考图按数组顺序全部生效,如 [模板图, 服装图]。每个元素接受本地绝对路径、file:// URL、http(s) URL、data URL 或裸 base64,上限 8 MB/张(按原始文件字节算,不是 base64 之后的长度),本工具不做压缩或格式转换——超了会在本地报错、不扣积分,先让用户压一下再传。"
5958
6493
  },
5959
6494
  model: {
5960
6495
  type: "string",
5961
- description: "模型 id,可选。不填就用该区目录里第一个带当前模式标签的模型(文生图看 text-to-image,改图看 image-to-image)。填了但该 tag 组里没有会直接报错,不会盲发。"
6496
+ description: "模型 id,可选,一般留空(空字符串也算留空)。只有用户点名要某个模型时才填,填了不存在或没有对应 tag 的 id 会直接报错并列出可用 id,不会盲发。"
5962
6497
  }
5963
6498
  },
5964
- required: ["prompt"],
6499
+ required: ["prompt", "size"],
5965
6500
  additionalProperties: false
5966
6501
  },
5967
6502
  output: {
@@ -5976,6 +6511,18 @@ function createImageTool(deps) {
5976
6511
  type: "string",
5977
6512
  description: "'generate'(文生图)或 'edit'(改图)。"
5978
6513
  },
6514
+ region: {
6515
+ type: "string",
6516
+ description: "'cn'(国内版)或 'global'(国际版)。"
6517
+ },
6518
+ size: {
6519
+ type: "string",
6520
+ description: "实际出图尺寸,规整后的小写「宽x高」。"
6521
+ },
6522
+ requestedSize: {
6523
+ type: "string",
6524
+ description: "尺寸被工具等比缩/放过时才有,是你原本写的值(写 auto 时是 auto)。"
6525
+ },
5979
6526
  model: {
5980
6527
  type: "string",
5981
6528
  description: "实际使用的模型 id。"
@@ -6000,6 +6547,8 @@ function createImageTool(deps) {
6000
6547
  required: [
6001
6548
  "url",
6002
6549
  "mode",
6550
+ "region",
6551
+ "size",
6003
6552
  "model",
6004
6553
  "prompt",
6005
6554
  "hint"
@@ -6030,11 +6579,12 @@ function createImageTool(deps) {
6030
6579
  timeoutMs: IMAGE_TOOL_TIMEOUT_MS,
6031
6580
  async execute(args, exec) {
6032
6581
  const record = asRecord$1(args);
6582
+ rejectUnknownArgs$1(record);
6033
6583
  const prompt = asNonEmptyString$1(record["prompt"]);
6034
6584
  if (prompt === void 0) throw new WorkBuddyImageError(`${WORKBUDDY_IMAGE_TOOL_NAME}: 参数 prompt 必填,且必须是非空字符串。`, "INVALID_ARGS");
6035
- const size = asNonEmptyString$1(record["size"]) ?? "1024x1024";
6036
- const requestedModel = asNonEmptyString$1(record["model"]);
6037
- const image = asNonEmptyString$1(record["image"]);
6585
+ const sizeSpec = parseSizeSpec(record["size"]);
6586
+ const requestedModel = strictString$1(record["model"], "model");
6587
+ const images = asImageList(record["image"]);
6038
6588
  const now = Date.now();
6039
6589
  if (now < cooldownUntil) {
6040
6590
  const seconds = Math.ceil((cooldownUntil - now) / 1e3);
@@ -6046,10 +6596,14 @@ function createImageTool(deps) {
6046
6596
  let sent = false;
6047
6597
  try {
6048
6598
  const models = await listModels(credential, signal);
6049
- const input = image === void 0 ? void 0 : await resolveImageInput(image, signal);
6050
- const model = pickMediaModel(models, requestedModel, input === void 0 ? IMAGE_TAG_TEXT_TO_IMAGE : IMAGE_TAG_IMAGE_TO_IMAGE);
6599
+ const resolved = images === void 0 ? void 0 : await Promise.all(images.map((image) => resolveImageInput(image, signal)));
6600
+ const inputSize = resolved === void 0 ? void 0 : firstDimensions(resolved);
6601
+ const plan = planImageSize(sizeSpec, inputSize);
6602
+ const size = plan.size;
6603
+ const inputs = resolved?.map((input) => input.dataUrl);
6604
+ const model = pickMediaModel(models, requestedModel, inputs === void 0 ? IMAGE_TAG_TEXT_TO_IMAGE : IMAGE_TAG_IMAGE_TO_IMAGE);
6051
6605
  sent = true;
6052
- const outcome = input === void 0 ? await deps.generateImage(credential, {
6606
+ const outcome = inputs === void 0 ? await deps.generateImage(credential, {
6053
6607
  model: model.id,
6054
6608
  prompt,
6055
6609
  size
@@ -6057,15 +6611,22 @@ function createImageTool(deps) {
6057
6611
  model: model.id,
6058
6612
  prompt,
6059
6613
  size,
6060
- image: [input]
6614
+ image: inputs
6061
6615
  }, signal);
6062
- const mode = input === void 0 ? "generate" : "edit";
6616
+ const mode = inputs === void 0 ? "generate" : "edit";
6617
+ const region = regionOf(credential.domain) === "global" ? "global" : "cn";
6618
+ const regionLabel = region === "global" ? "国际版" : "国内版";
6619
+ const dimensionNote = plan.note === void 0 ? "" : `${plan.note}。`;
6620
+ const inputNote = inputSize === void 0 ? "" : `输入图第一张是 ${inputSize.width}x${inputSize.height}(${ORIENTATION_LABEL[orientationOf(inputSize)]})。`;
6063
6621
  const value = {
6064
6622
  mode,
6623
+ region,
6624
+ size,
6065
6625
  model: model.id,
6066
6626
  prompt,
6067
- hint: `这张图来自 WorkBuddy(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"})。按张扣积分,单价随区域与模型不同` + (outcome.credit === void 0 ? "(本次响应没带扣费字段,以额度面板为准)。" : `;本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6627
+ hint: `这张图来自 WorkBuddy ${regionLabel}(模型 ${model.id},${mode === "edit" ? "改图" : "文生图"},尺寸 ${size})。` + inputNote + dimensionNote + (outcome.credit === void 0 ? "本次响应没带扣费字段,具体扣了多少以额度面板为准。" : `本次实际扣费 ${outcome.credit} 积分。`) + "COS 签名 URL 约 24 小时失效;要长期保留请及时下载。"
6068
6628
  };
6629
+ if (plan.requested !== void 0 && plan.requested !== size) value["requestedSize"] = plan.requested;
6069
6630
  if (outcome.url !== void 0) value["url"] = outcome.url;
6070
6631
  else if (outcome.b64 !== void 0) {
6071
6632
  const path = await writeTempImage(outcome.b64, model.id);
@@ -6121,8 +6682,22 @@ function registerWorkBuddyImageTool(tools, deps) {
6121
6682
  */
6122
6683
  /** 工具名。宿主禁止 `run_code`,这个名字与其它 connect 插件的命名习惯一致。 */
6123
6684
  const WORKBUDDY_VIDEO_TOOL_NAME = "workbuddy_draw_video";
6124
- /** 工具单次执行的上限:提交 + 轮询(最多 ~10 分钟)+ 下载,留足余量。 */
6125
- const VIDEO_TOOL_TIMEOUT_MS = 6e5;
6685
+ /**
6686
+ * 工具单次执行的上限:提交 + 轮询 + 下载。
6687
+ *
6688
+ * ## 为什么必须比宿主的 600 秒**明显小**(issue #187 的第三种现象)
6689
+ *
6690
+ * 这个值原本正好是 `600_000`,与宿主自己给工具调用的上限**完全相等**。两者同时到
6691
+ * 期,而宿主的计时器先落地:调用被宿主直接掐断,用户看到的是裸的
6692
+ * `tool call timed out after 600000ms`——没有 `taskId`、没有 `POLL_TIMEOUT`、没有
6693
+ * 任何结构化错误,日志里也找不到是提交卡住还是轮询卡住。
6694
+ *
6695
+ * 内部超时短于宿主上限,插件就能**先**抛 `POLL_TIMEOUT`,把 task id 带出去。那个
6696
+ * id 是这个故障里唯一能拿去问上游的东西,丢掉它等于把可排障的失败变成不可排障的。
6697
+ *
6698
+ * 570s 而不是更短:正常任务实测几十秒到几分钟,砍太狠会把慢但成功的任务判死。
6699
+ */
6700
+ const VIDEO_TOOL_TIMEOUT_MS = 57e4;
6126
6701
  /** 下载远程输入图(图生视频时)的上限,不含生视频本身。 */
6127
6702
  const VIDEO_INPUT_TIMEOUT_MS = 3e4;
6128
6703
  /** 失败后的冷却:视频按次扣积分且一次要几十秒,连续重试会烧掉大量积分。 */
@@ -6133,11 +6708,85 @@ function asRecord(value) {
6133
6708
  function asNonEmptyString(value) {
6134
6709
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
6135
6710
  }
6136
- function asNumber(value) {
6137
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
6711
+ function describeArgType(value) {
6712
+ if (Array.isArray(value)) return "array";
6713
+ if (value === null) return "null";
6714
+ return typeof value;
6715
+ }
6716
+ /** 本工具真正认的参数——与 `parameters.properties` 一一对应。 */
6717
+ const ALLOWED_ARGS = /* @__PURE__ */ new Set([
6718
+ "prompt",
6719
+ "image",
6720
+ "model",
6721
+ "seconds",
6722
+ "resolution",
6723
+ "aspect_ratio",
6724
+ "negative_prompt",
6725
+ "enable_audio"
6726
+ ]);
6727
+ /**
6728
+ * 拒掉 schema 里没有的参数。
6729
+ *
6730
+ * `additionalProperties: false` 只是写在 schema 里给模型看的:宿主把 `parameters`
6731
+ * 原样投影、不代校验,execute 照样会收到从别的生图工具串过来的字段——
6732
+ * `size: '1024x1024'`(生图的)、`ratio` / `n` / `return_base64`(agnes 的)、
6733
+ * `quality` / `style` 之类。静默忽略的后果是模型以为横竖版生效了,实际出的是
6734
+ * 默认 16:9,而视频按次扣积分、一次几十秒,错一次代价很高。
6735
+ *
6736
+ * 注意 `aspect_ratio` 是本工具**真有**的参数,与生图的 `size` 是同一件事的两种
6737
+ * 写法:不要因为生图没有 `aspect_ratio` 就把它也拒掉。
6738
+ */
6739
+ function rejectUnknownArgs(record) {
6740
+ const unknown = Object.keys(record).filter((key) => !ALLOWED_ARGS.has(key));
6741
+ if (unknown.length === 0) return;
6742
+ throw new WorkBuddyVideoError(`workbuddy video: 本工具没有 ${unknown.map((key) => `「${key}」`).join("、")} 参数,只有 prompt、image、model、seconds、resolution、aspect_ratio、negative_prompt、enable_audio 八个。横竖比例用 aspect_ratio(16:9 / 9:16 / 1:1,仅文生视频);尺寸 / 清晰度用 resolution(如 720P / 1080P);不需要 size、ratio、n、return_base64、quality 之类的字段。`, "INVALID_ARGS");
6138
6743
  }
6139
- function asBoolean(value) {
6140
- return typeof value === "boolean" ? value : void 0;
6744
+ /**
6745
+ * 可选参数的严格读取族:undefined/null/空串 → 未提供(走默认值);
6746
+ * 类型不对 → INVALID_ARGS,绝不静默丢掉。
6747
+ *
6748
+ * 旧行为(`asNumber`/`asBoolean` 式的"类型不对就当没给")与生图工具
6749
+ * `image: [...] 被丢掉切回文生图` 是同一族错误:`seconds: "10"` 安静地
6750
+ * 出 5 秒的片、`model: ["kling-video-v3"]` 安静地换了模型扣积分。调用方
6751
+ * 写了参数就要么被尊重、要么被明说——类型写错就报错,不要替它猜默认值。
6752
+ * 这些校验都发生在「发请求」之前:不花积分、不进冷却。
6753
+ */
6754
+ function strictString(value, name) {
6755
+ if (value === void 0 || value === null) return void 0;
6756
+ if (typeof value !== "string") throw new WorkBuddyVideoError(`workbuddy video: 参数 ${name} 必须是字符串(或不填),实际是${describeArgType(value)}。`, "INVALID_ARGS");
6757
+ return value.trim() === "" ? void 0 : value.trim();
6758
+ }
6759
+ function strictNumber(value, name) {
6760
+ if (value === void 0 || value === null) return void 0;
6761
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new WorkBuddyVideoError(`workbuddy video: 参数 ${name} 必须是有限数字(或不填),实际是${describeArgType(value)}。`, "INVALID_ARGS");
6762
+ return value;
6763
+ }
6764
+ function strictBoolean(value, name) {
6765
+ if (value === void 0 || value === null) return void 0;
6766
+ if (typeof value !== "boolean") throw new WorkBuddyVideoError(`workbuddy video: 参数 ${name} 必须是布尔值(或不填),实际是${describeArgType(value)}。`, "INVALID_ARGS");
6767
+ return value;
6768
+ }
6769
+ /**
6770
+ * 输入图参数:字符串 → 照旧;单元素字符串数组 → 解包(与字符串等价,宽容
6771
+ * 模型侧常见的数组写法);undefined/null/空串 → 未提供(文生视频)。
6772
+ * 其余 → INVALID_ARGS。
6773
+ *
6774
+ * 为什么不收多图数组:图生视频上游只吃**单张** `image_url`,不像图生图的
6775
+ * `/v2/images/edits` 收数组。调用方传多张时它以为自己在做多图参考——
6776
+ * 静默取第一张或静默全丢都是撒谎,必须明说;生图工具那种「数组被丢掉、
6777
+ * 模式悄悄切成文生」的 bug 在这里被钉死不再发生。
6778
+ */
6779
+ function asVideoImageInput(value) {
6780
+ if (value === void 0 || value === null) return void 0;
6781
+ if (typeof value === "string") return value.trim() === "" ? void 0 : value.trim();
6782
+ if (Array.isArray(value)) {
6783
+ if (value.length === 0) return void 0;
6784
+ if (value.length > 1) throw new WorkBuddyVideoError(`workbuddy video: 图生视频只支持一张输入图,收到 ${value.length} 张。需要多图参考时,先用生图工具把参考合成一张成品图,再把那张图传到这里。`, "INVALID_ARGS");
6785
+ const item = value[0];
6786
+ if (typeof item !== "string" || item.trim() === "") throw new WorkBuddyVideoError("workbuddy video: image 数组的唯一元素必须是非空字符串(本地路径 / file:// / http(s) / data URL / 裸 base64)。", "INVALID_ARGS");
6787
+ return item.trim();
6788
+ }
6789
+ throw new WorkBuddyVideoError("workbuddy video: image 必须是字符串或单元素字符串数组(本地路径 / file:// / http(s) / data URL / 裸 base64)。", "INVALID_ARGS");
6141
6790
  }
6142
6791
  /**
6143
6792
  * 这些失败说明请求真的打到了上游、可能已经扣了积分,才值得进冷却。
@@ -6166,14 +6815,27 @@ function isBillableFailure(error, sent) {
6166
6815
  return true;
6167
6816
  }
6168
6817
  /**
6169
- * 把任意形态的输入图规整成上游唯一接受的形态:data URL 或 http(s) URL。
6818
+ * 把任意形态的输入图规整成 data URL。
6819
+ *
6820
+ * ## 为什么 http(s) 也要下载下来(issue #187)
6821
+ *
6822
+ * 这里以前只发一个 `HEAD` 做可达性校验,然后把 URL **原样**交给上游。两个问题:
6170
6823
  *
6171
- * 图生视频的 `image_url` 字段只接受上游可访问的 URL。本地文件路径必须
6172
- * 读进来、编码成 data URL 再发,否则上游读到的是空响应,返回
6173
- * "Input ImageUrl data is invalid (too short)"。与 `image-tool.ts` 的
6174
- * `resolveImageInput` 同一套逻辑:data URL 校验后直传,http(s) 校验可达性
6175
- * 后直传,裸 base64 / 本地路径 / file:// 读文件编成 data URL。不做缩放
6176
- * 或格式转换——用户给什么就传什么。
6824
+ * 1. **`HEAD` 会被 COS 拒绝。** 插件自己出图返回的是腾讯 COS 签名 URL
6825
+ * (`ai-corpus-backup-*.cos.ap-beijing.myqcloud.com`),签名只覆盖 `GET`。
6826
+ * 对它发 `HEAD` 拿到 **403**,于是用户在"用上一张成功的图做首帧"这条最自然的
6827
+ * 路径上卡死——而那个 URL 用 `curl` 明明取得到。报错因此指向了错误的对象:
6828
+ * 用户以为是自己的图有问题。
6829
+ * 2. **上游不接受外链。** 即使 HEAD 通过,图生视频的 `image_url` 与图生图的
6830
+ * `image` 是同一条规则(PR #145 记录过:"image 必须是 data URI,传 COS 原始
6831
+ * URL → invoke model error")。原样传 URL 只是把失败推迟到上游,并且那时已经
6832
+ * 建了 task、扣了积分。
6833
+ *
6834
+ * 所以这里与 `image-tool.ts` 的 `resolveImageInput` 完全对齐:**下载并编码成
6835
+ * data URL**。这也顺带让签名过期、上游改域名的场景在本地就报出可读的错,而不是
6836
+ * 变成一个花了钱才发现的 `TASK_FAILED`。
6837
+ *
6838
+ * 仍然不做缩放或格式转换——用户给什么就传什么,只改承载形式。
6177
6839
  */
6178
6840
  async function resolveVideoImageInput(value, signal) {
6179
6841
  const text = value.trim();
@@ -6184,17 +6846,14 @@ async function resolveVideoImageInput(value, signal) {
6184
6846
  return text;
6185
6847
  }
6186
6848
  if (/^https?:\/\//i.test(text)) {
6849
+ let response;
6187
6850
  try {
6188
- const response = await fetch(text, {
6189
- method: "HEAD",
6190
- signal: signal ?? AbortSignal.timeout(VIDEO_INPUT_TIMEOUT_MS)
6191
- });
6192
- if (!response.ok) throw new WorkBuddyVideoError(`workbuddy video: 输入图 URL 不可达(HTTP ${response.status}): ${text}`, "INVALID_ARGS");
6851
+ response = await fetch(text, { signal: signal ?? AbortSignal.timeout(VIDEO_INPUT_TIMEOUT_MS) });
6193
6852
  } catch (error) {
6194
- if (error instanceof WorkBuddyVideoError) throw error;
6195
- throw new WorkBuddyVideoError(`workbuddy video: 校验输入图 URL 失败(${text}):` + (error instanceof Error ? error.message : String(error)), "INVALID_ARGS");
6853
+ throw new WorkBuddyVideoError(`workbuddy video: 下载输入图失败(${text}):` + (error instanceof Error ? error.message : String(error)), "INVALID_ARGS");
6196
6854
  }
6197
- return text;
6855
+ if (!response.ok) throw new WorkBuddyVideoError(`workbuddy video: 下载输入图失败(HTTP ${response.status}):${text}`, "INVALID_ARGS");
6856
+ return encodeVideoInputImage(new Uint8Array(await response.arrayBuffer()), response.headers.get("content-type") ?? text);
6198
6857
  }
6199
6858
  if (isBareBase64Image(text)) return encodeVideoInputImage(Buffer.from(text, "base64"), "(内联 base64)");
6200
6859
  const path = text.startsWith("file:") ? fileURLToPath(text) : text;
@@ -6256,7 +6915,7 @@ function createVideoTool(deps) {
6256
6915
  };
6257
6916
  return {
6258
6917
  name: WORKBUDDY_VIDEO_TOOL_NAME,
6259
- description: "用当前账号的 WorkBuddy 视频生成能力生成一段短视频。不填 image 是文生视频(用该区带 text-to-video 标签的模型);填了 image 是图生视频(用带 image-to-video 标签的模型)。国内区与国际区都可用,模型取自该区产品配置(国内区 kling-video-v3、minimax-video-h3;国际区 kling-video-v3,两种 video tag 都有;以该区目录为准)。视频是异步任务:先提交、再轮询到完成、最后把视频下载到本地,单次可能要几十秒到几分钟。每次生成会真实消耗 WorkBuddy 积分,单价随区域与模型不同,以返回结果里的 credit 为准;不要在没必要时调用,也不要为了试错连续调用。返回的是本地 .mp4 文件路径(file:// URL),由宿主/客户端打开或下载。",
6918
+ description: "用当前账号的 WorkBuddy 视频生成能力生成一段短视频。不填 image 是文生视频(用该区带 text-to-video 标签的模型);填了 image 是图生视频(用带 image-to-video 标签的模型,只收一张输入图)。本工具只有 prompt、image、model、seconds、resolution、aspect_ratio、negative_prompt、enable_audio 八个参数:没有 size / ratio / n / return_base64 / quality / style 之类的字段,塞进来会直接报错。时长用 seconds、横竖用 aspect_ratio(16:9 / 9:16 / 1:1)、清晰度用 resolution——用户提这类要求时改这些参数,不要只在 prompt 里写「横版」「竖版」。可选参数要么不填、要么类型正确;填错类型直接 INVALID_ARGS 且不发请求,不会静默丢参数或切换模式。国内区与国际区都可用,模型取自该区产品配置里带 video tag 的条目。model 默认留空:留空才走「用户在卡片上钉住的模型 → 该区目录第一个」这条链,不要凭印象猜模型 id,名称不对会直接报错并列出可用 id。视频是异步任务:先提交、再轮询到完成、最后把视频下载到本地,单次可能要几十秒到几分钟。每次生成会真实消耗 WorkBuddy 积分,单价随区域与模型不同,以返回结果里的 credit 为准;不要在没必要时调用,也不要为了试错连续调用。返回的是本地 .mp4 文件路径(file:// URL),由宿主/客户端打开或下载。",
6260
6919
  parameters: {
6261
6920
  type: "object",
6262
6921
  properties: {
@@ -6265,8 +6924,9 @@ function createVideoTool(deps) {
6265
6924
  description: "画面描述(中文或英文都可以),≤2500 字符。写清楚主体、动作、风格、镜头。"
6266
6925
  },
6267
6926
  image: {
6268
- type: "string",
6269
- description: "输入图,可选。填了就是图生视频(image-to-video);不填就是文生视频。接受本地绝对路径、file:// URL、http(s) URL、data URL 或裸 base64。上限 8 MB,不做缩放或格式转换。"
6927
+ type: ["string", "array"],
6928
+ items: { type: "string" },
6929
+ description: "输入图,可选。填了就是图生视频(image-to-video);不填就是文生视频。接受本地绝对路径、file:// URL、http(s) URL、data URL 或裸 base64。上限 8 MB,不做缩放或格式转换。单元素字符串数组与字符串等价;图生视频只支持一张输入图,传多张会直接报错(不会静默改走文生视频)。需要多图参考(如按模板换装)时,先用生图工具 workbuddy_draw_image 把参考合成一张成品图,再把这张图传进来。"
6270
6930
  },
6271
6931
  model: {
6272
6932
  type: "string",
@@ -6369,15 +7029,16 @@ function createVideoTool(deps) {
6369
7029
  timeoutMs: VIDEO_TOOL_TIMEOUT_MS,
6370
7030
  async execute(args, exec) {
6371
7031
  const record = asRecord(args);
7032
+ rejectUnknownArgs(record);
6372
7033
  const prompt = asNonEmptyString(record["prompt"]);
6373
7034
  if (prompt === void 0) throw new WorkBuddyVideoError(`${WORKBUDDY_VIDEO_TOOL_NAME}: 参数 prompt 必填,且必须是非空字符串。`, "INVALID_ARGS");
6374
- const requestedModel = asNonEmptyString(record["model"]);
6375
- const requestedSeconds = asNumber(record["seconds"]);
6376
- const requestedResolution = asNonEmptyString(record["resolution"]);
6377
- const requestedAspectRatio = asNonEmptyString(record["aspect_ratio"]);
6378
- const requestedNegativePrompt = asNonEmptyString(record["negative_prompt"]);
6379
- const requestedEnableAudio = asBoolean(record["enable_audio"]);
6380
- const image = asNonEmptyString(record["image"]);
7035
+ const requestedModel = strictString(record["model"], "model");
7036
+ const requestedSeconds = strictNumber(record["seconds"], "seconds");
7037
+ const requestedResolution = strictString(record["resolution"], "resolution");
7038
+ const requestedAspectRatio = strictString(record["aspect_ratio"], "aspect_ratio");
7039
+ const requestedNegativePrompt = strictString(record["negative_prompt"], "negative_prompt");
7040
+ const requestedEnableAudio = strictBoolean(record["enable_audio"], "enable_audio");
7041
+ const image = asVideoImageInput(record["image"]);
6381
7042
  const now = Date.now();
6382
7043
  if (now < cooldownUntil) {
6383
7044
  const seconds = Math.ceil((cooldownUntil - now) / 1e3);
@@ -8797,6 +9458,7 @@ async function probeModel(input) {
8797
9458
  return {
8798
9459
  modelId: input.modelId,
8799
9460
  outcome: "unavailable",
9461
+ status: 0,
8800
9462
  message: redactUpstreamText(error instanceof Error ? error.message : String(error))
8801
9463
  };
8802
9464
  }
@@ -9130,7 +9792,8 @@ async function testOne(target, modelId, deps) {
9130
9792
  ...base,
9131
9793
  result: {
9132
9794
  modelId,
9133
- outcome: "credential-rejected",
9795
+ outcome: "failed",
9796
+ status: 0,
9134
9797
  message: messageOf$1(error)
9135
9798
  }
9136
9799
  };
@@ -9156,6 +9819,13 @@ async function testOne(target, modelId, deps) {
9156
9819
  * model, and recording it would exclude a possibly-perfect account from the
9157
9820
  * pool — so those accounts keep their previous measurement instead.
9158
9821
  *
9822
+ * That covers two distinct "we never got to ask the model" cases, and they are
9823
+ * dropped by {@link isTransportFailure} for different reasons: an absent
9824
+ * credential reports itself as `credential-rejected` with the pool's own
9825
+ * message, while a credential STORE that threw reports `failed` with `status: 0`
9826
+ * (issue #195 — it used to report `credential-rejected`, which carries no
9827
+ * cooldown and excluded the account permanently).
9828
+ *
9159
9829
  * `atMs` is stamped here, once for the batch, so the card's "tested N minutes
9160
9830
  * ago" reflects when the batch finished rather than drifting per row.
9161
9831
  *
@@ -9182,14 +9852,35 @@ function probeUpdatesOf(rows) {
9182
9852
  return updates;
9183
9853
  }
9184
9854
  /**
9185
- * Whether a probe result measures the transport rather than the model.
9855
+ * Whether a probe result measures the TRANSPORT rather than the model.
9856
+ *
9857
+ * Two shapes qualify, and both must be dropped rather than persisted:
9858
+ *
9859
+ * 1. `credential-rejected` with the pool's own "no stored credential" message —
9860
+ * we could not even read the credential, so the request never left.
9861
+ * 2. `status: 0` — the request never produced an HTTP response at all. That is
9862
+ * what a probe timeout looks like (`transport error: no response within
9863
+ * 30000ms`), and equally a DNS failure, a reset connection, or a throw from
9864
+ * the identity work that runs BEFORE the request is sent (`wireIdentity`).
9865
+ * Issue #195 is the third of those: `probeModel`'s own `catch` returned
9866
+ * `unavailable` with NO `status` at all, so it slipped past this test and
9867
+ * benched a healthy account for half an hour.
9868
+ *
9869
+ * WHY (2) MATTERS — it is the difference between a working pool and a 30-minute
9870
+ * outage. A `status: 0` result carries no `retryAtMs` (nothing upstream said
9871
+ * when to come back), so `exclusionOf` falls back to
9872
+ * {@link POOL_UNKNOWN_COOLDOWN_MS} — 30 minutes. Persisting a timeout therefore
9873
+ * benches a perfectly healthy account for half an hour, and since nothing
9874
+ * re-probes an excluded member, the pool stays empty until the cooldown lapses
9875
+ * on its own. The user sees "池中已无可用账号" and a 502 for a fault that was
9876
+ * never the account's.
9186
9877
  *
9187
- * `credential-rejected` with the pool's own "no stored credential" message is
9188
- * the one case we can attribute to ourselves rather than the upstream: the
9189
- * request never left. Every other rejection came from the upstream and IS a
9190
- * statement about this account, so it is kept.
9878
+ * The distinction has to stay honest in the other direction too: `status >= 500`
9879
+ * is NOT a transport failure. The gateway answered, and its answer is a
9880
+ * statement about this account's standing with it, so those rows are still kept.
9191
9881
  */
9192
9882
  function isTransportFailure(result) {
9883
+ if (result.status === 0) return true;
9193
9884
  return result.outcome === "credential-rejected" && result.message?.startsWith("no stored credential") === true;
9194
9885
  }
9195
9886
  /** The default inter-account pause. */
@@ -9960,7 +10651,7 @@ function mergeTransferRecords(records, indexes, region, knownRegionOfDomain) {
9960
10651
  * @module dsh-connect-workbuddy/account-pool-store
9961
10652
  */
9962
10653
  /** On-disk format version; readers reject anything else. */
9963
- const STORE_FORMAT_VERSION = 1;
10654
+ const STORE_FORMAT_VERSION$1 = 1;
9964
10655
  /** Filename prefix for one region's measured pool facts. */
9965
10656
  const POOL_STORE_PREFIX = ".workbuddy-pool";
9966
10657
  /** Whether a parsed value looks like a stored probe. */
@@ -10050,7 +10741,7 @@ async function readPoolProbes(region) {
10050
10741
  }
10051
10742
  if (typeof parsed !== "object" || parsed === null) return {};
10052
10743
  const document = parsed;
10053
- if (document.version !== STORE_FORMAT_VERSION) return {};
10744
+ if (document.version !== STORE_FORMAT_VERSION$1) return {};
10054
10745
  if (typeof document.probes !== "object" || document.probes === null) return {};
10055
10746
  const probes = {};
10056
10747
  for (const [accountId, probe] of Object.entries(document.probes)) {
@@ -10147,7 +10838,7 @@ async function writePoolProbes(region, updates) {
10147
10838
  const merged = { ...existing };
10148
10839
  for (const [accountId, update] of Object.entries(updates)) merged[accountId] = mergePoolProbe(existing[accountId], update);
10149
10840
  await writeFileAtomic(path, `${JSON.stringify({
10150
- version: STORE_FORMAT_VERSION,
10841
+ version: STORE_FORMAT_VERSION$1,
10151
10842
  probes: merged
10152
10843
  }, null, 2)}\n`, {
10153
10844
  mode: 384,
@@ -10157,6 +10848,279 @@ async function writePoolProbes(region, updates) {
10157
10848
  } catch {}
10158
10849
  }
10159
10850
  //#endregion
10851
+ //#region src/auto-checkin.ts
10852
+ /**
10853
+ * Regions that have a daily check-in at all.
10854
+ *
10855
+ * The CN gateway runs a consumer check-in; the international one does not. The
10856
+ * card hides the switch on a region without one, and this predicate is the
10857
+ * single place that fact is stated for the background path — the manual button
10858
+ * asks `checkinSupported` on the same rule.
10859
+ */
10860
+ function autoCheckinRegions() {
10861
+ return ["cn"];
10862
+ }
10863
+ /**
10864
+ * Retry backoff after a failed attempt, in milliseconds.
10865
+ *
10866
+ * Five widening steps and then a slow poll. The shape matters more than the
10867
+ * numbers: the first retry is soon (a transient socket fault clears in seconds),
10868
+ * and the tail is slow (an upstream outage should not be probed every minute for
10869
+ * the rest of the day). After the last entry, {@link AUTO_CHECKIN_TAIL_MS}
10870
+ * repeats until the local day rolls over.
10871
+ */
10872
+ const AUTO_CHECKIN_BACKOFF_MS = [
10873
+ 3e4,
10874
+ 6e4,
10875
+ 12e4,
10876
+ 3e5,
10877
+ 9e5
10878
+ ];
10879
+ /** The steady-state retry interval once {@link AUTO_CHECKIN_BACKOFF_MS} is spent. */
10880
+ const AUTO_CHECKIN_TAIL_MS = 18e5;
10881
+ /**
10882
+ * How long after a completed day the runner waits before trying again.
10883
+ *
10884
+ * Not a retry: this is the "everything is done, come back tomorrow" interval.
10885
+ * It exists so the timer keeps a slow heartbeat rather than stopping dead — a
10886
+ * stopped timer cannot notice the local day rolling over, and re-arming from a
10887
+ * one-shot is how a background feature silently dies after its first day.
10888
+ */
10889
+ const AUTO_CHECKIN_IDLE_MS = 18e5;
10890
+ /**
10891
+ * The local calendar day, as `YYYY-MM-DD`.
10892
+ *
10893
+ * LOCAL, not UTC, and deliberately so: the upstream resets its check-in at the
10894
+ * user's local midnight (the card's own wording is 「今天」), so a runner keyed
10895
+ * to UTC would consider 08:00 local a new day and try to claim twice, or think
10896
+ * the day was done while the reward was still claimable.
10897
+ *
10898
+ * Built from the local getters rather than `toISOString()` — the latter is UTC
10899
+ * and would put the boundary in the wrong place for every user not on UTC.
10900
+ */
10901
+ function localDayKey(nowMs) {
10902
+ const date = new Date(nowMs);
10903
+ return `${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, "0")}-${`${date.getDate()}`.padStart(2, "0")}`;
10904
+ }
10905
+ /** A state for a day with nothing done yet. */
10906
+ function emptyAutoCheckinState(day) {
10907
+ return {
10908
+ day,
10909
+ doneAccountIds: [],
10910
+ scopeSize: 0,
10911
+ failures: 0
10912
+ };
10913
+ }
10914
+ /**
10915
+ * Fold one attempt's rows into the day's state.
10916
+ *
10917
+ * `doneAccountIds` accumulates ACROSS attempts within a day, because a batch can
10918
+ * fail halfway: the accounts that answered stay done, and the next tick only
10919
+ * has to retry the rest. Recomputing the set from this attempt alone would make
10920
+ * the runner re-check accounts that already succeeded.
10921
+ *
10922
+ * `failures` counts CONSECUTIVE failures, and an attempt that made progress
10923
+ * resets it — see {@link AutoCheckinState.failures}.
10924
+ */
10925
+ function foldAttempt(previous, rows, nowMs, scopeSize = previous.scopeSize) {
10926
+ const done = new Set(previous.doneAccountIds);
10927
+ let progressed = false;
10928
+ const failures = [];
10929
+ for (const row of rows) {
10930
+ if (row.status === "claimed" || row.status === "already") {
10931
+ if (!done.has(row.accountId)) {
10932
+ done.add(row.accountId);
10933
+ progressed = true;
10934
+ }
10935
+ continue;
10936
+ }
10937
+ if (row.status === "failed") failures.push(row.message ?? row.accountId);
10938
+ }
10939
+ const nextFailures = progressed ? 0 : previous.failures + (failures.length > 0 ? 1 : 0);
10940
+ return {
10941
+ day: previous.day,
10942
+ doneAccountIds: [...done],
10943
+ scopeSize,
10944
+ failures: nextFailures,
10945
+ lastAttemptAtMs: nowMs,
10946
+ ...failures.length === 0 ? {} : { lastError: failures[0] }
10947
+ };
10948
+ }
10949
+ /**
10950
+ * How long to wait before the next attempt.
10951
+ *
10952
+ * Returns `undefined` when there is nothing left to do today — the caller then
10953
+ * arms {@link AUTO_CHECKIN_IDLE_MS} instead of a retry, which is how the timer
10954
+ * stays alive to notice the day rolling over without re-running the batch.
10955
+ *
10956
+ * `pending` is the number of accounts still outstanding. It is passed rather
10957
+ * than derived from the state because only the caller can enumerate the pool
10958
+ * (the state records what is DONE, not what exists).
10959
+ */
10960
+ function nextDelayMs(state, pending) {
10961
+ if (pending === 0) return void 0;
10962
+ const step = AUTO_CHECKIN_BACKOFF_MS[Math.min(state.failures, AUTO_CHECKIN_BACKOFF_MS.length - 1)];
10963
+ return state.failures >= AUTO_CHECKIN_BACKOFF_MS.length ? AUTO_CHECKIN_TAIL_MS : step;
10964
+ }
10965
+ /**
10966
+ * Whether an attempt is due now.
10967
+ *
10968
+ * `pending === 0` is "nothing to do", which is NOT "due": arming a retry for an
10969
+ * empty set would spin the timer every backoff step to discover the same thing.
10970
+ */
10971
+ function isDue(state, pending, nowMs) {
10972
+ if (pending === 0) return false;
10973
+ if (state.lastAttemptAtMs === void 0) return true;
10974
+ const delay = nextDelayMs(state, pending);
10975
+ if (delay === void 0) return false;
10976
+ return nowMs - state.lastAttemptAtMs >= delay;
10977
+ }
10978
+ /**
10979
+ * Build the card's summary.
10980
+ *
10981
+ * Takes the STATE alone: the denominator was recorded when the day's first
10982
+ * attempt ran (see {@link AutoCheckinState.scopeSize}), so the card's poll needs
10983
+ * no credential-store scan and membership edits mid-day cannot silently rewrite
10984
+ * the progress it is reporting.
10985
+ */
10986
+ function summarizeAutoCheckin(state) {
10987
+ const inScope = Math.max(0, state.scopeSize);
10988
+ const done = Math.min(state.doneAccountIds.length, inScope);
10989
+ return {
10990
+ done,
10991
+ total: inScope,
10992
+ pending: Math.max(0, inScope - done),
10993
+ ...state.lastError === void 0 ? {} : { lastError: state.lastError }
10994
+ };
10995
+ }
10996
+ /**
10997
+ * The accounts an attempt should address, in the pool's own order.
10998
+ *
10999
+ * Only members that are not already done. Enterprise members are dropped HERE
11000
+ * rather than left to the batch runner: the runner would report them `skipped`
11001
+ * on every attempt, and while that is harmless it also means every tick would
11002
+ * look like it had work to do. Filtering up front keeps "pending" meaningful.
11003
+ */
11004
+ function pendingTargets(targets, state) {
11005
+ const done = new Set(state.doneAccountIds);
11006
+ return targets.filter((target) => target.enterprise !== true && !done.has(target.accountId));
11007
+ }
11008
+ //#endregion
11009
+ //#region src/auto-checkin-store.ts
11010
+ /**
11011
+ * On-disk memory for the automatic check-in.
11012
+ *
11013
+ * 参考:本仓库 `src/account-pool-store.ts`(`$DSH_HOME` 下
11014
+ * `.workbuddy-pool.<region>.json`,`withFileLock` + `writeFileAtomic`,
11015
+ * `mode: 0o600`)。本模块沿用同一套写入方式与同一份隐私标准。
11016
+ * 改动:存的是**今天签到到哪一步**,因此文件里不含任何 token,也不含账号名
11017
+ * ——只有账号 id 与一句失败原因。
11018
+ *
11019
+ * ## 为什么单独落盘,而不是塞进 settings
11020
+ *
11021
+ * 卡片对用户偏好用的是「草稿 → 保存 → 丢弃草稿」模式。签到进度是插件自己高频
11022
+ * 写的运行状态,不是用户偏好;把它塞进 `regions[region].pool` 会让用户手点一次
11023
+ * 「保存」用几分钟前的草稿把它覆盖回去。这与 `account-pool-store.ts` 当初把
11024
+ * 探测结果搬出 settings 是同一个理由。
11025
+ *
11026
+ * ## 读写从不抛异常
11027
+ *
11028
+ * 自动签到是增强功能。一个损坏的进度文件绝不能让插件启动失败或让卡片渲染不出来
11029
+ * ——最坏情况是「今天当作没签过」,而那次重跑是幂等的(先读状态、已签判 already)。
11030
+ *
11031
+ * @module dsh-connect-workbuddy/auto-checkin-store
11032
+ */
11033
+ /** On-disk format version; readers reject anything else. */
11034
+ const STORE_FORMAT_VERSION = 1;
11035
+ /** Filename prefix for one region's auto-check-in memory. */
11036
+ const AUTO_CHECKIN_PREFIX = ".workbuddy-auto-checkin";
11037
+ /** Whether a parsed value looks like a stored state. */
11038
+ function isState(value) {
11039
+ if (typeof value !== "object" || value === null) return false;
11040
+ const candidate = value;
11041
+ return typeof candidate["day"] === "string" && Array.isArray(candidate["doneAccountIds"]) && candidate["doneAccountIds"].every((id) => typeof id === "string") && typeof candidate["failures"] === "number" && Number.isFinite(candidate["failures"]) && (candidate["lastAttemptAtMs"] === void 0 || typeof candidate["lastAttemptAtMs"] === "number") && (candidate["lastError"] === void 0 || typeof candidate["lastError"] === "string");
11042
+ }
11043
+ /** One region's path for auto-check-in memory. */
11044
+ function autoCheckinStorePath(region) {
11045
+ return join(resolveDshHome(), `${AUTO_CHECKIN_PREFIX}.${region}.json`);
11046
+ }
11047
+ /**
11048
+ * Read every region's stored state.
11049
+ *
11050
+ * Returns `{}` for a missing, unreadable, corrupt, or wrong-version file — see
11051
+ * the module note. A region absent from the result simply has no memory, which
11052
+ * reads as "nothing done today".
11053
+ */
11054
+ async function readAutoCheckinState(region) {
11055
+ let raw;
11056
+ try {
11057
+ raw = await readFile(autoCheckinStorePath(region), "utf8");
11058
+ } catch {
11059
+ return;
11060
+ }
11061
+ let parsed;
11062
+ try {
11063
+ parsed = JSON.parse(raw);
11064
+ } catch {
11065
+ return;
11066
+ }
11067
+ if (typeof parsed !== "object" || parsed === null) return void 0;
11068
+ const document = parsed;
11069
+ if (document.version !== STORE_FORMAT_VERSION) return void 0;
11070
+ const regions = document.regions;
11071
+ if (typeof regions !== "object" || regions === null) return void 0;
11072
+ const state = regions[region];
11073
+ return isState(state) ? state : void 0;
11074
+ }
11075
+ /**
11076
+ * Write one region's state, merging into whatever the file already holds.
11077
+ *
11078
+ * A MERGE rather than a replace for the same reason `writePoolProbes` merges:
11079
+ * the two regions run independently, and a write from one must not erase the
11080
+ * other's memory. Never throws — see the module note.
11081
+ */
11082
+ async function writeAutoCheckinState(region, state) {
11083
+ const path = autoCheckinStorePath(region);
11084
+ try {
11085
+ await withFileLock(path, async () => {
11086
+ const regions = {
11087
+ ...await readDocument(path),
11088
+ [region]: state
11089
+ };
11090
+ await writeFileAtomic(path, `${JSON.stringify({
11091
+ version: STORE_FORMAT_VERSION,
11092
+ regions
11093
+ }, null, 2)}\n`, {
11094
+ mode: 384,
11095
+ dirMode: 448
11096
+ });
11097
+ });
11098
+ } catch {}
11099
+ }
11100
+ /** Read the whole document, for the merge above. */
11101
+ async function readDocument(path) {
11102
+ let raw;
11103
+ try {
11104
+ raw = await readFile(path, "utf8");
11105
+ } catch {
11106
+ return {};
11107
+ }
11108
+ let parsed;
11109
+ try {
11110
+ parsed = JSON.parse(raw);
11111
+ } catch {
11112
+ return {};
11113
+ }
11114
+ if (typeof parsed !== "object" || parsed === null) return {};
11115
+ const document = parsed;
11116
+ if (document.version !== STORE_FORMAT_VERSION) return {};
11117
+ const regions = document.regions;
11118
+ if (typeof regions !== "object" || regions === null) return {};
11119
+ const clean = {};
11120
+ for (const [key, value] of Object.entries(regions)) if (isState(value)) clean[key] = value;
11121
+ return clean;
11122
+ }
11123
+ //#endregion
10160
11124
  //#region src/web-status.ts
10161
11125
  /** Redact token-like content before it crosses to the browser. */
10162
11126
  function safeMessage(error) {
@@ -10182,7 +11146,8 @@ const UPSTREAM_SWITCH_FIELDS = /* @__PURE__ */ new Set([
10182
11146
  "extraInjectedPrefixes",
10183
11147
  "sessionTitle",
10184
11148
  "dropForeignThinking",
10185
- "channelRejectContinue"
11149
+ "channelRejectContinue",
11150
+ "sidebarPanel"
10186
11151
  ]);
10187
11152
  /** A non-null, non-array object: the only shape the slot merge applies to. */
10188
11153
  function isPlainRecord(value) {
@@ -10387,6 +11352,24 @@ async function searchedPaths(store) {
10387
11352
  return {};
10388
11353
  }
10389
11354
  }
11355
+ /**
11356
+ * The vault-read failure for the card, when there is one (issue #199).
11357
+ *
11358
+ * Mirrors `searchedPaths`' defensive shape: a store built without the probe
11359
+ * (an older Host half) or one whose probe throws degrades to the plain status
11360
+ * rather than failing the whole signed-out payload. The raw error is carried
11361
+ * verbatim — it is the ONLY place the #199 lockout (readdir EPERM with
11362
+ * per-path reads still working) becomes visible anywhere in the card data.
11363
+ */
11364
+ async function vaultUnreadableOf(store) {
11365
+ if (typeof store.vaultReadError !== "function") return {};
11366
+ try {
11367
+ const message = await store.vaultReadError();
11368
+ return message === void 0 ? {} : { vaultUnreadable: message };
11369
+ } catch {
11370
+ return {};
11371
+ }
11372
+ }
10390
11373
  /** Reads schemastery's internal `meta.volatile` marker for one top-level field. */
10391
11374
  function volatileFlagOf(field) {
10392
11375
  return Config.dict?.[field]?.meta?.volatile === true;
@@ -10471,6 +11454,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
10471
11454
  const videoToolEnabled = deps.videoToolEnabled?.(region) ?? false;
10472
11455
  const preferredVideoModels = deps.preferredVideoModels?.(region) ?? {};
10473
11456
  const cliBridgeEnabled = deps.cliBridgeEnabled?.() === true;
11457
+ const sidebarPanelEnabled = deps.sidebarPanelEnabled?.() === true;
10474
11458
  const cliBridgeModel = deps.cliBridgeModel?.() ?? "";
10475
11459
  const cliBridgeEffort = deps.cliBridgeEffort?.() ?? "";
10476
11460
  const cliBridgeRegionOrder = deps.cliBridgeRegionOrder?.() ?? "";
@@ -10489,6 +11473,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
10489
11473
  videoToolEnabled,
10490
11474
  preferredVideoModels,
10491
11475
  cliBridgeEnabled,
11476
+ sidebarPanelEnabled,
10492
11477
  cliBridgeModel,
10493
11478
  cliBridgeEffort,
10494
11479
  cliBridgeRegionOrder,
@@ -10512,6 +11497,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
10512
11497
  videoToolEnabled,
10513
11498
  preferredVideoModels,
10514
11499
  cliBridgeEnabled,
11500
+ sidebarPanelEnabled,
10515
11501
  cliBridgeModel,
10516
11502
  cliBridgeEffort,
10517
11503
  cliBridgeRegionOrder,
@@ -10519,6 +11505,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
10519
11505
  ...lastForeignThinking === void 0 ? {} : { lastForeignThinking },
10520
11506
  busyLevels,
10521
11507
  ...await store.selectionLost() ? { selectionLost: true } : {},
11508
+ ...await vaultUnreadableOf(store),
10522
11509
  ...webAccounts.length === 0 ? await searchedPaths(store) : {}
10523
11510
  };
10524
11511
  }
@@ -10538,6 +11525,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
10538
11525
  videoToolEnabled,
10539
11526
  preferredVideoModels,
10540
11527
  cliBridgeEnabled,
11528
+ sidebarPanelEnabled,
10541
11529
  cliBridgeModel,
10542
11530
  cliBridgeEffort,
10543
11531
  cliBridgeRegionOrder,
@@ -10686,6 +11674,11 @@ async function workBuddyWebPool(deps, region, fast = false) {
10686
11674
  return {
10687
11675
  enabled: preferences.enabled,
10688
11676
  checkinSupported: pool.checkinSupported?.(region) === true,
11677
+ ...preferences.autoCheckin !== true ? {} : { autoCheckin: true },
11678
+ ...(() => {
11679
+ const today = pool.autoCheckinToday?.(region);
11680
+ return today === void 0 ? {} : { autoCheckinToday: today };
11681
+ })(),
10689
11682
  ...target.modelId === void 0 ? {} : { targetModelId: target.modelId },
10690
11683
  ...target.staleModelId === void 0 ? {} : { staleTargetModelId: target.staleModelId },
10691
11684
  targetModelSource: target.source,
@@ -10853,10 +11846,13 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
10853
11846
  if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
10854
11847
  if (!requireLoopback(req, res)) return;
10855
11848
  if (deps.discoverModels === void 0) return json(res, 503, { error: "model refresh unavailable" });
11849
+ if (deps.persistModels === void 0) return json(res, 503, { error: "model refresh cannot be persisted" });
10856
11850
  const region = requestRegion(req, res);
10857
11851
  if (region === void 0) return;
10858
11852
  try {
10859
- json(res, 200, { models: (await deps.discoverModels(region)).map((model) => toWebModel(model, deps.contextBudgets(region))) });
11853
+ const models = await deps.discoverModels(region);
11854
+ await deps.persistModels(region, models);
11855
+ json(res, 200, { models: models.map((model) => toWebModel(model, deps.contextBudgets(region))) });
10860
11856
  } catch (error) {
10861
11857
  json(res, 500, { error: safeMessage(error) });
10862
11858
  }
@@ -11092,7 +12088,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
11092
12088
  req.on("error", reject);
11093
12089
  });
11094
12090
  const field = body.field;
11095
- if (field !== "regions" && field !== "accounts" && field !== "cliBridge" && !(typeof field === "string" && UPSTREAM_SWITCH_FIELDS.has(field))) return json(res, 400, { error: "field must be regions, accounts, cliBridge, usageIdentity, keepPromptLast, extraInjectedPrefixes, sessionTitle, dropForeignThinking or channelRejectContinue" });
12091
+ if (field !== "regions" && field !== "accounts" && field !== "cliBridge" && !(typeof field === "string" && UPSTREAM_SWITCH_FIELDS.has(field))) return json(res, 400, { error: "field must be regions, accounts, cliBridge, usageIdentity, keepPromptLast, extraInjectedPrefixes, sessionTitle, dropForeignThinking, channelRejectContinue or sidebarPanel" });
11096
12092
  const row = settings.describe().find((r) => String(r.ns).includes("workbuddy"));
11097
12093
  if (row === void 0) return json(res, 503, { error: "workbuddy namespace missing from describe()" });
11098
12094
  const current = field === "regions" ? regionsMapOf(row.value?.[field]) : unwrapVolatileDeep(row.value?.[field] ?? {});
@@ -11373,7 +12369,12 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
11373
12369
  });
11374
12370
  if (req.method === "GET") {
11375
12371
  try {
11376
- json(res, 200, await port.read());
12372
+ const report = await port.read();
12373
+ const enabled = await port.readEnabled();
12374
+ json(res, 200, enabled === void 0 ? report : {
12375
+ ...report,
12376
+ sdkEnabled: enabled
12377
+ });
11377
12378
  } catch (error) {
11378
12379
  json(res, 500, {
11379
12380
  reason: "device-sdk-failed",
@@ -11394,13 +12395,26 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
11394
12395
  return json(res, 200, { token });
11395
12396
  }
11396
12397
  if (action === "refresh") return json(res, 200, await port.refresh());
12398
+ /**
12399
+ * `?action=enable` / `?action=disable` —— SDK 总开关。
12400
+ *
12401
+ * 用两个动作名而不是 `?enabled=1`:这个路由的其余动作都是**动词**,
12402
+ * 而一个布尔查询参数会让"没传"和"传了空"看起来一样。
12403
+ */
12404
+ if (action === "enable" || action === "disable") {
12405
+ if (!await port.writeEnabled(action === "enable")) return json(res, 501, {
12406
+ reason: "settings-unavailable",
12407
+ error: "this host has no settings write path"
12408
+ });
12409
+ return json(res, 200, { sdkEnabled: action === "enable" });
12410
+ }
11397
12411
  } catch (error) {
11398
12412
  return json(res, 500, {
11399
12413
  reason: "device-sdk-failed",
11400
12414
  error: safeMessage(error)
11401
12415
  });
11402
12416
  }
11403
- json(res, 400, { error: "action must be 'refresh' or 'reveal'" });
12417
+ json(res, 400, { error: "action must be 'refresh', 'reveal', 'enable' or 'disable'" });
11404
12418
  }
11405
12419
  });
11406
12420
  return () => {
@@ -11485,6 +12499,25 @@ const poolConfig = z.object({
11485
12499
  */
11486
12500
  probeInputTokens: z.number().step(1).default(0).description("Input tokens each test probe sends: 10000 / 20000 / 30000 / 50000 / 100000. Bigger probes catch a rate limit real conversations would hit, but cost more credit per test and may mark an account unusable for large requests only. 0 uses the measured default (25000)"),
11487
12501
  memberAccountIds: z.array(z.string()).default([]).description("Account ids checked into this pool (opt-in; empty means the pool covers nothing)"),
12502
+ /**
12503
+ * Whether the plugin claims the daily check-in by itself (opt-IN, default off).
12504
+ *
12505
+ * OFF BY DEFAULT, and that is the whole design (issue #191). Claiming a daily
12506
+ * reward is a real WRITE on the user's account, and this plugin shipped with no
12507
+ * automatic check-in precisely so it would never make that decision for
12508
+ * someone. The reasoning still holds — what changed is that the user can now
12509
+ * make the decision once and have it honoured.
12510
+ *
12511
+ * The alternative was worse than it looks: a missed day resets the streak to
12512
+ * zero (the reporter was at 32), and the claim costs no credits and is
12513
+ * idempotent upstream. So the trade is "one switch" against "a 32-day streak
12514
+ * lost to a weekend".
12515
+ *
12516
+ * Only the CN region has a check-in; the switch is hidden elsewhere and the
12517
+ * runner refuses to start there, so a hand-edited profile cannot make the
12518
+ * background path spend a request per account per day learning a refusal.
12519
+ */
12520
+ autoCheckin: z.boolean().default(false).description("Claim the daily check-in automatically for the accounts checked into this pool (opt-in). Idempotent: an account already checked in today is reported, never re-claimed. Only the CN region has a daily check-in."),
11488
12521
  orderAccountIds: z.array(z.string()).default([]).description("The user's hand-ordered pool order, as account ids. Independent of membership: an id need not be checked in (it only takes effect once the account is a member), and ids not listed sort last. Separate from memberAccountIds so reordering never conflicts with, or is destroyed by, a membership edit.")
11489
12522
  });
11490
12523
  const regionStateConfig = z.object({
@@ -11583,9 +12616,11 @@ const regionStateConfig = z.object({
11583
12616
  * not have is a hard `UNSUPPORTED_REASONING_EFFORT` (issue #90).
11584
12617
  *
11585
12618
  * An ABSENT key means "follow this model's own upstream `defaultEffort`",
11586
- * which every model in the live catalog declares (measured 2026-10-30: `high`
11587
- * on thirteen of fifteen, `max` on the two five-tier ones). That is NOT the
11588
- * same as "no opinion": the adapter must still pin SOMETHING for the request
12619
+ * which the great majority of the live catalog declares (measured 2026-10-30:
12620
+ * `high` on thirteen of fifteen, `max` on the two five-tier ones) — and where
12621
+ * the upstream declares none, "follow this model's own MIDDLE tier", never its
12622
+ * weakest one (qoder 518ecbb's rule; see `src/default-effort.ts`). That is NOT
12623
+ * the same as "no opinion": the adapter must still pin SOMETHING for the request
11589
12624
  * paths that name no tier, and issue #83 is the record of what happens when
11590
12625
  * that is left to pi-ai's level map — it filled in `off`, the upstream answers
11591
12626
  * 400 / 11133, and `/compact` failed.
@@ -11675,6 +12710,7 @@ const Config = z.object({
11675
12710
  imageModelIds: z.array(z.string()).default([]).description("Deprecated: pre-region-split CN image opt-in"),
11676
12711
  contextBudgets: z.dict(z.number().step(1).min(1)).default({}).description("Deprecated: pre-region-split CN context budgets"),
11677
12712
  cliBridge: asVolatile(cliBridgeConfig.default({}).description("Optional CodeBuddy CLI route; off by default and independent of the providers")),
12713
+ sidebarPanel: asVolatile(z.boolean().default(false).description("Add a WorkBuddy panel to the DSH sidebar: a nav row that opens the credits / accounts / model catalog as a full page. Off by default — the row claims a global sidebar seat shared by every bundle, and the Plugins page already reaches the same content.")),
11678
12714
  channelPerturbation: asVolatile(z.union([
11679
12715
  z.const("off"),
11680
12716
  z.const("failure"),
@@ -11682,6 +12718,7 @@ const Config = z.object({
11682
12718
  ]).default("failure").description("When to perturb scanned messages with invisible characters: \"off\" only rescues after a channel-gate refusal, \"failure\" (default) learns from a successful rescue and starts later requests perturbed, \"always\" starts every request with the dense rescue for a gateway whose plain attempt is guaranteed to fail.")),
11683
12719
  usageIdentity: asVolatile(z.boolean().default(false).description("Send the chat conversation ids in the official client's 32-hex UUIDv7 shape and add a mirroring X-Request-ID. Off by default — it is a display alignment measured by a reporter, not by this plugin, and the chat channel identity (User-Agent) and request body never change.")),
11684
12720
  wireProfile: asVolatile(z.union([z.const("conservative"), z.const("balanced")]).default("balanced").description("Outbound identity profile. \"balanced\" (default) makes every request claim the same client (WorkBuddy product/IDE/agent headers, X-CodeBuddy-Request, Accept-Language, X-Root-Request-ID, and a per-account X-Machine-ID/X-Session-ID pair) and gives the billing routes a User-Agent plus Origin/Referer. \"conservative\" restores the 5.16.0 bytes exactly, including X-Product: SaaS.")),
12721
+ deviceSdkEnabled: asVolatile(z.boolean().default(false).description("Master switch for the real-device SDK. OFF by default, matching the default Virtual tier: turning it on makes the plugin discover the installed desktop SDK, fetch its device token in a background child process and keep it fresh. A capability that reaches into a third party's native modules on your machine should be opted into, and with the Virtual tier (the default) the token it fetches would never be sent anyway. On: discover, fetch, prewarm. Off: none of that — no discovery, no child process, no prewarming — so the Real tier has no token to send; the Virtual tier is unaffected (its ids derive from the local salt).")),
11685
12722
  deviceToken: asVolatile(z.object({
11686
12723
  file: z.string().default(""),
11687
12724
  ttlMs: z.number().step(1).min(1e3).default(3e5)
@@ -11737,6 +12774,42 @@ function regionEnabled(config, region) {
11737
12774
  /** Every region, in card tab order. */
11738
12775
  const REGION_KEYS = ["cn", "global"];
11739
12776
  /**
12777
+ * 「真实值」档在这台机器上能不能真的工作,以及为什么不能。
12778
+ *
12779
+ * ## 为什么不让界面自己判断平台
12780
+ *
12781
+ * 客户端能拿到 `sdk.platform`,但**平台不是判据**。macOS 上 SDK 能被发现、
12782
+ * `probe` 也答 `ready`,真正坏掉的是取 token 那一环:SDK 向 dispatch 主队列
12783
+ * `dispatch_sync`,而纯 libuv 子进程永不排空那个队列(`sample` 栈实测,见
12784
+ * CHANGELOG 的「macOS 现状如实记录」)。于是「darwin → 禁用」会把一台**没装**
12785
+ * 桌面端的 mac 和一台装了的 mac 说成同一件事,而它们的用户该做的事完全不同。
12786
+ *
12787
+ * ## 为什么现在还写死
12788
+ *
12789
+ * 这是一个**已知的、非本平台的**缺陷,不是运行时可以测出来的:真去测就要起子进程
12790
+ * 等 15 秒超时,而这一页每次打开都会拉一次设置。写成常量意味着它是可以被人替换
12791
+ * 的显式声明,而不是散在三个组件里的 `if (platform === 'darwin')`。
12792
+ *
12793
+ * ⚠️ 修好 `dispatch_sync` 那条路之后,**这里必须跟着改**,否则界面会继续劝退一个
12794
+ * 已经能用的功能。修法不在本次范围(需要一个排空主队列的伴生原生模块)。
12795
+ *
12796
+ * `state`:
12797
+ * - `available` —— 能取到 token,切成「真实值」就能用;
12798
+ * - `broken` —— 这套 SDK 在本平台取不到 token,切过去只会降级,界面上应禁用
12799
+ * 并说明原因;
12800
+ * - `unavailable` —— 本平台没有这条取链(不预期出现,留作兜底)。
12801
+ */
12802
+ function realTierAvailabilityFor(platform) {
12803
+ return platform === "darwin" ? {
12804
+ state: "broken",
12805
+ platform: "darwin"
12806
+ } : {
12807
+ state: "available",
12808
+ platform
12809
+ };
12810
+ }
12811
+ const REAL_TIER_AVAILABILITY = realTierAvailabilityFor(process.platform);
12812
+ /**
11740
12813
  * The region that owns the image tool right now, or `undefined` when no region
11741
12814
  * has it switched on.
11742
12815
  *
@@ -11854,12 +12927,29 @@ function apply(ctx, config) {
11854
12927
  * `dirSource` 让卡片上填的目录**下一次观察就生效**(作者意见 #1):句柄活到
11855
12928
  * 卸载,而设置随时会变,所以目录每次 `probe` 现问一次。`deviceProfiles` 读盘有
11856
12929
  * 5 秒缓存,保存会立即失效它。
12930
+ *
12931
+ * ⚠️ **总开关优先于预热**(`deviceSdkEnabled`):关掉就不建定时器、不预取。
12932
+ * 留着 `createTuringSdk()` 本身是因为端口(`createDeviceSdkPort`)仍要能回答
12933
+ * "这个功能被关掉了"——它读到的是 `disabled` 状态,而不是一块空白面板。
12934
+ */
12935
+ /**
12936
+ * 总开关:**默认关**(`default(false)`)。
12937
+ *
12938
+ * 与档位默认值一致:档位默认「虚拟值」本来就不发这个 token,那么默认去发现
12939
+ * SDK、起子进程、每 10 分钟取一次,取到的东西一次也用不上。更一般地说,一个
12940
+ * 会碰用户机器上第三方原生模块的能力,默认该由用户主动打开。
12941
+ *
12942
+ * `=== true` 而不是 `!== false`:`undefined`(老配置文件里没有这个字段)必须
12943
+ * 落到"关",与 `default(false)` 同一个答案。写成 `!== false` 会让"未设置"和
12944
+ * "显式开启"分叉,升级后老用户静默拿到与 schema 默认相反的行为。
11857
12945
  */
12946
+ const deviceSdkEnabled = unwrapVolatile(config.deviceSdkEnabled) === true;
11858
12947
  const turing = createTuringSdk({
11859
12948
  productVersion: APP_VERSION,
11860
- dirSource: () => deviceProfiles.sdkDir()
12949
+ dirSource: () => deviceProfiles.sdkDir(),
12950
+ enabled: deviceSdkEnabled
11861
12951
  });
11862
- turing.startAutoRefresh();
12952
+ if (deviceSdkEnabled) turing.startAutoRefresh();
11863
12953
  ctx.effect(() => () => {
11864
12954
  turing.stopAutoRefresh();
11865
12955
  });
@@ -12048,7 +13138,7 @@ function apply(ctx, config) {
12048
13138
  const savedOffModelIds = (state, roster) => state.offModelIds ?? defaultOffModelIds(roster);
12049
13139
  const displayModels = (value, region) => {
12050
13140
  const state = regionStateOf(value, region);
12051
- const live = stacks[region]?.catalog?.current() ?? [];
13141
+ const live = stacks[region]?.catalog?.hasLiveRoster() === true ? stacks[region].catalog.current() : [];
12052
13142
  return resolveRoster(state.lastCatalog ?? [], live, region);
12053
13143
  };
12054
13144
  /**
@@ -12144,7 +13234,7 @@ function apply(ctx, config) {
12144
13234
  * request. The read side is already correct without it, so the repair is
12145
13235
  * an optimisation that heals the profile, never a precondition.
12146
13236
  */
12147
- const repairRegionCatalog = async (region, live) => {
13237
+ const repairRegionCatalog = async (region, live, options = {}) => {
12148
13238
  if (live.length === 0) return;
12149
13239
  const saved = regionStateOf(current(), region).lastCatalog ?? [];
12150
13240
  const repaired = (isUnconfiguredFallbackSnapshot(saved, region) ? withoutRouters(live) : repairedCatalog(saved, live)).map((model) => {
@@ -12157,6 +13247,7 @@ function apply(ctx, config) {
12157
13247
  try {
12158
13248
  await writeRegionCatalog(hostSettings(), settingsNs, region, repaired);
12159
13249
  } catch (error) {
13250
+ if (options.strict === true) throw error;
12160
13251
  ctx.logger.warn(`dsh-connect-workbuddy: could not repair the ${region} model directory against the live roster`, error);
12161
13252
  }
12162
13253
  };
@@ -12204,6 +13295,45 @@ function apply(ctx, config) {
12204
13295
  return client.fetchModels(credential, signal, keep);
12205
13296
  };
12206
13297
  /**
13298
+ * Record a refresh the card just asked for (issue #214).
13299
+ *
13300
+ * The reported bug, in one sentence: the refresh button was the only code
13301
+ * path that read the CURRENT upstream prices, and it discarded them. So the
13302
+ * fresh numbers were visible only inside the response to that one press —
13303
+ * the card went on rendering `displayModels()` (the saved directory) and the
13304
+ * runtime went on serving the catalog built at startup, which is why the
13305
+ * reporter saw 0.69 from `models/refresh` and 0.79 from `usage` on the same
13306
+ * host at the same moment.
13307
+ *
13308
+ * TWO WRITES, and they are deliberately different:
13309
+ *
13310
+ * 1. the live CATALOG, so the running provider and the picker's price
13311
+ * labels follow the upstream immediately — this is the in-memory answer
13312
+ * the user was looking at when they pressed the button;
13313
+ * 2. the saved DIRECTORY, through the Host's merge, so the price survives
13314
+ * the settings card being closed and the harness being restarted.
13315
+ *
13316
+ * What is NOT written is the user's selection. `enabledModelIds`,
13317
+ * `imageModelIds`, `contextBudgets` and `defaultThinkingEfforts` remain the
13318
+ * card's DRAFT until Save — the card's own refresh handler re-maps them onto
13319
+ * the fresh rows and keeps them dirty, and the reporter's report shows the
13320
+ * draft list containing models that were not ticked. Committing them here
13321
+ * would turn one press of "refresh" into an unrequested "save".
13322
+ *
13323
+ * `origin: 'upstream'` on the catalog write is correct and load-bearing: this
13324
+ * roster IS a fresh upstream answer, which is what lets `hasLiveRoster()`
13325
+ * become true and every other reader stop mistaking the static table for the
13326
+ * upstream (see `displayModels`).
13327
+ */
13328
+ const persistRefreshedModels = async (region, models) => {
13329
+ if (models.length === 0) return;
13330
+ const state = regionStateOf(current(), region);
13331
+ const next = withEffectiveOff(withImageSelection(deriveCatalog(models, new Set(state.enabledModelIds ?? []), state.contextBudgets ?? {}), effectiveImageIds(state, models)), new Set(savedOffModelIds(state, models)));
13332
+ stacks[region].catalog.set(next);
13333
+ invalidateCatalog();
13334
+ await repairRegionCatalog(region, models, { strict: true });
13335
+ };
13336
+ /**
12207
13337
  * The region's MEDIA models, cached briefly for the card's read-only roster.
12208
13338
  *
12209
13339
  * Two callers ask the same question — the image tool (to validate a model
@@ -12287,13 +13417,14 @@ function apply(ctx, config) {
12287
13417
  for (const region of REGION_KEYS) {
12288
13418
  stacks[region].store.setDesktopPath(authFile);
12289
13419
  stacks[region].store.selectAccount(effectiveAccountFor(region, value));
12290
- stacks[region].catalog.set(configuredModels(value, region, stacks[region].catalog.current()));
13420
+ const liveRoster = stacks[region].catalog.hasLiveRoster() ? stacks[region].catalog.current() : [];
13421
+ stacks[region].catalog.set(configuredModels(value, region, liveRoster), "derived");
12291
13422
  }
12292
13423
  invalidateCatalog();
12293
13424
  for (const region of REGION_KEYS) (async () => {
12294
13425
  const live = await restampBusyLevels(region, stacks[region].catalog.current());
12295
13426
  if (live.length === 0) return;
12296
- stacks[region].catalog.set(live);
13427
+ stacks[region].catalog.set(live, "derived");
12297
13428
  invalidateCatalog();
12298
13429
  })();
12299
13430
  syncRegionRegistration(value);
@@ -12323,7 +13454,8 @@ function apply(ctx, config) {
12323
13454
  let accounts;
12324
13455
  try {
12325
13456
  accounts = await stacks[region].store.accounts();
12326
- } catch {
13457
+ } catch (error) {
13458
+ ctx.logger("workbuddy").warn("region usability scan failed for %s: %s", region, error);
12327
13459
  continue;
12328
13460
  }
12329
13461
  if (stacks[region].catalog.setRegionUsable(accounts.length > 0)) invalidateCatalog();
@@ -12564,12 +13696,19 @@ function apply(ctx, config) {
12564
13696
  const withDerived = async (settings) => {
12565
13697
  try {
12566
13698
  const derived = await describeDerivedDevices(await deviceAccounts());
12567
- return derived === void 0 ? settings : {
13699
+ return derived === void 0 ? {
12568
13700
  ...settings,
12569
- derived
13701
+ realTier: REAL_TIER_AVAILABILITY
13702
+ } : {
13703
+ ...settings,
13704
+ derived,
13705
+ realTier: REAL_TIER_AVAILABILITY
12570
13706
  };
12571
13707
  } catch {
12572
- return settings;
13708
+ return {
13709
+ ...settings,
13710
+ realTier: REAL_TIER_AVAILABILITY
13711
+ };
12573
13712
  }
12574
13713
  };
12575
13714
  return registerWorkBuddyStatusRoute(webCtx, {
@@ -12622,7 +13761,18 @@ function apply(ctx, config) {
12622
13761
  */
12623
13762
  deviceSdk: createDeviceSdkPort({
12624
13763
  sdk: turing,
12625
- mode: async () => (await readDeviceSettings()).mode
13764
+ mode: async () => (await readDeviceSettings()).mode,
13765
+ /**
13766
+ * 总开关走插件配置(`Config.deviceSdkEnabled`),不走设备设置文件。
13767
+ *
13768
+ * `read` 取的是 `current()`——也就是宿主交给 `apply()` 的那份活的引用,
13769
+ * 所以 `ctx.settings.update` 写完它就能读到新值(`asVolatile` 会就地改)。
13770
+ * 回 `undefined` 让卡片把开关标成不可用,而不是把它画成"关"。
13771
+ */
13772
+ enabled: {
13773
+ read: async () => unwrapVolatile(config.deviceSdkEnabled) !== false,
13774
+ write: writeDeviceSdkEnabled
13775
+ }
12626
13776
  }),
12627
13777
  /**
12628
13778
  * Why each of the region's accounts cannot serve right now, for the composer
@@ -12658,6 +13808,7 @@ function apply(ctx, config) {
12658
13808
  contextBudgets: (region) => regionStateOf(current(), region).contextBudgets ?? {},
12659
13809
  defaultThinkingEfforts: (region) => regionStateOf(current(), region).defaultThinkingEfforts ?? {},
12660
13810
  discoverModels,
13811
+ persistModels: persistRefreshedModels,
12661
13812
  /**
12662
13813
  * This region's first-sighting readout, the data behind the composer pill's
12663
13814
  * "· N 新模型" segment.
@@ -12702,6 +13853,15 @@ function apply(ctx, config) {
12702
13853
  */
12703
13854
  cliBridgeEnabled: () => unwrapVolatile(current().cliBridge)?.enabled === true,
12704
13855
  /**
13856
+ * Whether the optional DSH sidebar panel is switched on (PR #188).
13857
+ *
13858
+ * GLOBAL, so it takes no region. `=== true` like `cliBridgeEnabled`, not
13859
+ * `!== false`: the row claims a `sidebar.panellist` seat and a `main` page
13860
+ * that every installed bundle shares, so an absent value must read as "not
13861
+ * asked for" rather than as consent. Volatile, hence the unwrap.
13862
+ */
13863
+ sidebarPanelEnabled: () => unwrapVolatile(current().sidebarPanel) === true,
13864
+ /**
12705
13865
  * The model / reasoning effort the optional CodeBuddy CLI route runs on.
12706
13866
  *
12707
13867
  * `cliBridge` is volatile, hence the unwrap; absent keys read as `''` —
@@ -13025,6 +14185,20 @@ function apply(ctx, config) {
13025
14185
  * no equivalent here, so its card must not offer the action.
13026
14186
  */
13027
14187
  checkinSupported: (region) => region === "cn",
14188
+ /**
14189
+ * What the background check-in has settled today (issue #191).
14190
+ *
14191
+ * Answers from the runner's in-memory state, which is the same object the
14192
+ * tick updates — so the card never has to guess which accounts a previous
14193
+ * attempt already handled. `undefined` when the switch is off or nothing
14194
+ * has run, which the card renders as "no status line" rather than "0 of N".
14195
+ */
14196
+ autoCheckinToday: (region) => {
14197
+ if (!autoCheckinEnabled(region)) return void 0;
14198
+ const state = autoCheckinState[region];
14199
+ if (state === void 0) return void 0;
14200
+ return summarizeAutoCheckin(state);
14201
+ },
13028
14202
  checkin: async (region) => {
13029
14203
  const rows = await checkinAllAccounts(await poolTargets(region), poolRunnerDeps(region));
13030
14204
  for (const row of rows) {
@@ -13390,6 +14564,7 @@ function apply(ctx, config) {
13390
14564
  const recordAccountFailure = async (region, accountId, failure) => {
13391
14565
  if (!poolPreferencesOf(current(), region).enabled) return;
13392
14566
  if (failure.kind === "client") return;
14567
+ if (failure.status === 0) return;
13393
14568
  const members = poolPreferencesOf(current(), region).memberAccountIds;
13394
14569
  if (members.length > 0 && !members.includes(accountId)) return;
13395
14570
  const outcome = outcomeOfFailure(failure.status, failure.message);
@@ -13522,7 +14697,8 @@ function apply(ctx, config) {
13522
14697
  targetModelId: pool?.targetModelId ?? "",
13523
14698
  ...probeInputTokens === void 0 ? {} : { probeInputTokens },
13524
14699
  memberAccountIds: pool?.memberAccountIds ?? [],
13525
- orderAccountIds: pool?.orderAccountIds ?? []
14700
+ orderAccountIds: pool?.orderAccountIds ?? [],
14701
+ autoCheckin: pool?.autoCheckin === true
13526
14702
  };
13527
14703
  };
13528
14704
  /**
@@ -13580,12 +14756,163 @@ function apply(ctx, config) {
13580
14756
  }
13581
14757
  };
13582
14758
  }
14759
+ /**
14760
+ * The automatic daily check-in (issue #191).
14761
+ *
14762
+ * A single timer per region, armed only when the user ticks the switch. The
14763
+ * rules live in `src/auto-checkin.ts` (pure) and the memory in
14764
+ * `src/auto-checkin-store.ts`; this block owns only the two things those
14765
+ * modules deliberately do not: a real clock and a real batch call.
14766
+ *
14767
+ * ## Why a re-arming one-shot instead of `setInterval`
14768
+ *
14769
+ * The interval is not constant: a failure walks a widening backoff, a finished
14770
+ * day idles, and a day rollover resets everything. `setInterval` can only
14771
+ * express a fixed period, so the delay is computed per tick and the timer is
14772
+ * re-armed from the tick's own `finally`. The alternative — a 30-minute
14773
+ * `setInterval` plus "is it due?" inside — would sleep past the short first
14774
+ * retries (30 s, 60 s) and make a transient fault look like a 30-minute outage.
14775
+ *
14776
+ * ## Why the timer never stops
14777
+ *
14778
+ * Even when the day is finished the timer re-arms at {@link AUTO_CHECKIN_IDLE_MS}.
14779
+ * A timer that stops after its first successful day cannot notice the next
14780
+ * local midnight, so the feature would silently work exactly once — the
14781
+ * failure mode this whole design exists to avoid. The idle tick costs no
14782
+ * request: `isDue` answers "nothing pending" before any I/O.
14783
+ *
14784
+ * ## Why it is safe to run alongside a manual press
14785
+ *
14786
+ * `checkinAllAccounts` reads status first and reports `already` WITHOUT a
14787
+ * claim, so two overlapping runs cannot double-claim. The batch is also
14788
+ * serial, so the worst case is one redundant status request per account.
14789
+ */
14790
+ const autoCheckinTimers = {};
14791
+ /** In-memory mirror of the on-disk state, so a tick does not re-read the file. */
14792
+ const autoCheckinState = {};
14793
+ /** Guards against a second tick landing while one is still running. */
14794
+ const autoCheckinRunning = {};
14795
+ /** Whether the user has asked for the background check-in on this region. */
14796
+ function autoCheckinEnabled(region) {
14797
+ if (!autoCheckinRegions().includes(region)) return false;
14798
+ return poolPreferencesOf(current(), region).autoCheckin === true;
14799
+ }
14800
+ /**
14801
+ * One tick: decide, run, fold, persist, re-arm.
14802
+ *
14803
+ * Deliberately never throws — a background feature that can take down `apply`
14804
+ * (or a later tick) over a disk error would be worse than not having it.
14805
+ */
14806
+ async function autoCheckinTick(region) {
14807
+ if (autoCheckinRunning[region] === true) return;
14808
+ autoCheckinRunning[region] = true;
14809
+ try {
14810
+ if (!autoCheckinEnabled(region)) return;
14811
+ const nowMs = Date.now();
14812
+ const today = localDayKey(nowMs);
14813
+ const stored = autoCheckinState[region] ?? await readAutoCheckinState(region);
14814
+ const state = stored === void 0 || stored.day !== today ? emptyAutoCheckinState(today) : stored;
14815
+ autoCheckinState[region] = state;
14816
+ const targets = pendingTargets(await poolTargets(region), state);
14817
+ if (!isDue(state, targets.length, nowMs)) {
14818
+ scheduleAutoCheckin(region, AUTO_CHECKIN_IDLE_MS);
14819
+ return;
14820
+ }
14821
+ const rows = await checkinAllAccounts(targets, poolRunnerDeps(region));
14822
+ for (const row of rows) {
14823
+ if (row.status === "failed") continue;
14824
+ const cached = checkinStateCache[region];
14825
+ if (cached !== void 0) delete cached[row.accountId];
14826
+ }
14827
+ const folded = foldAttempt(state, rows, nowMs, targets.length + state.doneAccountIds.length);
14828
+ autoCheckinState[region] = folded;
14829
+ await writeAutoCheckinState(region, folded);
14830
+ const pending = pendingTargets(await poolTargets(region), folded).length;
14831
+ scheduleAutoCheckin(region, nextDelayMs(folded, pending) ?? 18e5);
14832
+ } catch (error) {
14833
+ ctx.logger.warn(`dsh-connect-workbuddy: auto check-in tick failed (${region})`, error);
14834
+ scheduleAutoCheckin(region, AUTO_CHECKIN_IDLE_MS);
14835
+ } finally {
14836
+ autoCheckinRunning[region] = false;
14837
+ }
14838
+ }
14839
+ /** Arm the next tick, replacing any pending one. */
14840
+ function scheduleAutoCheckin(region, delayMs) {
14841
+ const existing = autoCheckinTimers[region];
14842
+ if (existing !== void 0) clearTimeout(existing);
14843
+ const timer = setTimeout(() => {
14844
+ autoCheckinTick(region);
14845
+ }, delayMs);
14846
+ timer.unref?.();
14847
+ autoCheckinTimers[region] = timer;
14848
+ }
14849
+ /**
14850
+ * Arm or disarm every region to match the saved switches.
14851
+ *
14852
+ * Called once at `apply` and again on every settings change, so flipping the
14853
+ * switch takes effect without a restart. Disarming CLEARS the timer rather
14854
+ * than leaving it to notice: an off switch must stop the work immediately, not
14855
+ * at the next tick.
14856
+ */
14857
+ function syncAutoCheckin() {
14858
+ for (const region of autoCheckinRegions()) {
14859
+ if (autoCheckinEnabled(region)) {
14860
+ if (autoCheckinTimers[region] === void 0) scheduleAutoCheckin(region, 0);
14861
+ continue;
14862
+ }
14863
+ const timer = autoCheckinTimers[region];
14864
+ if (timer !== void 0) {
14865
+ clearTimeout(timer);
14866
+ delete autoCheckinTimers[region];
14867
+ }
14868
+ }
14869
+ }
14870
+ /** Stop every timer; called on unload. */
14871
+ function stopAutoCheckin() {
14872
+ for (const region of autoCheckinRegions()) {
14873
+ const timer = autoCheckinTimers[region];
14874
+ if (timer !== void 0) clearTimeout(timer);
14875
+ delete autoCheckinTimers[region];
14876
+ }
14877
+ }
14878
+ syncAutoCheckin();
14879
+ ctx.effect(() => () => {
14880
+ stopAutoCheckin();
14881
+ });
13583
14882
  ctx.inject(["settings"], (sctx) => {
13584
14883
  const settings = sctx.settings;
13585
14884
  ctx.effect(() => settings.configure({ auto: true }, ctx.fiber));
13586
14885
  });
14886
+ /**
14887
+ * The one settings WRITE the card is allowed to make: the SDK master switch.
14888
+ *
14889
+ * Resolved lazily (not captured at mount) because `settings` is an optional
14890
+ * service and the card may ask before that service is present — a captured
14891
+ * `undefined` would make the switch permanently read-only on that host.
14892
+ * Returns `false` rather than throwing when the host has no `update`: the
14893
+ * panel renders the same switch either way, and a thrown error there would
14894
+ * surface as "saving failed" for a capability the host simply lacks.
14895
+ *
14896
+ * ⚠️ The namespace MUST be `settingsNs` — the Loader entry id the host
14897
+ * actually serves — never the declared `WORKBUDDY_SETTINGS_NS` fallback. The
14898
+ * settings service resolves an entry by EXACT id
14899
+ * (`entries().find(row => row.options.id === ns)`) and throws
14900
+ * `No configurable plugin entry "workbuddy"` for a name it does not serve.
14901
+ * Every other write path here already threads `settingsNs`
14902
+ * (`writeRegionCatalog`, `healRegionsField`, the `__save` route); this one
14903
+ * shipped with the bare constant, so on the live Desktop host — whose entry is
14904
+ * `include:dsh-connect-workbuddy` — the switch answered HTTP 500 and could
14905
+ * never be turned on.
14906
+ */
14907
+ const writeDeviceSdkEnabled = async (enabled) => {
14908
+ const host = ctx.get("settings");
14909
+ if (host?.update === void 0) return false;
14910
+ await host.update(settingsNs, { deviceSdkEnabled: enabled });
14911
+ return true;
14912
+ };
13587
14913
  ctx.on("loader/volatile-update", () => {
13588
14914
  applySelection(current());
14915
+ syncAutoCheckin();
13589
14916
  });
13590
14917
  applySelection(config);
13591
14918
  (async () => {
@@ -13711,7 +15038,6 @@ function apply(ctx, config) {
13711
15038
  (async () => {
13712
15039
  try {
13713
15040
  const credential = await stacks[region].store.resolve();
13714
- if (stopped) return;
13715
15041
  const models = await withBusyLevels(region, await client.fetchModels(credential, void 0, regionStateOf(current(), region).enabledModelIds ?? []));
13716
15042
  if (stopped) return;
13717
15043
  const state = regionStateOf(current(), region);
@@ -13734,4 +15060,4 @@ function apply(ctx, config) {
13734
15060
  });
13735
15061
  }
13736
15062
  //#endregion
13737
- export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, WorkBuddyCatalog, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, WorkBuddyEncryptedCredentialError, WorkBuddyUpstreamClient, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };
15063
+ export { CREDENTIAL_REJECTED_CODE, Config, DEFAULT_PROBE_INPUT_TOKENS, ENCRYPTED_CREDENTIAL_CODE, FALLBACK_WORKBUDDY_MODELS, FALLBACK_WORKBUDDY_MODELS_GLOBAL, NATIVE_MODALITY_BY_MODEL_ID, PROBE_INPUT_TOKEN_CHOICES, PROBE_MAX_TOKENS, PROBE_SYSTEM_PROMPT, REFUSES_OFF_MODEL_IDS, WORKBUDDY_ACCOUNTS_REFRESH_PATH, WORKBUDDY_APP_EXECUTABLE_ENV, WORKBUDDY_AUTH_FILENAME, WORKBUDDY_AUTH_FILE_ENV, WORKBUDDY_CHECKIN_PATH, WORKBUDDY_CONNECT_VERSION, WORKBUDDY_GLOBAL_PROVIDER, WORKBUDDY_HOST_HEARTBEAT_FILENAME, WORKBUDDY_MODELS_REFRESH_PATH, WORKBUDDY_PROBE_PATH, WORKBUDDY_PROVIDER, WORKBUDDY_PROVIDERS, WORKBUDDY_PROVIDER_DISPLAY_NAMES, WORKBUDDY_REGIONS, WORKBUDDY_REGION_PARAM, WORKBUDDY_SETTINGS_NS, WORKBUDDY_STREAM_IDLE_TIMEOUT_MS, WORKBUDDY_TPS_PATH, WORKBUDDY_USAGE_PATH, WorkBuddyCatalog, WorkBuddyCredentialRejectedError, WorkBuddyCredentialStore, WorkBuddyEncryptedCredentialError, WorkBuddyUpstreamClient, apply, asVolatile, authFileName, classifyUpstreamError, clearAtRestKeyCache, clearHostHeartbeat, cooldownOf, createAccountUsabilityProbe, createWorkBuddyAdapter, createWorkBuddyShim, creditOfStream, defaultDesktopAuthCandidates, defaultDesktopAuthDirs, defaultDesktopAuthPath, defaultOffModelIds, deriveAtRestKey, deriveAtRestKeyId, deriveCatalog, fallbackModelsFor, fetchAtRestKeyPayload, findWorkbuddyAppExecutable, hasEncryptedCredentialFields, imageDefaultFor, imageToolRegionOf, inject, isCredentialRejectedError, isEncryptedCredentialError, isEncryptedFieldWrapper, isHeartbeatProcessAlive, isWorkbuddyBundle, knownRegionOf, legacyAttributionRegion, legacyWorkbuddyOwnAuthPath, macosBundleExecutable, macosNestedAppBundles, modelIdOfBody, name, nativeModalityOf, nextRegionEnabled, nextRegionSlots, offDefaultFor, openEncryptedField, outcomeOfFailure, parseCreditMultiplier, parseReasoning, parseRetryAfter, parseUpstreamModel, parseWorkBuddyAuth, prepareChatBody, probeModel, probeRequestBody, probeSucceeded, processStartTimeMs, readAtRestKey, readHostHeartbeat, realTierAvailabilityFor, regionCleared, regionEnabled, regionEnabledOf, regionOf, regionOfProvider, regionOfStatusUrl, regionStateOf, regionsFieldIsCorrupt, regionsMapOf, registerWorkBuddyStatusRoute, resolveCredentialRecovery, selectAccountFor, settingsNamespaceOf, toPersistedWorkBuddyModel, unwrapVolatileDeep, videoToolRegionOf, withEffectiveOff, withWorkBuddyRegion, workBuddyDisplayName, workBuddyModelInput, workBuddyThinkingLevelMap, workBuddyWebStatus, workbuddyAccountId, workbuddyAppExecutableCandidates, workbuddyHostHeartbeatPath, workbuddyOwnAuthPath, writeHostHeartbeat };