dsh-connect-workbuddy 5.20.2 → 5.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as withoutRouters, At as withEffectiveOff, B as defaultDesktopAuthPath, Bt as WorkBuddyImageError, C as setDeviceMode, Cn as withFileLock, Ct as attachBusyLevels, D as applyContextBudgets, Dt as offDefaultFor, E as WorkBuddyCatalog, Et as lastRefusalFor, F as WorkBuddyCredentialStore, Ft as pickVideoModel, G as parseWorkBuddyAuth, Gt as pickMediaModel, H as isEncryptedCredentialError, Ht as imageMimeForPath, I as WorkBuddyEncryptedCredentialError, It as resolveVideoParams, J as workbuddyOwnAuthPath, Jt as queueNoticeText, K as preferredAccountName, Kt as sniffImageMime, L as authFileName, Lt as IMAGE_TAG_IMAGE_TO_IMAGE, M as WORKBUDDY_AUTH_FILENAME, Mt as VIDEO_TAG_TEXT_TO_VIDEO, N as WORKBUDDY_AUTH_FILE_ENV, Nt as WorkBuddyVideoError, O as deriveCatalog, Ot as offRefused, Pt as parseSupportedSecondsRange, Q as CREDENTIAL_REJECTED_CODE, Qt as nativeModalityOf, R as defaultDesktopAuthCandidates, Rt as IMAGE_TAG_TEXT_TO_IMAGE, S as saveDeviceSdkSettings, Sn as resolveDshHome, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tt as defaultOffModelIds, U as isVaultAccountId, Ut as isBareBase64Image, V as hasEncryptedCredentialFields, Vt as imageDataUrl, W as legacyWorkbuddyOwnAuthPath, Wt as parseImageDataUrl, X as APP_VERSION, Xt as NATIVE_MODALITY_BY_MODEL_ID, Yt as pruneTempDir, Z as CONTEXT_OVERFLOW_MARKER, Zt as imageDefaultFor, _ as createDeviceProfileLookup, _n as macosNestedAppBundles, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as workbuddyAppExecutableCandidates, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, cn as clearAtRestKeyCache, ct as isContextTooLongBody, dn as fetchAtRestKeyPayload, dt as isFirstMessageGateBody, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as findWorkbuddyAppExecutable, ft as knownRegionOf, g as createTuringSdk, gn as macosBundleExecutable, gt as parseReasoning, h as createDeviceSdkPort, hn as isWorkbuddyBundle, ht as parseCreditMultiplier, i as processStartTimeMs, in as isDeviceId, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as VIDEO_TAG_IMAGE_TO_VIDEO, k as fallbackModelsFor, kt as recordRefusal, l as createFileRosterSeenStore, ln as deriveAtRestKey, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as isEncryptedFieldWrapper, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, p as resolveCnGateway, pt as modelIdOfBody, q as workbuddyAccountId, qt as parseQueueAnswer, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, sn as WORKBUDDY_APP_EXECUTABLE_ENV, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as deriveAtRestKeyId, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as openEncryptedField, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as writeFileAtomic, wt as REFUSES_OFF_MODEL_IDS, x as saveDeviceProfile, xt as requestEvidenceOf, y as isDeviceMode, yn as readAtRestKey, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as MAX_INPUT_IMAGE_BYTES } from "./host-heartbeat-CQ3ot5-F.js";
1
+ import { $t as imageDefaultFor, A as withoutRouters, At as offRefused, B as defaultDesktopAuthPath, Bt as IMAGE_TAG_TEXT_TO_IMAGE, C as setDeviceMode, Ct as attachBusyLevels, D as applyContextBudgets, Dt as defaultOffModelIds, E as WorkBuddyCatalog, En as writeFileAtomic, Et as REFUSES_OFF_MODEL_IDS, F as WorkBuddyCredentialStore, Ft as WorkBuddyVideoError, G as parseWorkBuddyAuth, Gt as isBareBase64Image, H as isEncryptedCredentialError, Ht as WorkBuddyImageError, I as WorkBuddyEncryptedCredentialError, It as parseSupportedSecondsRange, J as workbuddyOwnAuthPath, Jt as sniffImageMime, K as preferredAccountName, Kt as parseImageDataUrl, L as authFileName, Lt as pickVideoModel, M as WORKBUDDY_AUTH_FILENAME, Mt as withEffectiveOff, N as WORKBUDDY_AUTH_FILE_ENV, Nt as VIDEO_TAG_IMAGE_TO_VIDEO, O as deriveCatalog, Ot as lastRefusalFor, Pt as VIDEO_TAG_TEXT_TO_VIDEO, Q as CREDENTIAL_REJECTED_CODE, Qt as NATIVE_MODALITY_BY_MODEL_ID, R as defaultDesktopAuthCandidates, Rt as resolveVideoParams, S as saveDeviceSdkSettings, Sn as workbuddyAppExecutableCandidates, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tn as withFileLock, Tt as selectPromoBadge, U as isVaultAccountId, Ut as imageDataUrl, V as hasEncryptedCredentialFields, Vt as MAX_INPUT_IMAGE_BYTES, W as legacyWorkbuddyOwnAuthPath, Wt as imageMimeForPath, X as APP_VERSION, Xt as queueNoticeText, Yt as parseQueueAnswer, Z as CONTEXT_OVERFLOW_MARKER, Zt as pruneTempDir, _ as createDeviceProfileLookup, _n as isWorkbuddyBundle, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as openEncryptedField, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, ct as isContextTooLongBody, dn as deriveAtRestKey, dt as isFirstMessageGateBody, en as nativeModalityOf, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as deriveAtRestKeyId, ft as knownRegionOf, g as createTuringSdk, gn as isEncryptedFieldWrapper, gt as parseReasoning, h as createDeviceSdkPort, ht as parseCreditMultiplier, i as processStartTimeMs, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as recordRefusal, k as fallbackModelsFor, kt as offDefaultFor, l as createFileRosterSeenStore, ln as WORKBUDDY_APP_EXECUTABLE_ENV, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as findWorkbuddyAppExecutable, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, on as isDeviceId, p as resolveCnGateway, pn as fetchAtRestKeyPayload, pt as modelIdOfBody, q as workbuddyAccountId, qt as pickMediaModel, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as clearAtRestKeyCache, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as macosBundleExecutable, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as resolveDshHome, wt as promoBadgeTone, x as saveDeviceProfile, xn as readAtRestKey, xt as requestEvidenceOf, y as isDeviceMode, yn as macosNestedAppBundles, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as IMAGE_TAG_IMAGE_TO_IMAGE } from "./host-heartbeat-BLfxyXIA.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";
@@ -1909,6 +1909,62 @@ function foreignThinkingOf(context, identity = WORKBUDDY_MODEL_IDENTITY, request
1909
1909
  return found;
1910
1910
  }
