dsh-connect-trae 1.0.0 → 1.1.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
@@ -14,6 +14,161 @@ import { createServer } from "node:http";
14
14
  import { Readable } from "node:stream";
15
15
  import { execFile } from "node:child_process";
16
16
  import { promisify } from "node:util";
17
+ //#region src/catalog.ts
18
+ /** Bootstrap catalog: identity only where current Trae metadata has not been fetched yet. */
19
+ const FALLBACK_TRAE_MODELS = [
20
+ {
21
+ id: "auto",
22
+ name: "Auto"
23
+ },
24
+ {
25
+ id: "DeepSeek-V4-Flash",
26
+ name: "DeepSeek-V4-Flash"
27
+ },
28
+ {
29
+ id: "DeepSeek-V4-Pro",
30
+ name: "DeepSeek-V4-Pro"
31
+ },
32
+ {
33
+ id: "glm-5.2",
34
+ name: "GLM-5.2"
35
+ },
36
+ {
37
+ id: "kimi-k2.6",
38
+ name: "Kimi-K2.6"
39
+ }
40
+ ];
41
+ /** Exact DSH modalities for one catalog entry; absent metadata is text-only. */
42
+ function traeInputModalities(model) {
43
+ return [...model.input ?? ["text"]];
44
+ }
45
+ /** Apply the user's explicit image opt-ins; upstream and saved row hints are ignored. */
46
+ function applyImageSelection(models, selected) {
47
+ return models.map((model) => ({
48
+ ...model,
49
+ input: selected.has(model.id) ? ["text", "image"] : ["text"]
50
+ }));
51
+ }
52
+ /** Normalise a display name for cross-source joining. */
53
+ function displayKey(name) {
54
+ return name.trim().toLowerCase();
55
+ }
56
+ /**
57
+ * Merge the two Trae model sources into one authoritative catalog.
58
+ *
59
+ * `remote` (the solo.trae.cn `/models` directory) is the authoritative model
60
+ * skeleton: it supplies the display id, display name, context windows, credit
61
+ * multiplier, reasoning and multimodal flags. `wire` (from `get_detail_param`)
62
+ * supplies the real `llm_utils_chat` `config_name` — the only id the chat
63
+ * endpoint actually accepts. A remote row is only callable when it maps to a
64
+ * wire `config_name`, so a remote row with no wire match is DROPPED (it would
65
+ * otherwise be sent as an invalid `config_name` and rejected with 4001
66
+ * "param is invalid"). Verified 2026-08-30: the Remote directory advertises
67
+ * `Doubao-Seed-Code` and `glm-5.3`, neither of which is a current `config_name`;
68
+ * both fail every request, so they must not be exposed.
69
+ *
70
+ * Joining is two-tier, in priority order:
71
+ * 1. `wire.id` (the `config_name`) equals the remote id — the model's display
72
+ * id is already its wire id (the common case: glm-5.2, DeepSeek-V4-Flash,
73
+ * kimi-k3, …).
74
+ * 2. `wire.name` (the `display_name`) equals the remote display name — for
75
+ * models whose display id differs from the wire id across Trae versions.
76
+ * When the matched wire `config_name` differs from the remote id it is recorded
77
+ * as `wireConfigName`; otherwise it is left undefined (id is already the wire id).
78
+ */
79
+ function mergeTraeModelSources(remote, wire) {
80
+ const wireByName = /* @__PURE__ */ new Map();
81
+ const wireById = /* @__PURE__ */ new Map();
82
+ for (const model of wire) {
83
+ wireByName.set(displayKey(model.name), model);
84
+ wireById.set(displayKey(model.id), model);
85
+ }
86
+ const result = [];
87
+ for (const model of remote) {
88
+ const wireModel = wireById.get(displayKey(model.id)) ?? wireByName.get(displayKey(model.name));
89
+ if (wireModel === void 0) continue;
90
+ result.push({
91
+ id: model.id,
92
+ name: model.name,
93
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
94
+ ...model.maxContextWindow === void 0 ? {} : { maxContextWindow: model.maxContextWindow },
95
+ ...model.creditMultiplier === void 0 ? {} : { creditMultiplier: model.creditMultiplier },
96
+ input: ["text"],
97
+ reasoningSupported: model.reasoningSupported,
98
+ ...model.reasoning === void 0 ? {} : {
99
+ reasoning: model.reasoning,
100
+ reasoningEfforts: Object.fromEntries(model.reasoning.supported.map((effort) => [effort, effort === "low" ? "light" : effort === "xhigh" ? "extra_high" : "high"]))
101
+ },
102
+ ...wireModel.id !== "" && wireModel.id !== model.id ? { wireConfigName: wireModel.id } : {}
103
+ });
104
+ }
105
+ return result;
106
+ }
107
+ /**
108
+ * Apply the saved local budget. Trae advertises two windows per model (dev and
109
+ * Max), so the budget may only switch a model to its own advertised Max value —
110
+ * never to a fabricated number. Everything else keeps the dev window.
111
+ */
112
+ function applyContextBudgets(catalog, budgets = {}) {
113
+ return catalog.map((model) => ({
114
+ ...model,
115
+ ...model.maxContextWindow !== void 0 && budgets[model.id] === model.maxContextWindow ? { contextWindow: model.maxContextWindow } : {}
116
+ }));
117
+ }
118
+ /** Convert Trae metadata into text-only model rows; image support is user-owned configuration. */
119
+ function discoveredCatalog(models) {
120
+ const result = [];
121
+ for (const model of models) result.push({
122
+ id: model.id,
123
+ name: model.name,
124
+ ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
125
+ ...model.maxContextWindow === void 0 ? {} : { maxContextWindow: model.maxContextWindow },
126
+ input: ["text"],
127
+ ...model.creditMultiplier === void 0 ? {} : { creditMultiplier: model.creditMultiplier },
128
+ reasoningSupported: model.reasoningSupported,
129
+ ...model.reasoning === void 0 ? {} : {
130
+ reasoning: model.reasoning,
131
+ reasoningEfforts: Object.fromEntries(model.reasoning.supported.map((effort) => [effort, effort === "low" ? "light" : effort === "xhigh" ? "extra_high" : "high"]))
132
+ }
133
+ });
134
+ return result;
135
+ }
136
+ /**
137
+ * Drop rows saved by older releases that generated `@1m` variant models, so a
138
+ * stale configuration cannot resurrect a variant the runtime no longer builds.
139
+ */
140
+ function sanitizeCatalog(catalog) {
141
+ return catalog.filter((model) => {
142
+ if (model.id.endsWith("@1m")) return false;
143
+ const legacy = model;
144
+ return legacy.baseModelId === void 0 && legacy.maxContext !== true;
145
+ });
146
+ }
147
+ /**
148
+ * Derive the runtime catalog from the last refreshed Trae directory plus the
149
+ * user's explicit selection and context budgets. An empty selection falls back
150
+ * to the whole directory: a plugin that has never been configured must still
151
+ * serve models rather than nothing. This is the single source of truth for
152
+ * what DSH actually exposes, so saving only the selection and budgets is
153
+ * enough to rebuild it after a restart.
154
+ */
155
+ function deriveCatalog(catalog, enabled, budgets = {}) {
156
+ return applyContextBudgets(enabled.size === 0 ? catalog : catalog.filter((model) => enabled.has(model.id)), budgets);
157
+ }
158
+ var TraeCatalog = class {
159
+ models = FALLBACK_TRAE_MODELS;
160
+ current() {
161
+ return this.models;
162
+ }
163
+ set(models) {
164
+ if (models.length === 0) throw new Error("trae model catalog cannot be empty");
165
+ this.models = models.map((model) => ({
166
+ ...model,
167
+ ...model.input === void 0 ? {} : { input: [...model.input] }
168
+ }));
169
+ }
170
+ };
171
+ //#endregion
17
172
  //#region src/adapter.ts
