dsh-connect-trae 4.6.12 → 4.8.1

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,7 +1,7 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { createProvider } from "@earendil-works/pi-ai";
3
3
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
4
- import { resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
4
+ import { ReasoningEffortId, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
5
5
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
  import { basename, dirname, join } from "node:path";
@@ -817,6 +817,144 @@ function readManifest(directory) {
817
817
  }
818
818
  }
819
819
  //#endregion
820
+ //#region src/reasoning.ts
821
+ /**
822
+ * The DSH thinking levels this plugin can carry, in ascending order.
823
+ *
824
+ * `max` is the fifth level Trae's own client advertises — its bundle ships the
825
+ * i18n keys `trae-chat-core.model.reasoning_effort.{low,medium,high,extra_high,max}`
826
+ * and `ai.model.reasoning_effort.{low,medium,high,xhigh,max}`, and publishes the
827
+ * per-model list from a remote config (`AI.agent.model.reasoning_effort_level_by_agent_model_v2`).
828
+ * Leaving it out of this list meant a level the vendor could start serving was
829
+ * filtered away at PARSE time, before anything downstream could decide (issue
830
+ * #60). Listing it does not fabricate the level: `supported` is still built
831
+ * only from what the upstream response actually contains, so a model that does
832
+ * not advertise `max` never offers it.
833
+ *
834
+ * `minimal` is kept for the same reason in reverse — it is a DSH level, so the
835
+ * type must be able to represent it even though no CN model has advertised it.
836
+ */
837
+ const TRAE_REASONING_EFFORTS = [
838
+ "minimal",
839
+ "low",
840
+ "medium",
841
+ "high",
842
+ "xhigh",
843
+ "max"
844
+ ];
845
+ function parseReasoningCapability(value) {
846
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
847
+ const record = value;
848
+ const supported = (Array.isArray(record["reasoning_effort_options"]) ? record["reasoning_effort_options"] : []).filter((item) => typeof item === "string" && TRAE_REASONING_EFFORTS.includes(item));
849
+ const rawDefault = record["default_reasoning_effort"];
850
+ const defaultEffort = typeof rawDefault === "string" && supported.includes(rawDefault) ? rawDefault : void 0;
851
+ if (supported.length === 0 && defaultEffort === void 0) return void 0;
852
+ return {
853
+ supported,
854
+ ...defaultEffort === void 0 ? {} : { defaultEffort }
855
+ };
856
+ }
857
+ /** Add effort only when the selected model advertises that exact value. */
858
+ function applyReasoningEffort(body, effort, capability) {
859
+ if (effort === void 0) return body;
860
+ if (capability === void 0 || !capability.supported.includes(effort)) throw new Error(`Trae model does not advertise reasoning effort ${effort}`);
861
+ return {
862
+ ...body,
863
+ reasoning_effort: effort
864
+ };
865
+ }
866
+ //#endregion
867
+ //#region src/default-effort.ts
868
+ /**
869
+ * Which thinking level a model runs at when the caller names none.
870
+ *
871
+ * ## Why this module exists
872
+ *
873
+ * Trae's directory already tells us each model's own default level
874
+ * (`reasoning_effort_config.default_level`, parsed into `reasoning.defaultEffort`
875
+ * by `model-metadata.ts`) — measured 2026-11-03 on a live CN credential:
876
+ * `deepseek-v4.1-flash` says `high`, `glm-5.3` says `xhigh`. The card's meta row
877
+ * names the tiers it accepts, so the fact is known.
878
+ *
879
+ * DSH's model picker nevertheless reads **Default**, because the adapter never
880
+ * reports that level upward (`reasoning.defaultEffort` is absent from what
881
+ * {@link toPiModel} hands the kernel). The picker therefore cannot say which
882
+ * tier a request will run at, and the request itself carries no
883
+ * `reasoning_effort` — the upstream falls back to the same level it already
884
+ * published, so nothing is broken, but nothing is knowable either, and the user
885
+ * has no way to say "always use high on this model, regardless of what Trae
886
+ * ships as its default".
887
+ *
888
+ * ## The three seams that must agree (any one missing and the picker still says Default)
889
+ *
890
+ * 1. **The adapter** must report the level as `LlmResolvedModelInfo.reasoning.defaultEffort`.
891
+ * The kernel materialises that into every request that names no effort
892
+ * (`dsh-llm` `resolveCallWithInfo`: `const effective = requested ?? reasoning.defaultEffort`),
893
+ * and DSH's model picker takes its "current level" from the same metadata.
894
+ * 2. **A per-model saved choice** must survive a settings save. The settings
895
+ * channel rebuilds the whole region document through its schema, so a field
896
+ * absent from that schema is dropped on every save — the failure that once
897
+ * reset `wireConfigName` (see the `modelConfig` schema).
898
+ * 3. **The bridge** must translate the level it receives into Trae's wire name.
899
+ * `solo-bridge.ts` already does exactly that through the model's own
900
+ * `reasoningEfforts` table, and deletes the field when the model does not
901
+ * advertise it — so a level is never sent under a name the vendor never said.
902
+ *
903
+ * ## Precedence
904
+ *
905
+ * The user's explicit choice > the level upstream declares > this model's own
906
+ * middle tier.
907
+ *
908
+ * @module dsh-connect-trae/default-effort
909
+ */
910
+ /**
911
+ * The tier to fall back to when a model publishes a tier list but names no
912
+ * default of its own and the user has never chosen one.
913
+ *
914
+ * `medium` is tried first because it is the only middle tier shared by the
915
+ * families seen so far. It is deliberately not the only fallback: a model that
916
+ * publishes `low / high` (measured on `Doubao-Seed-2.1-Pro` and
917
+ * `step-5-preview`) has no `medium` at all, and picking its weakest tier instead
918
+ * would silently mean "thinking off" — that is not a fallback, that is the worst
919
+ * possible default.
920
+ */
921
+ const TRAE_FALLBACK_EFFORT = "medium";
922
+ /**
923
+ * The tiers a model actually declares, filtered to ones DSH can name.
924
+ *
925
+ * Upstream's vocabulary is not DSH's: Trae publishes `light / high / extra_high`
926
+ * and the parser maps them to `low / high / xhigh` (`EFFORT_MAP`). Anything that
927
+ * still fails to land in DSH's six names is dropped rather than passed through —
928
+ * a level the kernel cannot name would be rejected with
929
+ * `UNSUPPORTED_REASONING_EFFORT` and take the whole request with it.
930
+ *
931
+ * The result keeps `TRAE_REASONING_EFFORTS` order, so it reads weakest-first.
932
+ */
933
+ function declaredEfforts(model) {
934
+ const supported = model.supported ?? [];
935
+ return TRAE_REASONING_EFFORTS.filter((level) => supported.includes(level));
936
+ }
937
+ /**
938
+ * The tier this model should run at when a request names none.
939
+ *
940
+ * @param model - the model, with the tiers it declares and its upstream default.
941
+ * @param saved - the user's per-model choices (model id -> tier). A missing key
942
+ * means the user never chose, which is different from choosing the tier that
943
+ * happens to equal the upstream default.
944
+ * @returns a tier **this model declares**, or `undefined` when it declares none.
945
+ */
946
+ function defaultEffortFor(model, saved = {}) {
947
+ const declared = declaredEfforts(model);
948
+ if (declared.length === 0) return void 0;
949
+ const asked = saved[model.id];
950
+ const chosen = declared.find((level) => level === asked);
951
+ if (chosen !== void 0) return chosen;
952
+ const upstream = declared.find((level) => level === model.defaultEffort);
953
+ if (upstream !== void 0) return upstream;
954
+ if (declared.includes("medium")) return TRAE_FALLBACK_EFFORT;
955
+ return declared[Math.floor((declared.length - 1) / 2)];
956
+ }
957
+ //#endregion
820
958
  //#region src/adapter.ts
821
959
  /** Provider route this bundle owns for the domestic (CN) gateway. */
822
960
  const TRAE_PROVIDER = "trae";
@@ -896,10 +1034,33 @@ const INERT_AUTH = {
896
1034
  }
897
1035
  }