1911
1911
  /**
1912
+ * EVERY thinking block in the transcript, whoever produced it (issue #213).
1913
+ *
1914
+ * The narrow repairs above (`foreignThinkingOf`, `crossProviderThinkingOf`) exist
1915
+ * so a different model's reasoning is never replayed as this one's. This one
1916
+ * answers a different question: the WorkBuddy CHANNEL GATE scans the request
1917
+ * text, and a reporter matched every banned opening in a 11128 failure against
1918
+ * the session log's `reasoning` blocks character for character. The gate reads
1919
+ * what we send, and one of the things we send is our own past reasoning
1920
+ * (`reasoning_content`, emitted whenever a thinking block carries a signature).
1921
+ *
1922
+ * So this is not a repair of a mislabelled turn — it is a REDACTION, and it is
1923
+ * why it is a user switch rather than a default: dropping the model's own
1924
+ * reasoning from history changes what the model can see about its earlier work,
1925
+ * which is a real cost paid to get past the gate. The official client's history
1926
+ * very likely carries no thinking text at all, which is the reporter's point and
1927
+ * the reason this is worth offering.
1928
+ *
1929
+ * `variant` is 'flattened' for every block, and that is an APPROXIMATION this
1930
+ * function cannot refine: the real outcome depends on the block's signature,
1931
+ * which only pi-ai's request builder can see.
1932
+ *
1933
+ * - a block whose `thinkingSignature` is one of the three reasoning field names
1934
+ * is REPLAYED as that field (`reasoning_content` for this vendor), not
1935
+ * flattened;
1936
+ * - a block with NO signature is never emitted at all - it is dropped from the
1937
+ * request, not turned into prose;
1938
+ * - a block whose message fails `isSameModel` IS flattened into assistant prose
1939
+ * (`transform-messages.js:88-96`), and that is the only real 'flattened' case.
1940
+ *
1941
+ * So the field is deliberately not surfaced to the user: `variant` reaches
1942
+ * nothing but the diagnostic callback, and a label that is wrong for two of the
1943
+ * three cases would mislead whoever finally does display it. The count is what
1944
+ * the user is told ("N blocks were removed"), which is true for all three.
1945
+ */
1946
+ function allThinkingOf(context) {
1947
+ const messages = context.messages;
1948
+ if (!Array.isArray(messages)) return [];
1949
+ const found = [];
1950
+ for (const [messageIndex, message] of messages.entries()) for (const [blockIndex, block] of blocksOf$1(message).entries()) {
1951
+ if (typeof block !== "object" || block === null) continue;
1952
+ const fields = block;
1953
+ if (fields["type"] !== "thinking") continue;
1954
+ if (fields["redacted"] === true) continue;
1955
+ const thinking = fields["thinking"];
1956
+ const characters = typeof thinking === "string" ? thinking.length : 0;
1957
+ if (characters === 0) continue;
1958
+ found.push({
1959
+ messageIndex,
1960
+ blockIndex,
1961
+ characters,
1962
+ variant: "flattened"
1963
+ });
1964
+ }
1965
+ return found;
1966
+ }
1967
+ /**
1912
1968
  * The subset of {@link foreignThinkingOf} that is safe to repair without asking.
1913
1969
  *
1914
1970
  * This is the predicate the adapter uses when `dropForeignThinking` is OFF: a
@@ -1952,16 +2008,33 @@ function dropThinkingBlocks(context, affected) {
1952
2008
  messages: next
1953
2009
  };
1954
2010
  }
2011
+ /**
2012
+ * Pick the repair this request needs and apply it.
2013
+ *
2014
+ * EXTRACTED so the choice itself is testable. When the selection lived inline in
2015
+ * `prepare`, the only thing a test could assert was what each PREDICATE returns —
2016
+ * and a mutation that deleted the `dropAllThinking` branch entirely still left
2017
+ * every test green, because no test ever asked "which predicate ran". That is a
2018
+ * decoration, not a guard (AGENTS.md: a test that stays green when you break the
2019
+ * code is not a test).
2020
+ *
2021
+ * The order is load-bearing: `dropAllThinking` is checked FIRST because it is the
2022
+ * broadest. A user who turned it on has decided the gate matters more than the
2023
+ * model seeing its own past reasoning, so the narrow "is this block foreign?"
2024
+ * question is no longer the one to ask.
2025
+ */
2026
+ function applyTranscriptRepair(context, repair, identity = WORKBUDDY_MODEL_IDENTITY, requestModelId, ownedRoutes = [WORKBUDDY_PROVIDER, WORKBUDDY_GLOBAL_PROVIDER]) {
2027
+ const affected = repair?.dropAllThinking === true ? allThinkingOf(context) : repair?.dropForeignThinking === true ? foreignThinkingOf(context, identity, requestModelId) : crossProviderThinkingOf(context, identity, ownedRoutes);
2028
+ if (affected.length === 0) return context;
2029
+ try {
2030
+ repair?.onForeignThinking?.(affected);
2031
+ } catch {}
2032
+ return dropThinkingBlocks(context, affected);
2033
+ }
1955
2034
  function withLegacyContext(api, generation, identity = WORKBUDDY_MODEL_IDENTITY, ownedRoutes = [WORKBUDDY_PROVIDER, WORKBUDDY_GLOBAL_PROVIDER], repair) {
1956
2035
  /** One place so both branches and both entry points agree on the order. */
1957
2036
  const prepare = (context, requestModelId) => {
1958
- const aligned = alignAssistantIdentities(generation === "modern" ? foldModernContext(context) : adaptLegacyPiAiContext(context), identity, ownedRoutes);
1959
- const affected = repair?.dropForeignThinking === true ? foreignThinkingOf(aligned, identity, requestModelId) : crossProviderThinkingOf(aligned, identity, ownedRoutes);
1960
- if (affected.length === 0) return aligned;
1961
- try {
1962
- repair?.onForeignThinking?.(affected);
1963
- } catch {}
1964
- return dropThinkingBlocks(aligned, affected);
2037
+ return applyTranscriptRepair(alignAssistantIdentities(generation === "modern" ? foldModernContext(context) : adaptLegacyPiAiContext(context), identity, ownedRoutes), repair, identity, requestModelId, ownedRoutes);
1965
2038
  };
1966
2039
  if (generation === "modern") return {
1967
2040
  ...api,
@@ -2095,10 +2168,54 @@ var EffortNormalizingAdapter = class extends PiAiAdapter {
2095
2168
  * the `off`-only shape `advertiseOffOnly` below depends on.
2096
2169
  */
2097
2170
  defaultEffort;
2098
- constructor(config, effortCapable, defaultEffort = () => void 0) {
2171
+ /**
2172
+ * The selector badge for one exact model, or `undefined` when it carries none.
2173
+ *
2174
+ * Read LIVE on every `listModels()` call, like {@link effortCapable}: the
2175
+ * answer depends on the clock (a night window opens and closes), and the host
2176
+ * re-reads the catalog rather than caching this for the session.
2177
+ *
2178
+ * @see listModels for why the badge lives here at all.
2179
+ */
2180
+ modelBadge;
2181
+ constructor(config, effortCapable, defaultEffort = () => void 0, modelBadge = () => void 0) {
2099
2182
  super(config);
2100
2183
  this.effortCapable = effortCapable;
2101
2184
  this.defaultEffort = defaultEffort;
2185
+ this.modelBadge = modelBadge;
2186
+ }
2187
+ /**
2188
+ * The catalog, with this plugin's selector badge attached to each model.
2189
+ *
2190
+ * WHY THIS OVERRIDE EXISTS (issue #138). `conversation.input.model.label` is a
2191
+ * `single` slot, so whichever plugin wins it draws EVERY provider's rows — and
2192
+ * the host's own badge fallback only runs when the cell has NO occupant. A
2193
+ * sibling's chip therefore survives only if it travels as DATA rather than as
2194
+ * a component. From 0.2.2 the host's directory carries exactly such a field
2195
+ * (`LlmModelInfo.badge`), and the only way an adapter can fill it is here:
2196
+ * `resolveModel()` is normalized by the registry, which drops `badge`, so a
2197
+ * value returned from there never reaches the picker.
2198
+ *
2199
+ * WHY THE SPREAD AND NOT AN OBJECT LITERAL. This plugin's peer range still
2200
+ * starts at `0.1.7-rc.1`, where `LlmModelInfo` has no `badge` field — an
2201
+ * object literal naming it would fail to compile against that declaration.
2202
+ * The spread compiles against both, and on 0.1.x the extra property is simply
2203
+ * not read by anything. No runtime version check is needed or wanted.
2204
+ *
2205
+ * WHAT IS DELIBERATELY NOT HERE: the live load level. A catalog refresh costs
2206
+ * one `resolveModelInfo()` per model, so a per-minute fact would have to be
2207
+ * republished by emitting `llm/models-updated` on every probe — and a stale
2208
+ * 🚦 is worse than no 🚦. The load level stays on this plugin's own rows,
2209
+ * where the component can re-read a snapshot per render.
2210
+ */
2211
+ async listModels(provider) {
2212
+ return (await super.listModels(provider)).map((model) => {
2213
+ const badge = this.modelBadge(model.id);
2214
+ return {
2215
+ ...model,
2216
+ ...badge === void 0 ? {} : { badge }
2217
+ };
2218
+ });
2102
2219
  }
2103
2220
  async resolveModel(provider, model, signal) {
2104
2221
  return this.advertiseDefaultEffort(this.advertiseOffOnly(await super.resolveModel(provider, model, signal)));
@@ -2197,6 +2314,9 @@ function createWorkBuddyAdapter(options) {
2197
2314
  get dropForeignThinking() {
2198
2315
  return options.dropForeignThinking?.() === true;
2199
2316
  },
2317
+ get dropAllThinking() {
2318
+ return options.dropAllThinking?.() === true;
2319
+ },
2200
2320
  ...options.onForeignThinking === void 0 ? {} : { onForeignThinking: options.onForeignThinking }
2201
2321
  }), options.resolveContextRescue)
2202
2322
  }),
@@ -2260,13 +2380,51 @@ function createWorkBuddyAdapter(options) {
2260
2380
  if (info === void 0) return void 0;
2261
2381
  return defaultEffortFor(info, options.defaultThinkingEfforts?.() ?? {});
2262
2382
  };
2383
+ /**
2384
+ * The selector badge for one model: whatever promotion holds RIGHT NOW.
2385
+ *
2386
+ * WHY THE CLOCK IS READ HERE. `promos` rides along UNRESOLVED on the model
2387
+ * entry precisely so the decision can be made where it is drawn (`src/promo.ts`
2388
+ * explains why freezing it at parse time would leave "夜间折扣" on the row the
2389
+ * next morning). `listModels()` is called when the host builds the catalog, so
2390
+ * this is that "where it is drawn" moment on the host side.
2391
+ *
2392
+ * WHY A TABLE, AND WHEN IT COLLAPSES TO A STRING. The host resolves
2393
+ * `badge.text` against the READER's locale (`ctx.locale.resolveText`), and this
2394
+ * function runs in the host process, where the browser's language is not
2395
+ * knowable. A table lets the host pick; a bare string forces one language on
2396
+ * every user. `en` is mandatory in a table — one without it resolves to
2397
+ * `undefined` and the chip disappears entirely.
2398
+ *
2399
+ * Most CN promotions publish NO English wording, so `en = labelEn ?? label`
2400
+ * makes both entries identical and the value collapses to a bare string. That
2401
+ * is deliberate: inventing English copy would be worse than showing the
2402
+ * upstream's own Chinese wording to an English reader.
2403
+ *
2404
+ * ONLY THE PROMOTION GOES IN. The load level is a per-minute fact; see
2405
+ * `listModels` for why it deliberately stays on this plugin's own rows.
2406
+ */
2407
+ const resolveModelBadge = (model) => {
2408
+ const info = catalog.current().find((entry) => entry.id === model);
2409
+ if (info === void 0) return void 0;
2410
+ const promo = selectPromoBadge(info.promos, Date.now());
2411
+ if (promo === void 0) return void 0;
2412
+ const en = promo.badge.labelEn ?? promo.badge.label;
2413
+ return {
2414
+ text: promo.badge.label === en ? en : {
2415
+ en,
2416
+ zh: promo.badge.label
2417
+ },
2418
+ tone: promoBadgeTone(promo)
2419
+ };
2420
+ };
2263
2421
  return {
2264
2422
  adapter: new EffortNormalizingAdapter({
2265
2423
  profiles: () => profiles,
2266
2424
  auth: INERT_AUTH,
2267
2425
  resolveApiKey: async () => shim.token(),
2268
2426
  ...resolveAttachments === void 0 ? {} : { resolveAttachments }
2269
- }, effortCapable, resolveDefaultEffort),
2427
+ }, effortCapable, resolveDefaultEffort, resolveModelBadge),
2270
2428
  invalidate: () => {
2271
2429
  profiles = buildProfiles();
2272
2430
  }