18
173
  const TRAE_PROVIDER = "trae";
19
174
  const TRAE_STREAM_IDLE_TIMEOUT_MS = 3e5;
@@ -47,7 +202,7 @@ function toPiModel(info, baseUrl) {
47
202
  api: "openai-completions",
48
203
  provider: TRAE_PROVIDER,
49
204
  baseUrl,
50
- input: [...info.input ?? ["text"]],
205
+ input: traeInputModalities(info),
51
206
  cost: {
52
207
  input: 0,
53
208
  output: 0,
@@ -528,7 +683,6 @@ var TraeCredentialStore = class {
528
683
  storagePathOverride;
529
684
  edition;
530
685
  accountId;
531
- preferIds = [];
532
686
  ownPath;
533
687
  refresh;
534
688
  refreshMarginMs;
@@ -551,16 +705,6 @@ var TraeCredentialStore = class {
551
705
  this.accountId = accountId;
552
706
  this.inflight = void 0;
553
707
  }
554
- /**
555
- * Preferred account ordering used when no account is explicitly selected.
556
- * The connector can only bill the `llm_utils_chat` channel against general
557
- * credits, so accounts with zero general credits should not become the
558
- * default or they fail with 4008 / empty responses.
559
- */
560
- setPreferAccountIds(ids) {
561
- this.preferIds = [...ids];
562
- this.inflight = void 0;
563
- }
564
708
  candidates() {
565
709
  if (this.storagePathOverride !== void 0) return [{
566
710
  edition: this.edition === "auto" ? "cn" : this.edition,
@@ -569,13 +713,13 @@ var TraeCredentialStore = class {
569
713
  const all = traeStorageCandidates();
570
714
  return this.edition === "auto" ? all.filter((candidate) => candidate.edition === "cn" || candidate.edition === "solo") : all.filter((candidate) => candidate.edition === this.edition && (candidate.edition === "cn" || candidate.edition === "solo"));
571
715
  }
572
- /** First credential matching the preferred ordering, else the first live one. */
716
+ /**
717
+ * Deterministic default when no account is explicitly selected: the first
718
+ * discovered account. This is NOT credit-seeking — it never reorders accounts
719
+ * to find one with general credits. The plugin bills exactly the account the
720
+ * user selected, or the first account when nothing has been selected yet.
721
+ */
573
722
  preferred(credentials) {
574
- if (credentials.length === 0) return void 0;
575
- for (const id of this.preferIds) {
576
- const match = credentials.find((credential) => traeAccountId(credential) === id);
577
- if (match !== void 0) return match;
578
- }
579
723
  return credentials[0];
580
724
  }
581
725
  async accounts() {
@@ -594,7 +738,7 @@ var TraeCredentialStore = class {
594
738
  async current() {
595
739
  const credentials = await this.readAll();
596
740
  if (this.accountId === void 0) return this.preferred(credentials);
597
- return credentials.find((credential) => traeAccountId(credential) === this.accountId) ?? this.preferred(credentials);
741
+ return credentials.find((credential) => traeAccountId(credential) === this.accountId);
598
742
  }
599
743
  async resolve() {
600
744
  const credential = await this.current();
@@ -685,104 +829,6 @@ var TraeCredentialStore = class {
685
829
  }
686
830
  };
687
831
  //#endregion
688
- //#region src/catalog.ts
689
- /** Bootstrap catalog: identity only where current Trae metadata has not been fetched yet. */
690
- const FALLBACK_TRAE_MODELS = [
691
- {
692
- id: "auto",
693
- name: "Auto"
694
- },
695
- {
696
- id: "DeepSeek-V4-Flash",
697
- name: "DeepSeek-V4-Flash"
698
- },
699
- {
700
- id: "DeepSeek-V4-Pro",
701
- name: "DeepSeek-V4-Pro"
702
- },
703
- {
704
- id: "Doubao-Seed-Code",
705
- name: "Doubao-Seed-Code",
706
- input: ["text", "image"]
707
- },
708
- {
709
- id: "kimi-k2.6",
710
- name: "Kimi-K2.6",
711
- input: ["text", "image"]
712
- }
713
- ];
714
- /** Convert verified Trae API metadata into normal models and optional 1M variants. */
715
- function discoveredCatalog(models, enabled1m = /* @__PURE__ */ new Set()) {
716
- const result = [];
717
- for (const model of models) {
718
- const common = {
719
- input: model.multimodal ? ["text", "image"] : ["text"],
720
- ...model.creditMultiplier === void 0 ? {} : { creditMultiplier: model.creditMultiplier },
721
- reasoningSupported: model.reasoningSupported,
722
- ...model.reasoning === void 0 ? {} : {
723
- reasoning: model.reasoning,
724
- reasoningEfforts: Object.fromEntries(model.reasoning.supported.map((effort) => [effort, effort === "low" ? "light" : effort === "xhigh" ? "extra_high" : "high"]))
725
- }
726
- };
727
- result.push({
728
- id: model.id,
729
- name: model.name,
730
- ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
731
- ...model.maxContextWindow === void 0 ? {} : { maxContextWindow: model.maxContextWindow },
732
- ...common
733
- });
734
- if (model.maxContextWindow !== void 0 && enabled1m.has(model.id)) result.push({
735
- id: `${model.id}@1m`,
736
- name: `${model.name} 1M`,
737
- contextWindow: model.maxContextWindow,
738
- baseModelId: model.id,
739
- maxContext: true,
740
- ...common
741
- });
742
- }
743
- return result;
744
- }
745
- /**
746
- * Derive the runtime catalog from the last refreshed Trae directory plus the
747
- * user's explicit selection. Ordinary models whose `id` (Trae `name`) is
748
- * enabled survive; each 1M-capable enabled model produces a `@1m` variant.
749
- * This is the single source of truth for what DSH actually exposes, so saving
750
- * only the selection is enough to rebuild it after a restart.
751
- */
752
- function deriveCatalog(catalog, enabled, enabled1m) {
753
- const result = [];
754
- for (const model of catalog) {
755
- if (!enabled.has(model.id)) continue;
756
- result.push(model);
757
- if (enabled1m.has(model.id) && model.maxContextWindow !== void 0) result.push({
758
- id: `${model.id}@1m`,
759
- name: `${model.name} 1M`,
760
- contextWindow: model.maxContextWindow,
761
- baseModelId: model.id,
762
- maxContext: true,
763
- ...model.input === void 0 ? {} : { input: [...model.input] },
764
- ...model.creditMultiplier === void 0 ? {} : { creditMultiplier: model.creditMultiplier },
765
- ...model.reasoningSupported === void 0 ? {} : { reasoningSupported: model.reasoningSupported },
766
- ...model.reasoning === void 0 ? {} : { reasoning: model.reasoning },
767
- ...model.reasoningEfforts === void 0 ? {} : { reasoningEfforts: model.reasoningEfforts }
768
- });
769
- }
770
- return result;
771
- }
772
- var TraeCatalog = class {
773
- models = FALLBACK_TRAE_MODELS;
774
- current() {
775
- return this.models;
776
- }
777
- set(models) {
778
- if (models.length === 0) throw new Error("trae model catalog cannot be empty");
779
- this.models = models.map((model) => ({
780
- ...model,
781
- ...model.input === void 0 ? {} : { input: [...model.input] }
782
- }));
783
- }
784
- };
785
- //#endregion
786
832
  //#region src/refresh.ts
787
833
  const CLIENT_ID_BY_EDITION = {
788
834
  cn: "ono9krqynydwx5",
@@ -834,7 +880,10 @@ function deviceCenterId(storage) {
834
880
  return ids.length === 1 ? ids[0] : void 0;
835
881
  }
836
882
  /** Read stable identity from Trae-owned files without generating impersonated IDs. */
837
- async function readTraeIdentity(candidate) {
883
+ async function readTraeIdentity(candidate, options = {}) {
884
+ const platform = options.platform ?? process.platform;
885
+ const home = options.home ?? homedir();
886
+ const env = options.env ?? process.env;
838
887
  const storage = JSON.parse(await readFile(candidate.path, "utf8"));
839
888
  const appRoot = dirname(dirname(dirname(candidate.path)));
840
889
  const machineFile = nonEmpty(await readFile(join(appRoot, "machineid"), "utf8").catch(() => ""));
@@ -845,16 +894,24 @@ async function readTraeIdentity(candidate) {
845
894
  if (machineId === void 0) throw new Error(`Trae ${candidate.edition} has no stable machine identity`);
846
895
  const deviceId = dcDevice ?? devDevice ?? createHash("sha256").update(machineId).digest("hex").slice(0, 32);
847
896
  const buildVersion = nonEmpty(storage["iCubeLastVersion"]);
848
- const productPaths = candidate.edition === "cn" || candidate.edition === "solo" ? [candidate.edition === "cn" ? "/Applications/Trae CN.app/Contents/Resources/app/product.json" : "/Applications/TRAE SOLO CN.app/Contents/Resources/app/product.json"] : [];
897
+ const appName = candidate.edition === "cn" ? "Trae CN" : candidate.edition === "solo" ? "TRAE SOLO CN" : void 0;
898
+ const productPaths = [];
899
+ if (appName !== void 0 && (platform === "darwin" || platform === "win32")) {
900
+ if (platform === "darwin") productPaths.push(join("/Applications", `${appName}.app`, "Contents", "Resources", "app", "product.json"));
901
+ else {
902
+ const localRoots = [env.LOCALAPPDATA, join(home, "AppData", "Local")].filter((value) => typeof value === "string" && value !== "").filter((value, index, all) => all.indexOf(value) === index);
903
+ for (const root of localRoots) productPaths.push(join(root, "Programs", appName, "resources", "app", "product.json"));
904
+ }
905
+ }
849
906
  let product = {};
850
907
  for (const path of productPaths) try {
851
908
  product = JSON.parse(await readFile(path, "utf8"));
852
909
  break;
853
910
  } catch {}
854
911
  const appVersion = nonEmpty(product["appVersion"]);
855
- const deviceBrand = process.platform === "darwin" ? nonEmpty(process.env["TRAE_DEVICE_BRAND"]) : void 0;
912
+ const deviceBrand = platform === "darwin" ? nonEmpty(env["TRAE_DEVICE_BRAND"]) : void 0;
856
913
  const deviceCpu = cpus()[0]?.model.split(" ")[0];
857
- const osVersion = `${process.platform === "darwin" ? "macOS" : process.platform} ${release()}`;
914
+ const osVersion = `${platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : platform} ${release()}`;
858
915
  return {
859
916
  edition: candidate.edition,
860
917
  machineId,
@@ -864,7 +921,7 @@ async function readTraeIdentity(candidate) {
864
921
  ...deviceBrand === void 0 ? {} : { deviceBrand },
865
922
  ...deviceCpu === void 0 ? {} : { deviceCpu },
866
923
  osVersion,
867
- platform: process.platform
924
+ platform
868
925
  };
869
926
  }
870
927
  /** Headers derived from actual persisted identity, never a new random identity per request. */
@@ -1189,7 +1246,7 @@ function applyReasoningEffort(body, effort, capability) {
1189
1246
  const TRAE_SOLO_FUNCTION = "solo_work_lite";
1190
1247
  const TRAE_SOLO_CHAT_PATH = "/api/agent/v3/llm_utils_chat";
1191
1248
  const TRAE_SOLO_MODELS_PATH = "/api/ide/v1/get_detail_param";
1192
- function classify$1(status) {
1249
+ function classify(status) {
1193
1250
  if (status === 401 || status === 403) return "authentication";
1194
1251
  if (status === 402) return "hard_credit";
1195
1252
  if (status === 429) return "soft_rate";
@@ -1197,13 +1254,21 @@ function classify$1(status) {
1197
1254
  if (status >= 500) return "server";
1198
1255
  return "client";
1199
1256
  }
1257
+ function finitePositive$1(value) {
1258
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
1259
+ }
1200
1260
  function prepareSoloBody(source, defaultModel = "glm-5.2") {
1201
- const body = JSON.parse(source);
1202
- const model = typeof body["model"] === "string" && body["model"].trim() !== "" ? body["model"].trim() : defaultModel;
1203
- body["model"] = model;
1204
- body["config_name"] = model;
1205
- body["function"] = TRAE_SOLO_FUNCTION;
1206
- body["stream"] = true;
1261
+ const input = JSON.parse(source);
1262
+ const model = typeof input["model"] === "string" && input["model"].trim() !== "" ? input["model"].trim() : defaultModel;
1263
+ const body = {
1264
+ ...Array.isArray(input["messages"]) ? { messages: input["messages"] } : {},
1265
+ model,
1266
+ config_name: model,
1267
+ function: TRAE_SOLO_FUNCTION,
1268
+ stream: true,
1269
+ ...Array.isArray(input["tools"]) ? { tools: input["tools"] } : {},
1270
+ ...typeof input["reasoning_effort"] === "string" ? { reasoning_effort: input["reasoning_effort"] } : {}
1271
+ };
1207
1272
  if (Array.isArray(body["messages"])) for (const raw of body["messages"]) {
1208
1273
  if (typeof raw !== "object" || raw === null) continue;
1209
1274
  const message = raw;
@@ -1272,8 +1337,11 @@ var TraeSoloUpstreamClient = class {
1272
1337
  const display = typeof config["display_config"] === "object" && config["display_config"] !== null ? config["display_config"] : {};
1273
1338
  const details = Array.isArray(config["model_detail_list"]) ? config["model_detail_list"] : [];
1274
1339
  const detail = typeof details[0] === "object" && details[0] !== null ? details[0] : {};
1275
- const contextWindow = typeof detail["max_input_tokens"] === "number" ? detail["max_input_tokens"] : typeof config["max_input_tokens"] === "number" ? config["max_input_tokens"] : void 0;
1276
- const maxTokens = typeof detail["max_output_tokens"] === "number" ? detail["max_output_tokens"] : typeof config["max_output_tokens"] === "number" ? config["max_output_tokens"] : void 0;
1340
+ const contextTokens = typeof config["context_window_tokens"] === "object" && config["context_window_tokens"] !== null ? config["context_window_tokens"] : {};
1341
+ const promptMaxTokens = finitePositive$1(detail["prompt_max_tokens"]);
1342
+ const devTokens = finitePositive$1(contextTokens["dev"]);
1343
+ const contextWindow = promptMaxTokens ?? devTokens;
1344
+ const maxTokens = finitePositive$1(detail["max_tokens"]);
1277
1345
  const reasoning = parseReasoningCapability({
1278
1346
  ...config,
1279
1347
  ...detail
@@ -1324,10 +1392,17 @@ var TraeSoloUpstreamClient = class {
1324
1392
  response
1325
1393
  };
1326
1394
  const text = (await response.text()).slice(0, 1024);
1395
+ this.options.log?.("dsh-connect-trae: llm_utils_chat rejected", {
1396
+ status: response.status,
1397
+ model: JSON.parse(prepared)["model"],
1398
+ configName: JSON.parse(prepared)["config_name"],
1399
+ reasoningEffort: JSON.parse(prepared)["reasoning_effort"],
1400
+ body: text
1401
+ });
1327
1402
  return {
1328
1403
  ok: false,
1329
1404
  status: response.status,
1330
- kind: classify$1(response.status),
1405
+ kind: classify(response.status),
1331
1406
  message: text || `Trae SOLO returned HTTP ${response.status}`
1332
1407
  };
1333
1408
  }
@@ -1474,7 +1549,8 @@ function bridgeTraeSoloStream(response, model) {
1474
1549
  const encoder = new TextEncoder();
1475
1550
  const sse = new SseDecoder();
1476
1551
  let sawToolCalls = false;
1477
- let emittedDone = false;
1552
+ let emittedFinishReason = false;
1553
+ let upstreamEnded = false;
1478
1554
  let upstreamError;
1479
1555
  let usage;
1480
1556
  const chunk = (delta, finishReason = null) => encoder.encode(`data: ${JSON.stringify({
@@ -1515,13 +1591,16 @@ function bridgeTraeSoloStream(response, model) {
1515
1591
  ...decoded.outputTokens === void 0 ? {} : { completion_tokens: decoded.outputTokens },
1516
1592
  ...decoded.totalTokens === void 0 ? {} : { total_tokens: decoded.totalTokens }
1517
1593
  };
1518
- else if (decoded.type === "done" && !emittedDone) {
1519
- emittedDone = true;
1520
- if (upstreamError !== void 0) {
1521
- controller.error(upstreamError);
1522
- return;
1594
+ else if (decoded.type === "done") {
1595
+ upstreamEnded = true;
1596
+ if (!emittedFinishReason) {
1597
+ emittedFinishReason = true;
1598
+ if (upstreamError !== void 0) {
1599
+ controller.error(upstreamError);
1600
+ return;
1601
+ }
1602
+ controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : decoded.finishReason || "stop"));
1523
1603
  }
1524
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : decoded.finishReason));
1525
1604
  }
1526
1605
  };
1527
1606
  try {
@@ -1531,11 +1610,14 @@ function bridgeTraeSoloStream(response, model) {
1531
1610
  for (const event of sse.push(decoder.decode(next.value, { stream: true }))) consume(event);
1532
1611
  }
1533
1612
  for (const event of sse.finish()) consume(event);
1534
- if (upstreamError !== void 0 && !emittedDone) {
1613
+ if (upstreamError !== void 0 && !upstreamEnded) {
1535
1614
  controller.error(upstreamError);
1536
1615
  return;
1537
1616
  }
1538
- if (!emittedDone) controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
1617
+ if (!emittedFinishReason) {
1618
+ emittedFinishReason = true;
1619
+ controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
1620
+ }
1539
1621
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
1540
1622
  controller.close();
1541
1623
  } catch (error) {
@@ -1556,14 +1638,34 @@ function bridgeTraeSoloStream(response, model) {
1556
1638
  /** Native SOLO client wrapper used by the loopback OpenAI adapter. */
1557
1639
  var TraeSoloBridge = class {
1558
1640
  upstream;
1559
- constructor(upstream) {
1641
+ catalog;
1642
+ wireResolver;
1643
+ constructor(upstream, catalog, wireResolver) {
1560
1644
  this.upstream = upstream;
1645
+ this.catalog = catalog;
1646
+ this.wireResolver = wireResolver;
1561
1647
  }
1562
1648
  async chatStream(bodyJson, signal) {
1563
1649
  let model = "glm-5.2";
1650
+ let prepared = bodyJson;
1564
1651
  try {
1565
1652
  const input = JSON.parse(bodyJson);
1566
- if (typeof input["model"] === "string" && input["model"] !== "") model = input["model"].endsWith("@1m") ? input["model"].slice(0, -3) : input["model"];
1653
+ if (typeof input["model"] === "string" && input["model"] !== "") model = input["model"];
1654
+ const entry = this.catalog?.current().find((item) => item.id === model);
1655
+ const wireModel = entry?.wireConfigName ?? this.wireResolver?.(model) ?? this.wireResolver?.(entry?.name ?? "") ?? model;
1656
+ if (wireModel !== input["model"]) {
1657
+ input["model"] = wireModel;
1658
+ prepared = JSON.stringify(input);
1659
+ }
1660
+ if (typeof input["reasoning_effort"] === "string") {
1661
+ const efforts = entry?.reasoningEfforts;
1662
+ const requested = input["reasoning_effort"];
1663
+ const mapped = efforts?.[requested];
1664
+ const allowed = efforts === void 0 ? [] : Object.values(efforts).filter((value) => typeof value === "string");
1665
+ if (typeof mapped === "string") input["reasoning_effort"] = mapped;
1666
+ else if (!allowed.includes(requested)) delete input["reasoning_effort"];
1667
+ prepared = JSON.stringify(input);
1668
+ }
1567
1669
  } catch {
1568
1670
  return {
1569
1671
  ok: false,
@@ -1572,7 +1674,7 @@ var TraeSoloBridge = class {
1572
1674
  message: "invalid JSON request"
1573
1675
  };
1574
1676
  }
1575
- const result = await this.upstream.chatStream(bodyJson, signal);
1677
+ const result = await this.upstream.chatStream(prepared, signal);
1576
1678
  if (!result.ok) return result;
1577
1679
  return {
1578
1680
  ok: true,
@@ -1639,147 +1741,20 @@ function parseTraeRemoteModel(value) {
1639
1741
  //#endregion
1640
1742
  //#region src/solo-remote.ts
1641
1743
  const TRAE_SOLO_REMOTE_BASE = "https://solo.trae.cn/api/remote/v1";
1642
- const TRAE_SOLO_REMOTE_MODELS = [
1643
- {
1644
- name: "DeepSeek-V4-Flash",
1645
- displayName: "DeepSeek-V4-Flash",
1646
- multimodal: false
1647
- },
1648
- {
1649
- name: "DeepSeek-V4-Pro",
1650
- displayName: "DeepSeek-V4-Pro",
1651
- multimodal: false
1652
- },
1653
- {
1654
- name: "Doubao_1_6",
1655
- displayName: "Doubao-Seed-Code",
1656
- multimodal: true
1657
- },
1658
- {
1659
- name: "Doubao-Seed-2.0-Code",
1660
- displayName: "Doubao-Seed-2.0-Code",
1661
- multimodal: true
1662
- },
1663
- {
1664
- name: "kimi-k2.6",
1665
- displayName: "Kimi-K2.6",
1666
- multimodal: true
1667
- },
1668
- {
1669
- name: "kimi-k2.5",
1670
- displayName: "Kimi-K2.5",
1671
- multimodal: true
1672
- },
1673
- {
1674
- name: "qwen-3.6-plus",
1675
- displayName: "Qwen3.6-Plus",
1676
- multimodal: true
1677
- },
1678
- {
1679
- name: "qwen-3.5",
1680
- displayName: "Qwen3.5",
1681
- multimodal: true
1682
- },
1683
- {
1684
- name: "glm-5.1",
1685
- displayName: "GLM-5.1",
1686
- multimodal: false
1687
- },
1688
- {
1689
- name: "glm-5",
1690
- displayName: "GLM-5",
1691
- multimodal: false
1692
- },
1693
- {
1694
- name: "glm-5v-turbo",
1695
- displayName: "GLM-5V-Turbo",
1696
- multimodal: true
1697
- },
1698
- {
1699
- name: "minimax-m2.7",
1700
- displayName: "MiniMax-M2.7",
1701
- multimodal: false
1702
- },
1703
- {
1704
- name: "minimax-m2.5",
1705
- displayName: "MiniMax-M2.5",
1706
- multimodal: false
1707
- }
1708
- ];
1709
1744
  /**
1710
- * Preserve DSH's complete text conversation in the one query accepted by the
1711
- * SOLO Remote create-session endpoint. System instructions (including DSH's
1712
- * workspace/cwd context), assistant history, tool-result text and the newest
1713
- * user request stay ordered instead of collapsing to the last user message.
1745
+ * Read-only model catalog client for the SOLO Web API.
1746
+ *
1747
+ * This deliberately has no chat/session method: the Remote session protocol
1748
+ * only exposes a final answer and cannot preserve DSH's structured tool loop.
1714
1749
  */
1715
- function serializeTraeConversation(messages) {
1716
- if (messages.length === 1 && messages[0]?.role === "user") return messages[0].content;
1717
- return messages.map((message) => `<dsh-message role="${message.role}">\n${message.content}\n</dsh-message>`).join("\n\n");
1718
- }
1719
- function decodeUserId(token) {
1720
- try {
1721
- return JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64").toString("utf8")).data?.id ?? "0";
1722
- } catch {
1723
- return "0";
1724
- }
1725
- }
1726
- function generateWebId() {
1727
- return String(Math.floor(Math.random() * 9e15) + 0x38d7ea4c68000);
1728
- }
1729
- function buildCommonParams(userId, webId, sessionId) {
1730
- return JSON.stringify({
1731
- language: "zh-cn",
1732
- app_language: "en",
1733
- quality: "stable",
1734
- app_version: "1.0.0.1300",
1735
- user_identity: "Free",
1736
- is_freshman: "0",
1737
- scope: "marscode",
1738
- tenant: "marscode",
1739
- region: "CN",
1740
- aiRegion: "CN",
1741
- solo_chat_mode: "code",
1742
- is_privacy_mode: 1,
1743
- privacy_mode: "on",
1744
- ...sessionId === void 0 ? {} : { biz_session_id: sessionId },
1745
- web_id: webId,
1746
- biz_user_id: userId,
1747
- user_unique_id: userId
1748
- });
1749
- }
1750
- function extractContent(raw) {
1751
- try {
1752
- const parsed = JSON.parse(raw);
1753
- if (Array.isArray(parsed)) return parsed.filter((c) => typeof c === "object" && c !== null && c.type === "text").map((c) => c.text_content ?? "").join("");
1754
- if (typeof parsed === "object" && parsed !== null && Array.isArray(parsed.messages)) {
1755
- const parts = [];
1756
- for (const msg of parsed.messages) {
1757
- if (typeof msg !== "object" || msg === null) continue;
1758
- const pi = msg.plan_item;
1759
- if (typeof pi !== "object" || pi === null) continue;
1760
- const tc = pi.tool_call_info;
1761
- if (typeof tc !== "object" || tc === null) continue;
1762
- const tool = tc;
1763
- if (tool.name === "finish" && tool.params?.summary) parts.push(tool.params.summary);
1764
- else if (tool.result?.data?.summary && tool.name !== "finish") parts.push(tool.result.data.summary);
1765
- }
1766
- return parts.join("\n\n");
1767
- }
1768
- } catch {}
1769
- return raw;
1770
- }
1771
- var TraeSoloRemoteClient = class {
1750
+ var TraeSoloRemoteCatalogClient = class {
1772
1751
  options;
1773
1752
  fetchImpl;
1774
1753
  baseUrl;
1775
- pollIntervalMs;
1776
- timeoutMs;
1777
1754
  constructor(options) {
1778
1755
  this.options = options;
1779
1756
  this.fetchImpl = options.fetchImpl ?? fetch;
1780
1757
  this.baseUrl = options.baseUrl ?? "https://solo.trae.cn/api/remote/v1";
1781
- this.pollIntervalMs = options.pollIntervalMs ?? 2e3;
1782
- this.timeoutMs = options.timeoutMs ?? 12e4;
1783
1758
  }
1784
1759
  async headers() {
1785
1760
  return {
@@ -1792,77 +1767,6 @@ var TraeSoloRemoteClient = class {
1792
1767
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
1793
1768
  };
1794
1769
  }
1795
- async chat(messages, model, signal) {
1796
- const headers = await this.headers();
1797
- const token = (await this.options.credential()).accessToken;
1798
- const userId = decodeUserId(token);
1799
- const webId = generateWebId();
1800
- const modelInfo = TRAE_SOLO_REMOTE_MODELS.find((m) => m.name.toLowerCase() === model.toLowerCase()) ?? {
1801
- name: model,
1802
- displayName: model,
1803
- multimodal: false
1804
- };
1805
- const conversation = serializeTraeConversation(messages);
1806
- const body = {
1807
- mode: "code",
1808
- environment_id: "default",
1809
- env: "remote",
1810
- auto_create_project: false,
1811
- origin: "web",
1812
- initial_message: {
1813
- chat_session_id: "",
1814
- content: [],
1815
- query: JSON.stringify([{
1816
- type: "text",
1817
- data: { content: conversation }
1818
- }]),
1819
- model_name: modelInfo.name,
1820
- agent_type: "solo_agent_remote",
1821
- model_selection_strategy: "manual",
1822
- custom_model: {
1823
- name: modelInfo.name,
1824
- multimodal: modelInfo.multimodal,
1825
- is_default: false,
1826
- display_name: modelInfo.displayName,
1827
- config_name: modelInfo.name,
1828
- config_source: 1,
1829
- provider: "",
1830
- ak: "",
1831
- sk: "",
1832
- base_url: "",
1833
- auth_type: 0,
1834
- use_remote_service: true
1835
- },
1836
- common_params: buildCommonParams(userId, webId)
1837
- }
1838
- };
1839
- const createResponse = await this.fetchImpl(`${this.baseUrl}/chat_sessions`, {
1840
- method: "POST",
1841
- headers,
1842
- body: JSON.stringify(body),
1843
- signal: signal ?? AbortSignal.timeout(3e4)
1844
- });
1845
- const createJson = await createResponse.json();
1846
- if (!createResponse.ok || createJson.code !== 0 || !createJson.data?.chat_session_id) throw new Error(`SOLO remote session creation failed (http ${createResponse.status}): ${createJson.message ?? "unknown error"}`);
1847
- const sessionId = createJson.data.chat_session_id;
1848
- const start = Date.now();
1849
- while (Date.now() - start < this.timeoutMs) {
1850
- if (signal?.aborted) throw new Error("SOLO remote polling aborted");
1851
- await new Promise((resolve) => setTimeout(resolve, this.pollIntervalMs));
1852
- const messageResponse = await this.fetchImpl(`${this.baseUrl}/chat_sessions/${sessionId}/messages?page_size=50`, {
1853
- headers,
1854
- ...signal === void 0 ? {} : { signal }
1855
- });
1856
- if (!messageResponse.ok) continue;
1857
- const assistant = ((await messageResponse.json()).data?.items ?? []).find((item) => item.role === "assistant");
1858
- if (assistant && assistant.status !== "in_progress" && assistant.status !== "failed") return {
1859
- content: extractContent(assistant.content ?? ""),
1860
- sessionId
1861
- };
1862
- if (assistant?.status === "failed") throw new Error("SOLO remote assistant message failed");
1863
- }
1864
- throw new Error("SOLO remote polling timed out");
1865
- }
1866
1770
  async fetchModels(signal) {
1867
1771
  const headers = await this.headers();
1868
1772
  const response = await this.fetchImpl(`${this.baseUrl}/models?functions=solo_agent_remote,solo_work_remote`, {
@@ -1880,6 +1784,7 @@ var TraeSoloRemoteClient = class {
1880
1784
  seen.add(model.id);
1881
1785
  models.push(model);
1882
1786
  }
1787
+ if (models.length === 0) throw new Error("SOLO remote models response contained no models");
1883
1788
  return models;
1884
1789
  }
1885
1790
  };
@@ -2228,7 +2133,7 @@ function rawCapabilityDiagnostic(enabled, capability, checkedAtMs) {
2228
2133
  //#endregion
2229
2134
  //#region src/fallback-upstream.ts
2230
2135
  /**
2231
- * Raw Chat first, SOLO Remote second. Fallback is intentionally narrow:
2136
+ * Optional primary route first, native SOLO tool-call route second. Fallback is intentionally narrow:
2232
2137
  * only definitive pre-stream schema/route incompatibilities may retry the same
2233
2138
  * user request. Authentication, credit, rate, cancellation, transport/server
2234
2139
  * failures, and every successful Response are never replayed.
@@ -2320,9 +2225,16 @@ function parseTraeCachedModel(value) {
2320
2225
  ...typeof raw["model_type"] === "string" ? { modelType: raw["model_type"] } : {}
2321
2226
  };
2322
2227
  }
2323
- /** Read Trae's own current user's model map via sqlite3 without exposing secrets. */
2324
- async function readTraeCachedModel(functionName, modelName, userId) {
2325
- const database = join(homedir(), "Library", "Application Support", "Trae CN", "User", "globalStorage", "state.vscdb");
2228
+ /**
2229
+ * Read Trae's own current user's model map via sqlite3 without exposing
2230
+ * secrets. The sqlite3 command line is a macOS prerequisite; on Windows it is
2231
+ * typically absent, so the call fails and callers fall back gracefully.
2232
+ */
2233
+ async function readTraeCachedModel(functionName, modelName, userId, options = {}) {
2234
+ const platform = options.platform ?? process.platform;
2235
+ const home = options.home ?? homedir();
2236
+ const env = options.env ?? process.env;
2237
+ const database = platform === "win32" ? join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Trae CN", "User", "globalStorage", "state.vscdb") : join(home, "Library", "Application Support", "Trae CN", "User", "globalStorage", "state.vscdb");
2326
2238
  const key = `${userId}_AI.agent.model.model_list_map`;
2327
2239
  const sql = `select value from ItemTable where key=${JSON.stringify(key)} limit 1;`;
2328
2240
  const { stdout } = await execFileAsync("sqlite3", [database, sql], { maxBuffer: 8388608 });
@@ -2588,7 +2500,6 @@ async function traeWebUsage(deps) {
2588
2500
  ...model.input === void 0 ? {} : { input: [...model.input] }
2589
2501
  })),
2590
2502
  enabledModelIds: [...deps.enabledModelIds()],
2591
- enabled1mModelIds: [...deps.enabled1mModelIds()],
2592
2503
  ...deps.rawDiagnostic === void 0 ? {} : { rawChat: deps.rawDiagnostic() }
2593
2504
  };
2594
2505
  try {
@@ -2779,125 +2690,6 @@ function buildTraeFusionRawChatEnvelope(arg, config) {
2779
2690
  };
2780
2691
  }
2781
2692
  //#endregion
2782
- //#region src/solo-remote-bridge.ts
2783
- function classify(status) {
2784
- if (status === 401 || status === 403) return "authentication";
2785
- if (status === 402) return "hard_credit";
2786
- if (status === 429) return "soft_rate";
2787
- if (status === 404) return "not_found";
2788
- if (status >= 500) return "server";
2789
- return "client";
2790
- }
2791
- /**
2792
- * Bridges the SOLO remote polling-based API into the shim's stream interface.
2793
- * The remote API uses create-session + poll-messages rather than raw SSE,
2794
- * so this bridge converts the final result into a synthetic OpenAI SSE stream.
2795
- */
2796
- var TraeSoloRemoteBridge = class {
2797
- remote;
2798
- constructor(remote) {
2799
- this.remote = remote;
2800
- }
2801
- async chatStream(bodyJson, signal) {
2802
- let parsed;
2803
- try {
2804
- parsed = JSON.parse(bodyJson);
2805
- } catch {
2806
- return {
2807
- ok: false,
2808
- status: 400,
2809
- kind: "client",
2810
- message: "invalid JSON request"
2811
- };
2812
- }
2813
- if (!Array.isArray(parsed.messages) || parsed.messages.length === 0) return {
2814
- ok: false,
2815
- status: 400,
2816
- kind: "client",
2817
- message: "messages are required"
2818
- };
2819
- const messages = parsed.messages.flatMap((message) => {
2820
- if (typeof message.role !== "string") return [];
2821
- if (typeof message.content === "string") return [{
2822
- role: message.role,
2823
- content: message.content
2824
- }];
2825
- if (!Array.isArray(message.content)) return [];
2826
- const content = message.content.flatMap((part) => {
2827
- if (typeof part !== "object" || part === null) return [];
2828
- const item = part;
2829
- const text = typeof item.text === "string" ? item.text : typeof item.content === "string" ? item.content : void 0;
2830
- return text === void 0 ? [] : [text];
2831
- }).join("\n");
2832
- return content === "" ? [] : [{
2833
- role: message.role,
2834
- content
2835
- }];
2836
- });
2837
- if (messages.length === 0) return {
2838
- ok: false,
2839
- status: 400,
2840
- kind: "client",
2841
- message: "text messages are required"
2842
- };
2843
- const model = typeof parsed.model === "string" && parsed.model !== "" ? parsed.model : "DeepSeek-V4-Flash";
2844
- const upstreamModel = model.endsWith("@1m") ? model.slice(0, -3) : model;
2845
- try {
2846
- const chunks = buildOpenAISseChunks((await this.remote.chat(messages, upstreamModel, signal)).content, model);
2847
- const encoder = new TextEncoder();
2848
- const stream = new ReadableStream({ start(controller) {
2849
- for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
2850
- controller.close();
2851
- } });
2852
- return {
2853
- ok: true,
2854
- response: new Response(stream, {
2855
- status: 200,
2856
- headers: { "Content-Type": "text/event-stream" }
2857
- })
2858
- };
2859
- } catch (error) {
2860
- const message = error instanceof Error ? error.message : String(error);
2861
- const status = /timed out/i.test(message) ? 504 : /session creation failed/i.test(message) ? 502 : 502;
2862
- return {
2863
- ok: false,
2864
- status,
2865
- kind: classify(status),
2866
- message: message.slice(0, 400)
2867
- };
2868
- }
2869
- }
2870
- };
2871
- function buildOpenAISseChunks(content, model) {
2872
- const id = `chatcmpl-${randomUUID().replaceAll("-", "").slice(0, 24)}`;
2873
- const created = Math.floor(Date.now() / 1e3);
2874
- const chunks = [];
2875
- if (content !== "") chunks.push(`data: ${JSON.stringify({
2876
- id,
2877
- object: "chat.completion.chunk",
2878
- created,
2879
- model,
2880
- choices: [{
2881
- index: 0,
2882
- delta: { content },
2883
- finish_reason: null
2884
- }]
2885
- })}\n\n`);
2886
- chunks.push(`data: ${JSON.stringify({
2887
- id,
2888
- object: "chat.completion.chunk",
2889
- created,
2890
- model,
2891
- choices: [{
2892
- index: 0,
2893
- delta: {},
2894
- finish_reason: "stop"
2895
- }]
2896
- })}\n\n`);
2897
- chunks.push("data: [DONE]\n\n");
2898
- return chunks;
2899
- }
2900
- //#endregion
2901
2693
  //#region src/upstream.ts
2902
2694
  /**
2903
2695
  * Safe first-stage upstream. Real Trae traffic stays disabled until one
@@ -2915,7 +2707,7 @@ var UnconfiguredTraeUpstreamClient = class {
2915
2707
  };
2916
2708
  //#endregion
2917
2709
  //#region src/index.ts
2918
- const name = "llm-trae";
2710
+ const name = "dsh-connect-trae";
2919
2711
  const inject = ["llm"];
2920
2712
  const TRAE_SETTINGS_NS = settingsNamespace("trae");
2921
2713
  const modelConfig = z.object({
@@ -2937,18 +2729,26 @@ const Config = z.object({
2937
2729
  accountId: z.string().description("Selected local Trae account id (never a token)"),
2938
2730
  lastCatalog: z.array(modelConfig).description("Last refreshed Trae raw model directory shown by the plugin card"),
2939
2731
  enabledModelIds: z.array(z.string()).default([]).description("Trae model ids the user enabled"),
2940
- enabled1mModels: z.array(z.string()).default([]).description("Trae model ids whose 1M variants are enabled"),
2732
+ contextBudgets: z.dict(z.number().step(1).min(1)).default({}).description("Local DSH context budget per Trae model"),
2733
+ imageModelIds: z.array(z.string()).default([]).description("Trae model ids the user explicitly enabled for image input"),
2941
2734
  models: z.array(modelConfig).description("Legacy generated Trae model list")
2942
2735
  });
2943
2736
  function apply(ctx, config) {
2944
2737
  const catalog = new TraeCatalog();
2945
2738
  const enabledSet = (value) => new Set(value.enabledModelIds ?? []);
2946
- const enabled1mSet = (value) => new Set(value.enabled1mModels ?? []);
2947
- const configuredModels = (value) => {
2948
- if (value.lastCatalog?.length) return deriveCatalog(value.lastCatalog, enabledSet(value), enabled1mSet(value));
2949
- return value.models?.length ? value.models : FALLBACK_TRAE_MODELS;
2739
+ const imageSet = (value) => new Set(value.imageModelIds ?? []);
2740
+ const callableKeys = /* @__PURE__ */ new Set();
2741
+ const dropDeadModels = (rows) => {
2742
+ if (callableKeys.size === 0) return rows;
2743
+ return rows.filter((model) => callableKeys.has(model.id.trim().toLowerCase()) || callableKeys.has(model.name.trim().toLowerCase()));
2744
+ };
2745
+ const derive = (value, raw) => {
2746
+ const selectedImages = imageSet(value);
2747
+ const derived = deriveCatalog(applyImageSelection(sanitizeCatalog(dropDeadModels(raw)), selectedImages), enabledSet(value), value.contextBudgets ?? {});
2748
+ return derived.length > 0 ? derived : applyImageSelection(dropDeadModels(FALLBACK_TRAE_MODELS), selectedImages);
2950
2749
  };
2951
- const displayModels = (value) => value.lastCatalog?.length ? value.lastCatalog : value.models?.length ? value.models : FALLBACK_TRAE_MODELS;
2750
+ const configuredModels = (value) => value.lastCatalog?.length ? derive(value, value.lastCatalog) : value.models?.length ? derive(value, value.models) : applyImageSelection(dropDeadModels(FALLBACK_TRAE_MODELS), imageSet(value));
2751
+ const displayModels = (value) => value.lastCatalog?.length ? dropDeadModels(sanitizeCatalog(value.lastCatalog)) : value.models?.length ? dropDeadModels(sanitizeCatalog(value.models)) : dropDeadModels(FALLBACK_TRAE_MODELS);
2952
2752
  const store = new TraeCredentialStore({
2953
2753
  ...config.authFile === void 0 ? {} : { storagePath: config.authFile },
2954
2754
  edition: config.edition ?? "auto",
@@ -2966,10 +2766,14 @@ function apply(ctx, config) {
2966
2766
  const solo = new TraeSoloUpstreamClient({
2967
2767
  credential: () => store.resolve(),
2968
2768
  identity,
2969
- baseUrl: "https://trae-api-cn.mchost.guru"
2769
+ baseUrl: "https://trae-api-cn.mchost.guru",
2770
+ log: (message, detail) => ctx.logger.warn(message, detail)
2970
2771
  });
2971
- const remote = new TraeSoloRemoteClient({ credential: () => store.resolve() });
2972
- const upstream = new TraeSoloBridge(solo);
2772
+ const remoteCatalog = new TraeSoloRemoteCatalogClient({ credential: () => store.resolve() });
2773
+ const wireById = /* @__PURE__ */ new Map();
2774
+ const wireByName = /* @__PURE__ */ new Map();
2775
+ const wireResolver = (displayId) => wireById.get(displayId) ?? wireByName.get(displayId.trim().toLowerCase());
2776
+ const upstream = new TraeSoloBridge(solo, catalog, wireResolver);
2973
2777
  const delegating = new TraeDelegatingUpstreamClient(upstream);
2974
2778
  const shim = createTraeShim({
2975
2779
  catalog,
@@ -3009,41 +2813,32 @@ function apply(ctx, config) {
3009
2813
  ctx.logger.warn("dsh-connect-trae: Raw gateway unavailable; continuing with native SOLO tool-call channel", error);
3010
2814
  }
3011
2815
  })();
3012
- const selectPreferredGeneralAccount = async () => {
3013
- try {
3014
- const accounts = await store.accounts();
3015
- const scored = [];
3016
- for (const account of accounts) try {
3017
- store.selectAccount(account.id);
3018
- const credential = await store.resolve();
3019
- const snapshot = await new TraeUsageClient({ credential: async () => credential }).snapshot();
3020
- const general = Math.round(snapshot.packs.filter((pack) => pack.availableEndpoint === 0).reduce((sum, pack) => sum + Math.max(0, (pack.creditsLimit ?? 0) - (pack.consumedCredits ?? 0)), 0) * 1e4) / 1e4;
3021
- scored.push({
3022
- id: account.id,
3023
- general
3024
- });
3025
- } catch (error) {
3026
- ctx.logger.warn(`dsh-connect-trae: account ${account.id} unavailable for default selection`, error);
3027
- }
3028
- scored.sort((a, b) => b.general - a.general);
3029
- store.setPreferAccountIds(scored.filter((item) => item.general > 0).map((item) => item.id));
3030
- store.setSource(config.authFile, config.edition ?? "auto", config.accountId);
3031
- } catch (error) {
3032
- ctx.logger.warn("dsh-connect-trae: default account selection failed; continuing", error);
3033
- }
3034
- };
3035
2816
  const usageClient = new TraeUsageClient({ credential: () => store.resolve() });
3036
2817
  let current = () => config;
3037
2818
  let invalidateAdapter = () => {};
3038
2819
  const discoverModels = async (signal) => {
3039
- return discoveredCatalog(await remote.fetchModels(signal), /* @__PURE__ */ new Set());
2820
+ const [remote, wire] = await Promise.all([remoteCatalog.fetchModels(signal), solo.fetchModels(signal)]);
2821
+ const merged = mergeTraeModelSources(remote, wire);
2822
+ callableKeys.clear();
2823
+ for (const model of merged) {
2824
+ callableKeys.add(model.id.trim().toLowerCase());
2825
+ callableKeys.add(model.name.trim().toLowerCase());
2826
+ }
2827
+ wireById.clear();
2828
+ wireByName.clear();
2829
+ for (const model of merged) if (model.wireConfigName !== void 0) {
2830
+ wireById.set(model.id, model.wireConfigName);
2831
+ wireByName.set(model.name.trim().toLowerCase(), model.wireConfigName);
2832
+ }
2833
+ const next = applyImageSelection(merged, imageSet(current()));
2834
+ catalog.set(next);
2835
+ return merged;
3040
2836
  };
3041
2837
  ctx.inject(["webServer"], (webCtx) => registerTraeUsageRoute(webCtx, {
3042
2838
  store,
3043
2839
  client: usageClient,
3044
2840
  displayModels: () => displayModels(current()),
3045
2841
  enabledModelIds: () => current().enabledModelIds ?? [],
3046
- enabled1mModelIds: () => current().enabled1mModels ?? [],
3047
2842
  discoverModels,
3048
2843
  rawDiagnostic: () => rawDiagnostic()
3049
2844
  }));
@@ -3065,7 +2860,11 @@ function apply(ctx, config) {
3065
2860
  });
3066
2861
  shim.ready.then(async () => {
3067
2862
  if (stopped) return;
3068
- await selectPreferredGeneralAccount();
2863
+ try {
2864
+ await discoverModels();
2865
+ } catch (error) {
2866
+ ctx.logger.warn("dsh-connect-trae: wire-id resolution failed at startup; falling back to display ids", error);
2867
+ }
3069
2868
  catalog.set(configuredModels(current()));
3070
2869
  const trae = createTraeAdapter({
3071
2870
  shim,
@@ -3081,11 +2880,12 @@ function apply(ctx, config) {
3081
2880
  releaseAdapter = ctx.llm.registerAdapter([TRAE_PROVIDER], trae.adapter);
3082
2881
  ctx.llm.registerModelDiscovery(TRAE_SETTINGS_NS, async (request) => {
3083
2882
  if (request.provider !== "trae") return [];
3084
- return (await discoverModels(request.signal)).map((model) => ({
2883
+ return applyImageSelection(await discoverModels(request.signal), imageSet(current())).map((model) => ({
3085
2884
  id: model.id,
3086
2885
  name: model.name,
3087
2886
  ...model.contextWindow === void 0 ? {} : { contextWindow: model.contextWindow },
3088
- ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens }
2887
+ ...model.maxTokens === void 0 ? {} : { maxTokens: model.maxTokens },
2888
+ inputModalities: traeInputModalities(model)
3089
2889
  }));
3090
2890
  });
3091
2891
  releaseDirectory = ctx.llm.registerConfigurableProviders([{
@@ -3115,4 +2915,4 @@ function apply(ctx, config) {
3115
2915
  });
3116
2916
  }
3117
2917
  //#endregion
3118
- export { Config, FALLBACK_TRAE_MODELS, SseDecoder, TRAE_CN_AGENT_TASK_PATH, TRAE_CN_TITLE_PATH, TRAE_MODEL_DETAIL_FUNCTIONS, TRAE_MODEL_DETAIL_PATH, TRAE_PAY_BASE, TRAE_PROVIDER, TRAE_RAW_CHAT_V1_PATH, TRAE_RAW_CHAT_V2_PATH, TRAE_REASONING_EFFORTS, TRAE_SETTINGS_NS, TRAE_SOLO_CHAT_PATH, TRAE_SOLO_FUNCTION, TRAE_SOLO_MODELS_PATH, TRAE_SOLO_REMOTE_BASE, TRAE_SOLO_REMOTE_MODELS, TRAE_STREAM_IDLE_TIMEOUT_MS, TRAE_USAGE_PATH, TRAE_VERSION_CODE_FALLBACK, TraeCatalog, TraeCredentialStore, TraeDelegatingUpstreamClient, TraeFallbackUpstreamClient, TraeGatedUpstreamClient, TraeRawCapabilityController, TraeRawCapabilityState, TraeRawChatUpstreamClient, TraeSoloBridge, TraeSoloRemoteBridge, TraeSoloRemoteClient, TraeSoloUpstreamClient, TraeUsageClient, UnconfiguredTraeUpstreamClient, apply, applyReasoningEffort, bridgeTraeSoloStream, buildTraeAgentTaskBody, buildTraeCnHeaders, buildTraeFusionRawChatEnvelope, buildTraeModelDetailRequest, buildTraeRawChatDraft, buildTraeRawChatRuntimeConfig, classifyTraeRawChatFailure, createTraeAdapter, createTraeRawGateway, createTraeShim, decodeRawChatChunk, decodeTraeEvent, decryptTraeStorageValue, discoveredCatalog, hashTraeRawChatArg, identityHeaders, inject, name, normalizeTraeCredential, normalizeTraeVersionCode, parseObservedModelConfig, parseReasoningCapability, parseTraeAuthValue, parseTraeCachedModel, parseTraeModelExtraConfigLogLine, parseTraeRawChatBehaviorConfig, parseTraeRemoteModel, parseTraeStorageDocument, prepareSoloBody, probeTraeRawChatCapability, rawCapabilityDiagnostic, rawCapabilityFingerprint, readTraeCachedModel, readTraeIdentity, refreshTraeCredential, registerTraeUsageRoute, resolveTraeRawRuntime, traeEndpoint, traeOwnAuthPath, traeRawChatExtraInfo, traeStorageCandidates, traeWebUsage };
2918
+ export { Config, FALLBACK_TRAE_MODELS, SseDecoder, TRAE_CN_AGENT_TASK_PATH, TRAE_CN_TITLE_PATH, TRAE_MODEL_DETAIL_FUNCTIONS, TRAE_MODEL_DETAIL_PATH, TRAE_PAY_BASE, TRAE_PROVIDER, TRAE_RAW_CHAT_V1_PATH, TRAE_RAW_CHAT_V2_PATH, TRAE_REASONING_EFFORTS, TRAE_SETTINGS_NS, TRAE_SOLO_CHAT_PATH, TRAE_SOLO_FUNCTION, TRAE_SOLO_MODELS_PATH, TRAE_SOLO_REMOTE_BASE, TRAE_STREAM_IDLE_TIMEOUT_MS, TRAE_USAGE_PATH, TRAE_VERSION_CODE_FALLBACK, TraeCatalog, TraeCredentialStore, TraeDelegatingUpstreamClient, TraeFallbackUpstreamClient, TraeGatedUpstreamClient, TraeRawCapabilityController, TraeRawCapabilityState, TraeRawChatUpstreamClient, TraeSoloBridge, TraeSoloRemoteCatalogClient, TraeSoloUpstreamClient, TraeUsageClient, UnconfiguredTraeUpstreamClient, apply, applyContextBudgets, applyImageSelection, applyReasoningEffort, bridgeTraeSoloStream, buildTraeAgentTaskBody, buildTraeCnHeaders, buildTraeFusionRawChatEnvelope, buildTraeModelDetailRequest, buildTraeRawChatDraft, buildTraeRawChatRuntimeConfig, classifyTraeRawChatFailure, createTraeAdapter, createTraeRawGateway, createTraeShim, decodeRawChatChunk, decodeTraeEvent, decryptTraeStorageValue, deriveCatalog, discoveredCatalog, hashTraeRawChatArg, identityHeaders, inject, mergeTraeModelSources, name, normalizeTraeCredential, normalizeTraeVersionCode, parseObservedModelConfig, parseReasoningCapability, parseTraeAuthValue, parseTraeCachedModel, parseTraeModelExtraConfigLogLine, parseTraeRawChatBehaviorConfig, parseTraeRemoteModel, parseTraeStorageDocument, prepareSoloBody, probeTraeRawChatCapability, rawCapabilityDiagnostic, rawCapabilityFingerprint, readTraeCachedModel, readTraeIdentity, refreshTraeCredential, registerTraeUsageRoute, resolveTraeRawRuntime, sanitizeCatalog, traeEndpoint, traeInputModalities, traeOwnAuthPath, traeRawChatExtraInfo, traeStorageCandidates, traeWebUsage };