898
1036
  };
1037
+ /**
1038
+ * The image-request policy this hand-built profile hands to `dsh-llm-pi-ai`.
1039
+ *
1040
+ * WHY THIS OBJECT IS SPELLED OUT. DSH's own config resolution (`resolveProfiles`
1041
+ * in `dsh-llm-pi-ai`) defaults every route-level image bound. This plugin never
1042
+ * runs that path: it builds `ResolvedPiAiProviderProfile` by hand from a live
1043
+ * Trae catalog, so every field the host expects has to be named here or the
1044
+ * bound silently does not apply.
1045
+ *
1046
+ * `maxRequestImages` / `imageOffloadCountQuantum` joined that contract in DSH
1047
+ * 0.2.2-rc.1 (the required fields on `ResolvedPiAiProviderProfile`). The count
1048
+ * bound is what turns a request carrying more images than a route accepts into
1049
+ * the host's `IMAGE_OFFLOAD_REQUIRED` flow instead of an upstream rejection, and
1050
+ * the quantum is how many of the oldest occurrences that flow offloads at once.
1051
+ * Without them the host treats the route as count-unbounded — the pre-0.2.2
1052
+ * behaviour, which is why 4.8.0 kept working — but the type contract no longer
1053
+ * compiles, so they are declared here with the host's own defaults (50 / 10).
1054
+ *
1055
+ * `imageOffloadCountQuantum` must be a positive integer no greater than
1056
+ * `maxRequestImages`; 10 ≤ 50 keeps the host's default ratio.
1057
+ */
899
1058
  const REQUEST_IMAGE_BUDGETS = {
900
1059
  maxRequestImageBytes: 20971520,
901
1060
  requestImagePixelBudget: 4194304,
902
- requestImageMaxBytes: 1048576
1061
+ requestImageMaxBytes: 1048576,
1062
+ maxRequestImages: 50,
1063
+ imageOffloadCountQuantum: 10
903
1064
  };