@@ -10479,9 +10637,72 @@ function parseTransferFile(text) {
10479
10637
  } catch (error) {
10480
10638
  throw new Error("transfer file is not valid JSON: " + (error instanceof Error ? error.message : String(error)));
10481
10639
  }
10482
- if (!Array.isArray(parsed)) throw new Error("transfer file must be a JSON array of account records");
10483
- for (const [index, item] of parsed.entries()) if (typeof item !== "object" || item === null || Array.isArray(item)) throw new Error("transfer file item " + (index + 1) + " is not an account object");
10484
- return parsed;
10640
+ const records = recordsOf(parsed);
10641
+ if (records === void 0) throw new Error("transfer file must be a JSON array of account records; this file is " + describeShape(parsed) + ". Accepted wrappers: {\"accounts\": [...]}, {\"data\": [...]}, {\"records\": [...]}.");
10642
+ for (const [index, item] of records.entries()) if (typeof item !== "object" || item === null || Array.isArray(item)) throw new Error("transfer file item " + (index + 1) + " is not an account object");
10643
+ return records.map((item) => stripRedundantRaw(item));
10644
+ }
10645
+ /**
10646
+ * Drop `*_raw` snapshots the importer never reads, keeping `auth_raw`.
10647
+ *
10648
+ * `auth_raw` is exempt because it carries the billing `uin`, which is what makes
10649
+ * a re-imported account converge on the same vault id — dropping it would change
10650
+ * behaviour, not just size.
10651
+ */
10652
+ function stripRedundantRaw(record) {
10653
+ let changed = false;
10654
+ const kept = {};
10655
+ for (const [key, value] of Object.entries(record)) {
10656
+ if (key !== "auth_raw" && key.endsWith("_raw")) {
10657
+ changed = true;
10658
+ continue;
10659
+ }
10660
+ kept[key] = value;
10661
+ }
10662
+ return changed ? kept : record;
10663
+ }
10664
+ /**
10665
+ * The record array inside whatever the file's top level happens to be.
10666
+ *
10667
+ * THE FIX FOR ISSUE #229: the export/import loop has to be closed against the
10668
+ * files sibling tools actually produce, and several of them wrap the records one
10669
+ * level down (`{accounts: [...]}`) — which is also the shape THIS plugin's own
10670
+ * export endpoint answers with, so a user who saved that JSON verbatim got a file
10671
+ * the importer refused. A bare array stays the primary format; the wrappers are
10672
+ * recognized by NAME, never by scanning for the first array anywhere, because a
10673
+ * file whose records live under an unrelated key should fail loudly rather than
10674
+ * be guessed at.
10675
+ *
10676
+ * `undefined` means "not a transfer document", which the caller turns into a
10677
+ * message naming the shape it actually saw.
10678
+ */
10679
+ function recordsOf(parsed, depth = 0) {
10680
+ if (Array.isArray(parsed)) return parsed;
10681
+ if (typeof parsed !== "object" || parsed === null) return void 0;
10682
+ const root = parsed;
10683
+ for (const key of [
10684
+ "accounts",
10685
+ "data",
10686
+ "records"
10687
+ ]) {
10688
+ const value = root[key];
10689
+ if (Array.isArray(value)) return value;
10690
+ }
10691
+ if (depth >= 1) return void 0;
10692
+ for (const key of ["data", "result"]) {
10693
+ const value = root[key];
10694
+ if (typeof value !== "object" || value === null) continue;
10695
+ const inner = recordsOf(value, depth + 1);
10696
+ if (inner !== void 0) return inner;
10697
+ }
10698
+ }
10699
+ /** A short, human-readable description of what the top level actually is. */
10700
+ function describeShape(parsed) {
10701
+ if (parsed === null) return "null";
10702
+ if (Array.isArray(parsed)) return "an array";
10703
+ if (typeof parsed !== "object") return "a " + typeof parsed;
10704
+ const keys = Object.keys(parsed);
10705
+ return keys.length === 0 ? "an empty object" : "an object with keys: " + keys.slice(0, 8).join(", ");
10485
10706
  }
10486
10707
  /** One string field of a record, tolerating the sibling format's odd shapes. */
10487
10708
  function displayString(value) {
@@ -11146,6 +11367,7 @@ const UPSTREAM_SWITCH_FIELDS = /* @__PURE__ */ new Set([
11146
11367
  "extraInjectedPrefixes",
11147
11368
  "sessionTitle",
11148
11369
  "dropForeignThinking",
11370
+ "dropAllThinking",
11149
11371
  "channelRejectContinue",
11150
11372
  "sidebarPanel"
11151
11373
  ]);
@@ -11191,29 +11413,77 @@ function jsonPrivate(res, status, body) {
11191
11413
  });
11192
11414
  res.end(payload);
11193
11415
  }
11194
- /** Request-body cap for the probe route: model ids only, never content. */
11416
+ /** Request-body cap for the PROBE route: model ids only, never content. */
11195
11417
  const PROBE_BODY_LIMIT = 65536;
11196
11418
  /**
11197
- * Read a small JSON request body.
11419
+ * Request-body cap for routes that carry a FILE the user chose.
11420
+ *
11421
+ * WHY THIS IS NOT `PROBE_BODY_LIMIT` (issue #229, second report). The transfer
11422
+ * route takes the whole text of an account-export file, and those are not small:
11423
+ * a single account from a sibling tool measured 108 KiB, because the file carries
11424
+ * two raw upstream snapshots (`quota_raw` + `usage_raw`, ~59 KiB together) that
11425
+ * this plugin never reads. One account already exceeded the probe's 64 KiB, so a
11426
+ * perfectly valid import failed — with the *worst possible* error message (the
11427
+ * socket was destroyed, so the browser reported `Failed to fetch`).
11428
+ *
11429
+ * The number matches the chat route's limit for the same reason: a cap exists to
11430
+ * stop unbounded buffering, not to express an opinion about how big a user's
11431
+ * export file is allowed to be.
11432
+ */
11433
+ const TRANSFER_BODY_LIMIT = 67108864;
11434
+ /**
11435
+ * Raised when a request body exceeds its route's cap.
11436
+ *
11437
+ * A CLASS, not a message, so the caller can answer 413 instead of 500: the
11438
+ * protocol says the client sent too much, and a 500 would send the reader
11439
+ * looking for a server-side fault that does not exist. Same reasoning (and the
11440
+ * same shape) as `RequestBodyTooLargeError` in `shim.ts`.
11441
+ */
11442
+ var JsonBodyTooLargeError = class extends Error {
11443
+ limitBytes;
11444
+ constructor(limitBytes) {
11445
+ super("request body too large (limit " + String(limitBytes) + " bytes)");
11446
+ this.limitBytes = limitBytes;
11447
+ this.name = "JsonBodyTooLargeError";
11448
+ }
11449
+ };
11450
+ /**
11451
+ * Read a JSON object request body, bounded.
11452
+ *
11453
+ * AN OVER-LIMIT BODY IS STOPPED, NOT DESTROYED (issue #229). This used to call
11454
+ * `req.destroy()`, which tears down the SOCKET — so the error response could
11455
+ * never reach the client, and the browser reported a bare `Failed to fetch`.
11456
+ * The user then had no way to learn that the file was merely too large. The
11457
+ * chat route fixed exactly this in #174 ("the 413 can never reach the client
11458
+ * ... it saw a reset connection instead of an answer"); this reader was left
11459
+ * behind, and because the transfer route is the one route that takes a FILE, it
11460
+ * is the place the flaw actually bit. So the stream is paused and its listeners
11461
+ * dropped, the response still goes out, and the caller answers 413.
11198
11462
  *
11199
- * Bounded, unlike the settings route's reader: this endpoint takes a list of
11200
- * model ids and has no legitimate use for a large payload, so an oversized body
11201
- * is refused rather than buffered.
11463
+ * @param req - The request to read.
11464
+ * @param limitBytes - The route's cap; defaults to the probe's small limit.
11202
11465
  */