904
1065
  function toPiModel(info, baseUrl, providerId, withRate = true) {
905
1066
  return {
@@ -1132,6 +1293,65 @@ function withContextAdaptation(api, generation) {
1132
1293
  streamSimple: (model, context, options) => api.streamSimple(model, forApi(context), options)
1133
1294
  };
1134
1295
  }
1296
+ /**
1297
+ * The adapter, with the level each model runs at reported upward.
1298
+ *
1299
+ * WHY THIS SUBCLASS EXISTS. The kernel asks the adapter for a model's reasoning
1300
+ * metadata and materialises `reasoning.defaultEffort` into every request that
1301
+ * names no level (`dsh-llm` `resolveCallWithInfo`), and DSH's model picker reads
1302
+ * the same field to say which level is current. This plugin knows the answer —
1303
+ * Trae publishes a per-model default and the user may override it — but the
1304
+ * hand-built provider cannot express a per-model default through pi-ai's `Model`
1305
+ * (its shape has one `reasoning: boolean` for the whole row). Reporting it here,
1306
+ * at the seam the kernel actually consults, is what makes the picker name a
1307
+ * level instead of `Default`. See `default-effort.ts` for the precedence.
1308
+ *
1309
+ * The override is deliberately narrow: it rewrites ONE field of an object the
1310
+ * parent just built, and only when the model genuinely declares that level.
1311
+ */
1312
+ var DefaultEffortAdapter = class extends PiAiAdapter {
1313
+ /**
1314
+ * The level one model should run at; `undefined` means it offers no reasoning.
1315
+ *
1316
+ * Read on every resolution rather than captured once, so a catalog refresh or
1317
+ * a settings change reaches the very next request without a restart.
1318
+ */
1319
+ defaultEffort;
1320
+ constructor(config, defaultEffort = () => void 0) {
1321
+ super(config);
1322
+ this.defaultEffort = defaultEffort;
1323
+ }
1324
+ resolveModel(provider, model, signal) {
1325
+ return super.resolveModel(provider, model, signal).then((info) => this.advertiseDefaultEffort(info));
1326
+ }
1327
+ prepareCall(provider, model, signal) {
1328
+ return super.prepareCall(provider, model, signal).then((call) => ({
1329
+ ...call,
1330
+ model: this.advertiseDefaultEffort(call.model)
1331
+ }));
1332
+ }
1333
+ /**
1334
+ * Write the level into the model metadata.
1335
+ *
1336
+ * It must NEVER contradict the tier list: reporting a level the model does not
1337
+ * offer makes the kernel reject the request outright with
1338
+ * `INVALID_MODEL_REASONING` — far worse than the picker saying `Default`.
1339
+ */
1340
+ advertiseDefaultEffort(info) {
1341
+ if (info.reasoning === void 0) return info;
1342
+ const effort = this.defaultEffort(info.id);
1343
+ if (effort === void 0) return info;
1344
+ if (!info.reasoning.efforts.some((level) => level.id === effort)) return info;
1345
+ if (info.reasoning.defaultEffort === effort) return info;
1346
+ return {
1347
+ ...info,
1348
+ reasoning: {
1349
+ ...info.reasoning,
1350
+ defaultEffort: ReasoningEffortId(effort)
1351
+ }
1352
+ };
1353
+ }
1354
+ };
1135
1355
  function createTraeAdapter(options) {
1136
1356
  const providerId = options.provider ?? "trae";
1137
1357
  const providerName = options.displayName ?? "Trae";
@@ -1173,13 +1393,30 @@ function createTraeAdapter(options) {
1173
1393
  piProvider: provider
1174
1394
  };
1175
1395
  let profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
1396
+ /**
1397
+ * The level one model should run at, resolved from the LIVE catalog.
1398
+ *
1399
+ * The catalog, not the saved `lastCatalog`, because `catalog.current()` is
1400
+ * what the provider serves and what `toPiModel` sized the tier list from —
1401
+ * answering from a different source could name a level that row does not
1402
+ * offer, which the kernel rejects.
1403
+ */
1404
+ const resolveDefaultEffort = (model) => {
1405
+ const info = options.catalog.current().find((entry) => entry.id === model);
1406
+ if (info === void 0 || info.reasoning === void 0) return void 0;
1407
+ return defaultEffortFor({
1408
+ id: info.id,
1409
+ supported: info.reasoning.supported,
1410
+ defaultEffort: info.reasoning.defaultEffort
1411
+ }, options.defaultEfforts?.() ?? {});
1412
+ };
1176
1413
  return {
1177
- adapter: new PiAiAdapter({
1414
+ adapter: new DefaultEffortAdapter({
1178
1415
  profiles: () => profiles,
1179
1416
  auth: INERT_AUTH,
1180
1417
  resolveApiKey: async () => options.secret ?? options.shim.token(),
1181
1418
  ...options.resolveAttachments === void 0 ? {} : { resolveAttachments: options.resolveAttachments }
1182
- }),
1419
+ }, resolveDefaultEffort),
1183
1420
  invalidate() {
1184
1421
  profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
1185
1422
  }
@@ -5005,53 +5242,6 @@ function parseTraeActivityDiscount(value) {
5005
5242
  return parsed.current === void 0 && parsed.member === void 0 && parsed.offPeak === void 0 && parsed.subsidy === void 0 ? void 0 : parsed;
5006
5243
  }
5007
5244
  //#endregion
5008
- //#region src/reasoning.ts
5009
- /**
5010
- * The DSH thinking levels this plugin can carry, in ascending order.
5011
- *
5012
- * `max` is the fifth level Trae's own client advertises — its bundle ships the
5013
- * i18n keys `trae-chat-core.model.reasoning_effort.{low,medium,high,extra_high,max}`
5014
- * and `ai.model.reasoning_effort.{low,medium,high,xhigh,max}`, and publishes the
5015
- * per-model list from a remote config (`AI.agent.model.reasoning_effort_level_by_agent_model_v2`).
5016
- * Leaving it out of this list meant a level the vendor could start serving was
5017
- * filtered away at PARSE time, before anything downstream could decide (issue
5018
- * #60). Listing it does not fabricate the level: `supported` is still built
5019
- * only from what the upstream response actually contains, so a model that does
5020
- * not advertise `max` never offers it.
5021
- *
5022
- * `minimal` is kept for the same reason in reverse — it is a DSH level, so the
5023
- * type must be able to represent it even though no CN model has advertised it.
5024
- */
5025
- const TRAE_REASONING_EFFORTS = [
5026
- "minimal",
5027
- "low",
5028
- "medium",
5029
- "high",
5030
- "xhigh",
5031
- "max"
5032
- ];
5033
- function parseReasoningCapability(value) {
5034
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
5035
- const record = value;
5036
- const supported = (Array.isArray(record["reasoning_effort_options"]) ? record["reasoning_effort_options"] : []).filter((item) => typeof item === "string" && TRAE_REASONING_EFFORTS.includes(item));
5037
- const rawDefault = record["default_reasoning_effort"];
5038
- const defaultEffort = typeof rawDefault === "string" && supported.includes(rawDefault) ? rawDefault : void 0;
5039
- if (supported.length === 0 && defaultEffort === void 0) return void 0;
5040
- return {
5041
- supported,
5042
- ...defaultEffort === void 0 ? {} : { defaultEffort }
5043
- };
5044
- }
5045
- /** Add effort only when the selected model advertises that exact value. */
5046
- function applyReasoningEffort(body, effort, capability) {
5047
- if (effort === void 0) return body;
5048
- if (capability === void 0 || !capability.supported.includes(effort)) throw new Error(`Trae model does not advertise reasoning effort ${effort}`);
5049
- return {
5050
- ...body,
5051
- reasoning_effort: effort
5052
- };
5053
- }
5054
- //#endregion
5055
5245
  //#region src/solo.ts
5056
5246
  /**
5057
5247
  * `llm_utils_chat` functions to union per region, in priority order.
@@ -8657,6 +8847,18 @@ async function traeWebUsage(deps, panel, options = {}) {
8657
8847
  const store = deps.store(panel);
8658
8848
  const enabled = deps.regionEnabled(panel);
8659
8849
  /**
8850
+ * GLOBAL, read once per answer and repeated on every panel: the card polls
8851
+ * one region at a time, so the sidebar switch has to be present on whichever
8852
+ * tab is open. `=== true` for the same reason as every opt-in switch here —
8853
+ * the row claims a seat every bundle shares, so an absent answer (an older
8854
+ * Host that cannot answer) must never read as "the user asked for this".
8855
+ *
8856
+ * The signed-OUT branches below carry it too: the row is a property of the
8857
+ * plugin, not of a signed-in account, and a signed-out card is exactly where
8858
+ * a user may still want the page it opens.
8859
+ */
8860
+ const sidebarPanelEnabled = deps.sidebarPanelEnabled?.() === true;
8861
+ /**
8660
8862
  * Accounts this panel may actually bill.
8661
8863
  *
8662
8864
  * Filtered ONCE, at the source, because this list is spliced into every
@@ -8701,6 +8903,7 @@ async function traeWebUsage(deps, panel, options = {}) {
8701
8903
  status: "signed-out",
8702
8904
  accounts,
8703
8905
  enabled,
8906
+ sidebarPanelEnabled,
8704
8907
  quarantined,
8705
8908
  ...unsupportedRegion === void 0 ? {} : { unsupportedRegion },
8706
8909
  searched: failures.map((failure) => ({
@@ -8722,6 +8925,7 @@ async function traeWebUsage(deps, panel, options = {}) {
8722
8925
  status: "signed-out",
8723
8926
  accounts,
8724
8927
  enabled,
8928
+ sidebarPanelEnabled,
8725
8929
  quarantined,
8726
8930
  ...unsupportedRegion === void 0 ? {} : { unsupportedRegion },
8727
8931
  ...explained ? {} : { message: safeMessage(error) }
@@ -8734,6 +8938,7 @@ async function traeWebUsage(deps, panel, options = {}) {
8734
8938
  ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
8735
8939
  region: regionOfPanel(panel),
8736
8940
  enabled,
8941
+ sidebarPanelEnabled,
8737
8942
  ...unsupportedRegion === void 0 ? {} : { unsupportedRegion },
8738
8943
  accounts,
8739
8944
  models: deps.displayModels(panel).map((model) => ({
@@ -9052,12 +9257,34 @@ async function traeAccountCredits(deps, panel) {
9052
9257
  if (accounts.length === 0) return [];
9053
9258
  return Promise.all(accounts.map(async (account) => {
9054
9259
  let generalAvailable;
9055
- if (account.selected) try {
9056
- generalAvailable = toCredits(await deps.client(panel).snapshot()).generalAvailable;
9057
- } catch {}
9058
- else if (deps.creditsOfAccount !== void 0) try {
9260
+ /**
9261
+ * EVERY row goes through `creditsOfAccount`, INCLUDING the bound one.
9262
+ *
9263
+ * That is a correctness fix, not a simplification. The bound row used to
9264
+ * take `deps.client(panel).snapshot()` — the shared client, which reads
9265
+ * through `store.resolve()` and therefore whatever account is bound. The
9266
+ * branch existed because the bound account's stored token is usually
9267
+ * EXPIRED, and `creditsOfAccount` used to be a pure lookup that handed a
9268
+ * stale token back as-is. `126faa9` removed that reason: `creditsOfAccount`
9269
+ * now resolves each named account's credential, refreshing it first.
9270
+ *
9271
+ * What was left behind was a way to report the WRONG account's balance. The
9272
+ * shared client answers for the binding, so if the store's binding moved
9273
+ * between the `accounts()` read and the snapshot — or `resolve()` picked a
9274
+ * different account than the `selected` flag names — this row carried the
9275
+ * OTHER account's figure. The visible symptom was two rows showing the same
9276
+ * number (issue #74 follow-up, 2026-11-03): both accounts read 644.29 while
9277
+ * the upstream said 678.54 and 644.00.
9278
+ *
9279
+ * Reading by id is also what makes the rows independent: each request names
9280
+ * its account, so no row can be answered by another row's credential.
9281
+ */
9282
+ if (deps.creditsOfAccount !== void 0) try {
9059
9283
  generalAvailable = (await deps.creditsOfAccount(panel, account.id))?.generalAvailable;
9060
9284
  } catch {}
9285
+ else if (account.selected) try {
9286
+ generalAvailable = toCredits(await deps.client(panel).snapshot()).generalAvailable;
9287
+ } catch {}
9061
9288
  return {
9062
9289
  id: account.id,
9063
9290
  accountName: account.accountName,
@@ -10842,6 +11069,41 @@ function creditPosition(config, region) {
10842
11069
  return regionStateOf(config, region).creditPosition === "stats" ? "stats" : "composer";
10843
11070
  }
10844
11071
  /**
11072
+ * The user's thinking-level choices for one panel (model id -> DSH level).
11073
+ *
11074
+ * Read through `regionStateOf` so the region split, the legacy CN fallback and
11075
+ * the volatile unwrap all apply exactly once, in one place. Values are filtered
11076
+ * to non-empty strings: an empty string is not a level, and passing one on would
11077
+ * make the model report a default the kernel cannot name.
11078
+ *
11079
+ * A saved level is NOT validated against the model's current tier list here —
11080
+ * that belongs where the tiers are known (`default-effort.ts`
11081
+ * `defaultEffortFor`), which is also where a withdrawn tier is dropped instead
11082
+ * of being sent.
11083
+ */
11084
+ function thinkingEffortsOf(config, region) {
11085
+ const raw = regionStateOf(config, region).thinkingEfforts;
11086
+ if (raw === void 0 || raw === null || typeof raw !== "object") return {};
11087
+ const out = {};
11088
+ for (const [id, level] of Object.entries(raw)) if (typeof level === "string" && level !== "") out[id] = level;
11089
+ return out;
11090
+ }
11091
+ /**
11092
+ * Whether the OPTIONAL sidebar row is switched on (`Config.sidebarPanel`).
11093
+ *
11094
+ * `=== true` on purpose, exactly like the sibling workbuddy reader: the row
11095
+ * claims a GLOBAL sidebar seat every installed bundle shares, so an absent,
11096
+ * unreadable or hand-edited value must read as "the user did not ask for this",
11097
+ * never as consent. Only an explicit boolean `true` turns the row on.
11098
+ *
11099
+ * Read through `unwrapVolatile` because the field is volatile on 0.1.7: the
11100
+ * live `{get(): T}` reference would otherwise be a truthy non-boolean and every
11101
+ * config would look switched on.
11102
+ */
11103
+ function sidebarPanelEnabled(config) {
11104
+ return unwrapVolatile(config.sidebarPanel) === true;
11105
+ }
11106
+ /**
10845
11107
  * Mark a schema's field as volatile.
10846
11108
  *
10847
11109
  * `volatile()` exists from schemastery 3.18.3; since 2.3.0 the peer range
@@ -10883,6 +11145,7 @@ const regionStateConfig = z.object({
10883
11145
  imageModelIds: z.array(z.string()).default([]),
10884
11146
  drawImageEnabled: z.boolean().default(false).description("Allow the model to generate images with trae_draw_image on this panel (consumes credits; default off)"),
10885
11147
  contextBudgets: z.dict(z.number().step(1).min(1)).default({}),
11148
+ thinkingEfforts: z.dict(z.string()).default({}).description("每个模型的思考强度(模型 id → 档位)。留空 = 跟随该模型自己的默认档。"),
10886
11149
  creditPosition: z.union([z.const("composer"), z.const("stats")]).default("composer").description("积分读数显示位置:\"composer\" = 输入框工具栏(默认),\"stats\" = 输入框下方(与「轮次 / 步数 / token」统计同一行)。装了别的插件后读数不显示时改成 stats。"),
10887
11150
  pool: z.object({
10888
11151
  enabled: z.boolean().default(false).description("账号池:打开后本面板由池中可用账号轮流计费(关闭时按下面的绑定账号)"),
@@ -10907,6 +11170,7 @@ const Config = z.object({
10907
11170
  ]).default("auto").description("Trae edition hint")),
10908
11171
  accountId: z.string().description("Deprecated: pre-split account selector, attributed to its own region"),
10909
11172
  showPointsInMainUi: asVolatile(z.boolean().default(false).description("在输入框工具栏显示积分读数「Trae CN · <数值>」(仅当选中的模型属于本插件时出现,可点击查看账号与积分明细)")),
11173
+ sidebarPanel: asVolatile(z.boolean().default(false).description("在 DSH 侧边栏显示「Trae」面板:点开是这张卡片的整页版。默认关闭——这一行占的是所有插件共用的全局侧边栏座位,而「插件」页本来就能看到同样的内容。点一下即生效,不用保存。")),
10910
11174
  accounts: asVolatile(accountSelectionConfig.description("Per-panel account selections, keyed cn | enterprise | ai")),
10911
11175
  regions: asVolatile(z.dict(regionStateConfig).default({}).description("Per-panel model directory and selection, keyed cn | enterprise | ai")),
10912
11176
  lastCatalog: z.array(modelConfig).description("Deprecated: pre-region-split CN model directory"),
@@ -11881,6 +12145,7 @@ function apply(ctx, config) {
11881
12145
  displayModels: (panel) => displayModels(current(), panel),
11882
12146
  enabledModelIds: (panel) => regionStateOf(current(), panel).enabledModelIds ?? [],
11883
12147
  regionEnabled: (panel) => regionEnabled(current(), panel),
12148
+ sidebarPanelEnabled: () => sidebarPanelEnabled(current()),
11884
12149
  discoverModels: (panel, signal) => stacks[panel].discoverModels(signal),
11885
12150
  probeModels: async (panel, ids) => {
11886
12151
  await warmWireMap(panel);
@@ -11948,6 +12213,64 @@ function apply(ctx, config) {
11948
12213
  delete registration.cn.directory;
11949
12214
  };
11950
12215
  /**
12216
+ * The last catalog announced to the host, per region.
12217
+ *
12218
+ * DSH 0.2.2-rc.1 added `llm/models-updated(provider)`: "a provider's advertised
12219
+ * models or display metadata changed; consumers reload `listModels()`". The
12220
+ * model picker listens for it next to the payload-free `llm/adapters-updated`
12221
+ * — and the latter only fires when a route's TOPOLOGY changes, which is not
12222
+ * the same event as "the models behind an unchanged route changed". The live
12223
+ * directory this plugin refreshes from upstream is exactly the second kind:
12224
+ * the same provider, a different roster.
12225
+ *
12226
+ * The map is the dedupe ledger. Every settings write rebuilds the catalog
12227
+ * object even when the served rows are identical, so an unconditional emit
12228
+ * would make every picker (and every other consumer) re-read the catalog on
12229
+ * each card keystroke.
12230
+ */
12231
+ const announcedCatalog = /* @__PURE__ */ new Map();
12232
+ /**
12233
+ * What a picker can tell apart about one catalog.
12234
+ *
12235
+ * Must cover every field the host exposes for a model — id, display name,
12236
+ * context window, output cap, input modalities, reasoning tiers, and the
12237
+ * credit multiplier the display name is derived from — or a refresh that
12238
+ * changed only one of them would stay stale in the picker. Order and
12239
+ * omission are both meaningful, so `null` marks an absent key instead of it
12240
+ * collapsing into the empty string.
12241
+ */
12242
+ function catalogSignature(models) {
12243
+ return models.map((model) => JSON.stringify([
12244
+ model.id,
12245
+ model.name,
12246
+ model.contextWindow ?? null,
12247
+ model.maxTokens ?? null,
12248
+ model.input ?? null,
12249
+ model.reasoningEfforts ?? null,
12250
+ model.creditMultiplier ?? null
12251
+ ])).join("\n");
12252
+ }
12253
+ /**
12254
+ * Tell the host that one region's catalog changed, once per change.
12255
+ *
12256
+ * Called from `invalidateAdapter` — the single seam every `catalog.set` path
12257
+ * already ends with (a settings write through `applySelection`, and the
12258
+ * startup discovery) — so a new catalog-set path cannot forget to announce.
12259
+ * A switched-off region advertises nothing: its route is withdrawn and
12260
+ * `syncRegionRegistration` announces that topology change itself, so this
12261
+ * only records the signature.
12262
+ *
12263
+ * Emitting on a host older than 0.2.2 is deliberately harmless: cordis
12264
+ * dispatches events by name and simply has no listener for this one.
12265
+ */
12266
+ function announceCatalog(panel) {
12267
+ const signature = catalogSignature(stacks[panel].catalog.current());
12268
+ if (announcedCatalog.get(panel) === signature) return;
12269
+ announcedCatalog.set(panel, signature);
12270
+ if (!regionEnabled(current(), panel)) return;
12271
+ ctx.emit("llm/models-updated", providerOfPanel(panel));
12272
+ }
12273
+ /**
11951
12274
  * Publish each region's on/off state to the harness (issue #11). Both swaps
11952
12275
  * are single synchronous sections, so no request can observe a half-applied
11953
12276
  * state, and `replace` announces itself through `llm/adapters-updated`, which
@@ -12108,10 +12431,12 @@ function apply(ctx, config) {
12108
12431
  provider,
12109
12432
  displayName: displayNameOfTraeProvider(provider),
12110
12433
  secret: entry.secret,
12111
- resolveAttachments: () => ctx.get("attachments")
12434
+ resolveAttachments: () => ctx.get("attachments"),
12435
+ defaultEfforts: () => thinkingEffortsOf(current(), panel)
12112
12436
  });
12113
12437
  stack.invalidateAdapter = () => {
12114
12438
  trae.invalidate();
12439
+ announceCatalog(panel);
12115
12440
  };
12116
12441
  registration[panel].adapters.push({
12117
12442
  provider,
@@ -12171,4 +12496,4 @@ function apply(ctx, config) {
12171
12496
  });
12172
12497
  }
12173
12498
  //#endregion
12174
- export { Config, FALLBACK_CONTEXT_WINDOW, FALLBACK_TRAE_MODELS, FALLBACK_TRAE_MODELS_AI, MAX_PROBE_INPUT_TOKENS, REGION_GATEWAYS, SseDecoder, TRAE_ACCOUNT_STATUS_PATH, TRAE_AI_PROVIDER, TRAE_CHANNEL_PRIORITY, TRAE_CHECKIN_PATH, TRAE_CN_AGENT_TASK_PATH, TRAE_CN_TITLE_PATH, TRAE_COMMON_FUNCTIONS, TRAE_ENTERPRISE_PROVIDER, TRAE_MODELS_TEST_PATH, TRAE_MODEL_DETAIL_FUNCTIONS, TRAE_MODEL_DETAIL_PATH, TRAE_OFFICIAL_ROSTER_PATH, TRAE_PANELS, TRAE_PAY_BASE, TRAE_PROBE_TIMEOUT_MS, TRAE_PROVIDER, TRAE_PROVIDERS, TRAE_PROVIDER_DISPLAY_NAMES, TRAE_PROVIDER_IDS, TRAE_PROVIDER_ID_DISPLAY_NAMES, TRAE_PROVIDER_ROUTES, TRAE_RAW_CHAT_V1_PATH, TRAE_RAW_CHAT_V2_PATH, TRAE_REASONING_EFFORTS, TRAE_REGIONS, TRAE_REGION_PARAM, TRAE_SETTINGS_NS, TRAE_SOLO_CHAT_PATH, TRAE_SOLO_FUNCTION, TRAE_SOLO_MODELS_PATH, TRAE_SOLO_REMOTE_BASE, TRAE_STATE_DB_FILENAME, TRAE_STREAM_IDLE_TIMEOUT_MS, TRAE_USAGE_PATH, TRAE_VERSION_CODE_FALLBACK, TraeCatalog, TraeCredentialStore, TraeDelegatingUpstreamClient, TraeFallbackUpstreamClient, TraeGatedUpstreamClient, TraeOfficialRosterClient, TraeRawCapabilityController, TraeRawCapabilityState, TraeRawChatUpstreamClient, TraeSoloBridge, TraeSoloRemoteCatalogClient, TraeSoloUpstreamClient, TraeUsageClient, UnconfiguredTraeUpstreamClient, adaptLegacyPiAiContext, adaptModernPiAiContext, apply, applyContextBudgets, applyImageSelection, applyOfficialRoster, applyReasoningEffort, asVolatile, bridgeTraeSoloStream, buildTraeAgentTaskBody, buildTraeCnHeaders, buildTraeFusionRawChatEnvelope, buildTraeModelDetailRequest, buildTraeRawChatDraft, buildTraeRawChatRuntimeConfig, classifyProbeError, classifyProbeResult, classifyTraeRawChatFailure, configuredAccountsOf, createTraeAdapter, createTraeRawGateway, createTraeShim, creditPosition, decidePiAiGeneration, decodeRawChatChunk, decodeTraeEvent, decryptTraeStorageValue, deriveCatalog, describeIdShape, describeNameShape, describeTraeFailure, discoveredCatalog, displayNameOfTraeProvider, fallbackModelsFor, filterTraeModels, generationOf, groupTraeModels, hashTraeRawChatArg, identityHeaders, inject, isEnterpriseAccount, isPromotableWireModel, legacyTraeOwnAuthPath, maskUserPath, mergeTraeModelSources, name, nextRegionCreditPosition, nextRegionEnabled, nextRegionSlots, normalizeTraeCredential, normalizeTraeToolSchema, normalizeTraeToolSchemas, normalizeTraeVersionCode, officialVerdictOf, orderTraeModels, panelOfKey, panelOfProvider, parseObservedModelConfig, parseReasoningCapability, parseTraeAuthValue, parseTraeCachedModel, parseTraeModelExtraConfigLogLine, parseTraeOfficialRoster, parseTraeRawChatBehaviorConfig, parseTraeRemoteModel, parseTraeStorageDocument, piAiRuntimeInfo, pickTraeStorageIdentity, prepareSoloBody, probeBody, probeModelsSequentially, probeOneModel, probeTraeRawChatCapability, providerOfPanel, rawCapabilityDiagnostic, rawCapabilityFingerprint, readTraeCachedModel, readTraeCliIdentity, readTraeIdentity, refreshTraeCredential, regionCreditPositionOf, regionEnabled, regionEnabledOf, regionOfCredential, regionOfEdition, regionOfHost, regionOfPanel, regionOfTraeProvider, regionOfTraeStatusUrl, regionOfUserRegion, regionStateOf, registerTraeUsageRoute, resolveTraeIdentity, resolveTraeRawRuntime, routeOfTraeProvider, sanitizeCatalog, scopeTraeModels, servedContextWindow, settingsNamespaceOf, traeEndpoint, traeInputModalities, traeModelCallChannel, traeModelDisplayName, traeModelInView, traeModelMatchesQuery, traeOwnAuthPath, traeRawChatExtraInfo, traeStateDatabaseCandidates, traeStorageCandidates, traeWebUsage, traeWindowsAppNames, unwrapVolatile, unwrapVolatileDeep, wireTargetsOf, withChatCallableFunctions, withContextAdaptation, withTraeRegion };
12499
+ export { Config, FALLBACK_CONTEXT_WINDOW, FALLBACK_TRAE_MODELS, FALLBACK_TRAE_MODELS_AI, MAX_PROBE_INPUT_TOKENS, REGION_GATEWAYS, SseDecoder, TRAE_ACCOUNT_STATUS_PATH, TRAE_AI_PROVIDER, TRAE_CHANNEL_PRIORITY, TRAE_CHECKIN_PATH, TRAE_CN_AGENT_TASK_PATH, TRAE_CN_TITLE_PATH, TRAE_COMMON_FUNCTIONS, TRAE_ENTERPRISE_PROVIDER, TRAE_MODELS_TEST_PATH, TRAE_MODEL_DETAIL_FUNCTIONS, TRAE_MODEL_DETAIL_PATH, TRAE_OFFICIAL_ROSTER_PATH, TRAE_PANELS, TRAE_PAY_BASE, TRAE_PROBE_TIMEOUT_MS, TRAE_PROVIDER, TRAE_PROVIDERS, TRAE_PROVIDER_DISPLAY_NAMES, TRAE_PROVIDER_IDS, TRAE_PROVIDER_ID_DISPLAY_NAMES, TRAE_PROVIDER_ROUTES, TRAE_RAW_CHAT_V1_PATH, TRAE_RAW_CHAT_V2_PATH, TRAE_REASONING_EFFORTS, TRAE_REGIONS, TRAE_REGION_PARAM, TRAE_SETTINGS_NS, TRAE_SOLO_CHAT_PATH, TRAE_SOLO_FUNCTION, TRAE_SOLO_MODELS_PATH, TRAE_SOLO_REMOTE_BASE, TRAE_STATE_DB_FILENAME, TRAE_STREAM_IDLE_TIMEOUT_MS, TRAE_USAGE_PATH, TRAE_VERSION_CODE_FALLBACK, TraeCatalog, TraeCredentialStore, TraeDelegatingUpstreamClient, TraeFallbackUpstreamClient, TraeGatedUpstreamClient, TraeOfficialRosterClient, TraeRawCapabilityController, TraeRawCapabilityState, TraeRawChatUpstreamClient, TraeSoloBridge, TraeSoloRemoteCatalogClient, TraeSoloUpstreamClient, TraeUsageClient, UnconfiguredTraeUpstreamClient, adaptLegacyPiAiContext, adaptModernPiAiContext, apply, applyContextBudgets, applyImageSelection, applyOfficialRoster, applyReasoningEffort, asVolatile, bridgeTraeSoloStream, buildTraeAgentTaskBody, buildTraeCnHeaders, buildTraeFusionRawChatEnvelope, buildTraeModelDetailRequest, buildTraeRawChatDraft, buildTraeRawChatRuntimeConfig, classifyProbeError, classifyProbeResult, classifyTraeRawChatFailure, configuredAccountsOf, createTraeAdapter, createTraeRawGateway, createTraeShim, creditPosition, decidePiAiGeneration, decodeRawChatChunk, decodeTraeEvent, decryptTraeStorageValue, deriveCatalog, describeIdShape, describeNameShape, describeTraeFailure, discoveredCatalog, displayNameOfTraeProvider, fallbackModelsFor, filterTraeModels, generationOf, groupTraeModels, hashTraeRawChatArg, identityHeaders, inject, isEnterpriseAccount, isPromotableWireModel, legacyTraeOwnAuthPath, maskUserPath, mergeTraeModelSources, name, nextRegionCreditPosition, nextRegionEnabled, nextRegionSlots, normalizeTraeCredential, normalizeTraeToolSchema, normalizeTraeToolSchemas, normalizeTraeVersionCode, officialVerdictOf, orderTraeModels, panelOfKey, panelOfProvider, parseObservedModelConfig, parseReasoningCapability, parseTraeAuthValue, parseTraeCachedModel, parseTraeModelExtraConfigLogLine, parseTraeOfficialRoster, parseTraeRawChatBehaviorConfig, parseTraeRemoteModel, parseTraeStorageDocument, piAiRuntimeInfo, pickTraeStorageIdentity, prepareSoloBody, probeBody, probeModelsSequentially, probeOneModel, probeTraeRawChatCapability, providerOfPanel, rawCapabilityDiagnostic, rawCapabilityFingerprint, readTraeCachedModel, readTraeCliIdentity, readTraeIdentity, refreshTraeCredential, regionCreditPositionOf, regionEnabled, regionEnabledOf, regionOfCredential, regionOfEdition, regionOfHost, regionOfPanel, regionOfTraeProvider, regionOfTraeStatusUrl, regionOfUserRegion, regionStateOf, registerTraeUsageRoute, resolveTraeIdentity, resolveTraeRawRuntime, routeOfTraeProvider, sanitizeCatalog, scopeTraeModels, servedContextWindow, settingsNamespaceOf, sidebarPanelEnabled, thinkingEffortsOf, traeEndpoint, traeInputModalities, traeModelCallChannel, traeModelDisplayName, traeModelInView, traeModelMatchesQuery, traeOwnAuthPath, traeRawChatExtraInfo, traeStateDatabaseCandidates, traeStorageCandidates, traeWebUsage, traeWindowsAppNames, unwrapVolatile, unwrapVolatileDeep, wireTargetsOf, withChatCallableFunctions, withContextAdaptation, withTraeRegion };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-trae",
3
3
  "displayName": "DSH Connect Trae",
4
4
  "description": "把本机登录的 Trae 模型接入 DeepSeek Harness:国内版与国际版双供应商并行,提供用量/积分概览与每日签到领取。",
5
- "version": "4.6.12",
5
+ "version": "4.8.1",
6
6
  "author": "dingminhua",
7
7
  "copyright": "Copyright (c) 2026 LaoDing",
8
8
  "license": "MIT",
@@ -34,6 +34,7 @@
34
34
  "lib",
35
35
  "icons",
36
36
  "docs/assets/dsh-connect-trae-usage-card.png",
37
+ "docs/assets/dsh-connect-trae-sidebar-page.png",
37
38
  "scripts/verify-windows.mjs",
38
39
  "screenshots.json",
39
40
  "cordis.patch.yml",
@@ -99,22 +100,22 @@
99
100
  }
100
101
  },
101
102
  "devDependencies": {
102
- "@deepseek-ai/cordis": "^4.0.5",
103
- "@deepseek-ai/dsh-atomic-write": "0.2.1-rc.5",
104
- "@deepseek-ai/dsh-attachment": "0.2.1-rc.5",
105
- "@deepseek-ai/dsh-client-locale": "0.2.1-rc.5",
106
- "@deepseek-ai/dsh-client-ui-primitives": "0.2.1-rc.5",
107
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.1-rc.5",
108
- "@deepseek-ai/dsh-client-ui-settings": "0.2.1-rc.5",
109
- "@deepseek-ai/dsh-client-ui-settings-plugins": "0.2.1-rc.5",
110
- "@deepseek-ai/dsh-client-ui-slots": "0.2.1-rc.5",
111
- "@deepseek-ai/dsh-home-paths": "0.2.1-rc.5",
112
- "@deepseek-ai/dsh-host-webserver": "0.2.1-rc.5",
113
- "@deepseek-ai/dsh-llm": "0.2.1-rc.5",
114
- "@deepseek-ai/dsh-llm-pi-ai": "0.2.1-rc.5",
115
- "@deepseek-ai/dsh-settings": "0.2.1-rc.5",
116
- "@deepseek-ai/schemastery": "3.18.5",
117
- "@earendil-works/pi-ai": "1.1.0",
103
+ "@deepseek-ai/cordis": "^4.1.0",
104
+ "@deepseek-ai/dsh-atomic-write": "0.2.2-rc.1",
105
+ "@deepseek-ai/dsh-attachment": "0.2.2-rc.1",
106
+ "@deepseek-ai/dsh-client-locale": "0.2.2-rc.1",
107
+ "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.1",
108
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.1",
109
+ "@deepseek-ai/dsh-client-ui-settings": "0.2.2-rc.1",
110
+ "@deepseek-ai/dsh-client-ui-settings-plugins": "0.2.2-rc.1",
111
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.1",
112
+ "@deepseek-ai/dsh-home-paths": "0.2.2-rc.1",
113
+ "@deepseek-ai/dsh-host-webserver": "0.2.2-rc.1",
114
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
115
+ "@deepseek-ai/dsh-llm-pi-ai": "0.2.2-rc.1",
116
+ "@deepseek-ai/dsh-settings": "0.2.2-rc.1",
117
+ "@deepseek-ai/schemastery": "3.19.0",
118
+ "@earendil-works/pi-ai": "1.3.0",
118
119
  "@testing-library/dom": "^10.4.2",
119
120
  "@testing-library/react": "^16.3.3",
120
121
  "@types/node": "^22.20.0",