11203
- function readJsonBody(req) {
11466
+ function readJsonBody(req, limitBytes = PROBE_BODY_LIMIT) {
11204
11467
  return new Promise((resolve, reject) => {
11205
11468
  const chunks = [];
11206
11469
  let size = 0;
11470
+ let settled = false;
11207
11471
  req.on("data", (chunk) => {
11472
+ if (settled) return;
11208
11473
  size += chunk.length;
11209
- if (size > PROBE_BODY_LIMIT) {
11210
- reject(/* @__PURE__ */ new Error("request body too large"));
11211
- req.destroy();
11474
+ if (size > limitBytes) {
11475
+ settled = true;
11476
+ chunks.length = 0;
11477
+ req.removeAllListeners("data");
11478
+ req.removeAllListeners("end");
11479
+ req.pause();
11480
+ reject(new JsonBodyTooLargeError(limitBytes));
11212
11481
  return;
11213
11482
  }
11214
11483
  chunks.push(chunk);
11215
11484
  });
11216
11485
  req.on("end", () => {
11486
+ if (settled) return;
11217
11487
  try {
11218
11488
  const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
11219
11489
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
@@ -11449,6 +11719,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11449
11719
  deps.regionUsable?.(region, accounts.length > 0);
11450
11720
  const enabled = deps.regionEnabled(region);
11451
11721
  const showCreditsInMainUi = deps.showCreditsInMainUi?.(region) ?? true;
11722
+ const showNewModelsInMainUi = deps.showNewModelsInMainUi?.(region) ?? false;
11452
11723
  const creditPosition = deps.creditPosition?.(region) ?? "composer";
11453
11724
  const imageToolEnabled = deps.imageToolEnabled?.(region) ?? false;
11454
11725
  const videoToolEnabled = deps.videoToolEnabled?.(region) ?? false;
@@ -11469,6 +11740,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11469
11740
  selectionExplicit,
11470
11741
  enabled,
11471
11742
  showCreditsInMainUi,
11743
+ showNewModelsInMainUi,
11472
11744
  imageToolEnabled,
11473
11745
  videoToolEnabled,
11474
11746
  preferredVideoModels,
@@ -11492,6 +11764,7 @@ async function workBuddyWebStatus(deps, region, options = {}) {
11492
11764
  selectionExplicit,
11493
11765
  enabled,
11494
11766
  showCreditsInMainUi,
11767
+ showNewModelsInMainUi,
11495
11768
  creditPosition,
11496
11769
  imageToolEnabled,
11497
11770
  videoToolEnabled,
@@ -12088,7 +12361,7 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12088
12361
  req.on("error", reject);
12089
12362
  });
12090
12363
  const field = body.field;
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" });
12364
+ 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, dropAllThinking, channelRejectContinue or sidebarPanel" });
12092
12365
  const row = settings.describe().find((r) => String(r.ns).includes("workbuddy"));
12093
12366
  if (row === void 0) return json(res, 503, { error: "workbuddy namespace missing from describe()" });
12094
12367
  const current = field === "regions" ? regionsMapOf(row.value?.[field]) : unwrapVolatileDeep(row.value?.[field] ?? {});
@@ -12205,13 +12478,14 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
12205
12478
  if (answer.accounts.length === 0) return json(res, 409, { error: "none of the named accounts was found in this region" });
12206
12479
  return jsonPrivate(res, 200, answer);
12207
12480
  }
12208
- const body = await readJsonBody(req);
12481
+ const body = await readJsonBody(req, TRANSFER_BODY_LIMIT);
12209
12482
  if (typeof body.text !== "string" || body.text.trim() === "") return json(res, 400, { error: "text must be the transfer file's JSON content" });
12210
12483
  if (action === "preview") return json(res, 200, await transfer.previewImport(region, body.text));
12211
12484
  const indexes = Array.isArray(body.indexes) ? body.indexes.filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 0) : [];
12212
12485
  if (indexes.length === 0) return json(res, 400, { error: "indexes must name at least one file entry to import" });
12213
12486
  return json(res, 200, await transfer.importAccounts(region, body.text, indexes));
12214
12487
  } catch (error) {
12488
+ if (error instanceof JsonBodyTooLargeError) return json(res, 413, { error: safeMessage(error) });
12215
12489
  json(res, 500, { error: safeMessage(error) });
12216
12490
  }
12217
12491
  }
@@ -12538,6 +12812,25 @@ const regionStateConfig = z.object({
12538
12812
  * `×` in the sidebar, which is reachable exactly where the feature renders.
12539
12813
  */
12540
12814
  showCreditsInMainUi: z.boolean().default(true).description("Show this region's remaining credits at the DSH sidebar foot (opt-out; the line carries its own hide button)"),
12815
+ /**
12816
+ * Whether the composer pill carries its "· N 新模型" segment (opt-IN, default
12817
+ * off).
12818
+ *
12819
+ * WHY OFF BY DEFAULT. "New" here means *first seen by this machine*, not *new
12820
+ * upstream* — the plugin cannot observe when the upstream listed a model, only
12821
+ * when its own roster history first recorded the id. On a fresh install every
12822
+ * id is first-seen, so the very first refresh announces the entire roster as
12823
+ * new: a number that is true by construction, says nothing about the upstream,
12824
+ * and reads as a defect.
12825
+ *
12826
+ * It is a genuinely useful signal ONCE history exists, and it WAS already on,
12827
+ * so the people who want it would lose it to a silent change. Hence opt-in
12828
+ * rather than removal: the segment is worth having, it is just not worth
12829
+ * showing to someone who never asked for it. The same switch governs the "新"
12830
+ * mark on individual picker rows — both read one snapshot (see
12831
+ * `WorkBuddyModelLabel`), so the two surfaces cannot disagree.
12832
+ */
12833
+ showNewModelsInMainUi: z.boolean().default(false).description("Show the \"· N 新模型\" segment (and the per-row \"新\" mark) in the composer. \"New\" means first seen BY THIS MACHINE, not newly listed upstream — on a fresh install that is the whole roster. Off by default."),
12541
12834
  creditPosition: z.union([z.const("composer"), z.const("stats")]).default("composer").description("Where the credit readout sits: \"composer\" = the composer tool row (default), \"stats\" = the ambient row below the composer card, next to the shell's own token pills. Choose \"stats\" if another plugin occupies the composer row."),
12542
12835
  lastCatalog: z.array(modelConfig).default([]),
12543
12836
  enabledModelIds: z.array(z.string()).default([]),
@@ -12738,6 +13031,7 @@ const Config = z.object({
12738
13031
  keepPromptLast: asVolatile(z.boolean().default(false).description("Move the harness-injected runtime context above the real prompt, so the WorkBuddy usage page records what you actually typed instead of the injected block. Message count and text are preserved; the one edit is the recorded prompt's own leading <acp> marker. Off by default because it changes the message order the upstream counts.")),
12739
13032
  extraInjectedPrefixes: asVolatile(z.array(z.string()).default([]).description("Extra literal prefixes (issue #133) treated like the harness-injected context markers when keepPromptLast is on — for blocks a companion plugin injects that the built-in list does not recognize. Each entry matches the start of a trailing user message; read only while keepPromptLast is enabled. Sampled when the plugin mounts: reload the plugin (or restart the host) after changing it.")),
12740
13033
  dropForeignThinking: asVolatile(z.boolean().default(false).description("Drop foreign thinking blocks that pi-ai would publish as prose (issue #147). CROSS-PROVIDER turns are dropped automatically: after a provider switch the other provider's unsigned thinking blocks can never be replayed, and pi-ai would flatten them into assistant prose that the gateway refuses with 11128 (issue #163's measured scene). This switch only widens the repair to a model switch inside one of this bundle's own routes. On, those blocks are removed from the request; text and tool calls are untouched. Off by default for the same-route leg because it changes bytes the upstream counts.")),
13034
+ dropAllThinking: asVolatile(z.boolean().default(false).description("Strip EVERY historical thinking block before the request goes out (issue #213). The channel gate scans the request text, and a 11128 report matched every banned opening against this session's own reasoning blocks: WorkBuddy answers reasoning in `reasoning_content`, pi-ai records that field name as the block signature and replays it under the same name, so past reasoning rides along in the request and is one of the things carrying the text the gate refuses. On, all thinking blocks are removed from the request; your messages, tool calls and the model's answers are untouched, but the model no longer sees its own earlier reasoning. OFF by default: that loss is real, so it is a deliberate answer to a 11128 you can match to reasoning text, not a default. Takes effect on the next turn, no reload.")),
12741
13035
  sessionTitle: asVolatile(z.object({
12742
13036
  enabled: z.boolean().default(false),
12743
13037
  model: z.string().default("wb-lite")
@@ -13883,6 +14177,15 @@ function apply(ctx, config) {
13883
14177
  */
13884
14178
  showCreditsInMainUi: (region) => regionStateOf(current(), region).showCreditsInMainUi !== false,
13885
14179
  /**
14180
+ * The region's committed new-model-segment flag, read from the same config
14181
+ * the card writes.
14182
+ *
14183
+ * `=== true`, the opposite reading to the line above and for the same reason
14184
+ * `imageToolEnabled` uses it: this one is opt-IN, so a missing or unreadable
14185
+ * value must mean "do not show it", never "assume the user wanted it".
14186
+ */
14187
+ showNewModelsInMainUi: (region) => regionStateOf(current(), region).showNewModelsInMainUi === true,
14188
+ /**
13886
14189
  * Whether the model may call the image tool here. Read from the committed
13887
14190
  * value like the flag above, and deliberately `=== true`: an absent setting
13888
14191
  * is NOT consent to let the model spend.
@@ -13932,6 +14235,7 @@ function apply(ctx, config) {
13932
14235
  * rather than the one captured at mount.
13933
14236
  */
13934
14237
  dropForeignThinking: () => unwrapVolatile(current().dropForeignThinking) === true,
14238
+ dropAllThinking: () => unwrapVolatile(current().dropAllThinking) === true,
13935
14239
  /**
13936
14240
  * What the last request had to drop, so the card can explain a turn that
13937
14241
  * arrived looking like working notes instead of leaving the user to conclude
@@ -15017,12 +15321,14 @@ function apply(ctx, config) {
15017
15321
  */
15018
15322
  defaultThinkingEfforts: () => regionStateOf(current(), region).defaultThinkingEfforts ?? {},
15019
15323
  dropForeignThinking: () => unwrapVolatile(current().dropForeignThinking) === true,
15324
+ dropAllThinking: () => unwrapVolatile(current().dropAllThinking) === true,
15020
15325
  onForeignThinking: (blocks) => {
15021
15326
  latestForeignThinking = {
15022
15327
  blocks,
15023
15328
  atMs: Date.now()
15024
15329
  };
15025
- if (unwrapVolatile(current().dropForeignThinking) !== true) ctx.logger.warn(`dsh-connect-workbuddy: dropped ${blocks.length} cross-provider thinking block(s) before a WorkBuddy request (provider switch); see issue #163`);
15330
+ if (unwrapVolatile(current().dropAllThinking) === true) ctx.logger.warn(`dsh-connect-workbuddy: dropped ${blocks.length} thinking block(s) before a WorkBuddy request because the reasoning-redaction switch is on; see issue #213`);
15331
+ else if (unwrapVolatile(current().dropForeignThinking) !== true) ctx.logger.warn(`dsh-connect-workbuddy: dropped ${blocks.length} cross-provider thinking block(s) before a WorkBuddy request (provider switch); see issue #163`);
15026
15332
  }
15027
15333
  });
15028
15334
  invalidateCatalog = () => {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-workbuddy",
3
3
  "displayName": "DSH Connect WorkBuddy",
4
4
  "description": "把本机登录的 WorkBuddy 模型(国内版与国际版)接入 DeepSeek Harness:每次刷新按上游目录自动读取每个模型的积分倍率,支持逐模型图片输入开关、多账号切换与账号池自动换号,并提供每日签到、卡片与输入框里的胶囊积分读数等只读积分概览。",
5
- "version": "5.20.2",
5
+ "version": "5.21.0",
6
6
  "author": "dingminhua",
7
7
  "copyright": "Copyright (c) 2026 LaoDing",
8
8
  "license": "MIT",
@@ -43,6 +43,7 @@
43
43
  "icons",
44
44
  "locale",
45
45
  "docs/assets",
46
+ "docs/PRIVACY.md",
46
47
  "screenshots.json",
47
48
  "cordis.patch.yml",
48
49
  "README.md",
@@ -54,13 +55,14 @@
54
55
  ],
55
56
  "scripts": {
56
57
  "prepare": "npm run build",
57
- "prepack": "npm run build",
58
+ "prepack": "npm run build && node scripts/check-pii.mjs",
58
59
  "build": "tsdown && node scripts/verify-entry-artifacts.mjs",
59
60
  "verify:entries": "node scripts/verify-entry-artifacts.mjs",
61
+ "check:pii": "node scripts/check-pii.mjs",
60
62
  "test": "vitest run",
61
63
  "section:shot": "vitest run --config vitest.card.config.ts",
62
64
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
63
- "check": "pnpm run typecheck && pnpm run test && pnpm run build"
65
+ "check": "pnpm run typecheck && pnpm run build && pnpm run check:pii && pnpm run test"
64
66
  },
65
67
  "dsh": {
66
68
  "bundle": {