dsh-agent-sdk-bridge 1.0.1 → 1.1.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,16 +1,19 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, ToolCallId, fileHandleText, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, textOnlyImageText } from "@deepseek-ai/dsh-llm";
3
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
4
- import { homedir } from "node:os";
3
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
5
  import * as path from "node:path";
6
- import { dirname, join } from "node:path";
6
+ import { delimiter, dirname, join } from "node:path";
7
7
  import * as cnSdk from "@qodercn-ai/qodercn-agent-sdk";
8
8
  import { createSdkMcpServer, qodercliAuth } from "@qodercn-ai/qodercn-agent-sdk";
9
- import { randomBytes, randomUUID } from "node:crypto";
9
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
10
10
  import { z } from "zod";
11
11
  import { spawn } from "node:child_process";
12
- import { fileURLToPath } from "node:url";
12
+ import { createServer } from "node:http";
13
+ import { Readable, Writable } from "node:stream";
14
+ import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
13
15
  import { TextDecoder } from "node:util";
16
+ import { fileURLToPath } from "node:url";
14
17
  import { isVolatile } from "@deepseek-ai/cosmokit";
15
18
  import z$1 from "@deepseek-ai/schemastery";
16
19
  //#region src/brand.ts
@@ -78,11 +81,36 @@ const CODEBUDDY_BRAND = {
78
81
  setupScript: null,
79
82
  staticCatalog: false
80
83
  };
84
+ /**
85
+ * MiniMax Code, spoken over the Agent Client Protocol.
86
+ *
87
+ * `mcode acp` runs as a stdio ACP server. Unlike CodeBuddy, there is no SDK
88
+ * package to import: the plugin speaks the protocol directly and the CLI owns
89
+ * login, model selection and the upstream account. The login region is a
90
+ * config choice (`MAVIS_REGION` pins each process), not a brand.
91
+ */
92
+ const MINIMAX_BRAND = {
93
+ id: "minimax",
94
+ family: "minimax",
95
+ provider: "minimax-acp",
96
+ defaultDisplayName: "MiniMax Code",
97
+ enabledKey: "minimaxEnabled",
98
+ sdkPackage: "@agentclientprotocol/sdk",
99
+ cliPackages: [{
100
+ scope: "@minimax-ai",
101
+ name: "code"
102
+ }],
103
+ cliCommands: ["mcode"],
104
+ configDirName: ".minimax",
105
+ setupScript: null,
106
+ staticCatalog: false
107
+ };
81
108
  /** Every brand, in the order the settings pages list them. */
82
109
  const BRANDS = [
83
110
  CN_BRAND,
84
111
  GLOBAL_BRAND,
85
- CODEBUDDY_BRAND
112
+ CODEBUDDY_BRAND,
113
+ MINIMAX_BRAND
86
114
  ];
87
115
  /** Whether a value names a Qoder edition. */
88
116
  function isQoderBrand(value) {
@@ -90,7 +118,7 @@ function isQoderBrand(value) {
90
118
  }
91
119
  /** Whether a value names one of the provider brands. */
92
120
  function isBrandId(value) {
93
- return isQoderBrand(value) || value === "codebuddy";
121
+ return isQoderBrand(value) || value === "codebuddy" || value === "minimax";
94
122
  }
95
123
  /** Whether a value names a CodeBuddy login region. */
96
124
  function isCodeBuddyRegion(value) {
@@ -99,8 +127,19 @@ function isCodeBuddyRegion(value) {
99
127
  /** The profile for one brand. */
100
128
  function brandProfile(brand) {
101
129
  if (brand === "codebuddy") return CODEBUDDY_BRAND;
130
+ if (brand === "minimax") return MINIMAX_BRAND;
102
131
  return brand === "global" ? GLOBAL_BRAND : CN_BRAND;
103
132
  }
133
+ /**
134
+ * The region name the MiniMax CLI uses internally.
135
+ *
136
+ * The CLI calls the mainland site `cn` and the international one `en`; its
137
+ * login command accepts `global` and maps it to `en`. Processes are pinned
138
+ * with `MAVIS_REGION`, which also expects `cn`/`en`.
139
+ */
140
+ function minimaxCliRegion(region) {
141
+ return region === "cn" ? "cn" : "en";
142
+ }
104
143
  /** The SDK environment a CodeBuddy region logs into. */
105
144
  function codeBuddyEnvironment(region) {
106
145
  return region === "cn" ? "internal" : "external";
@@ -672,7 +711,7 @@ var QoderModelCatalog = class {
672
711
  }
673
712
  });
674
713
  try {
675
- return await withTimeout$1(q.getAvailableModels({ fetchStrategy: "live" }), readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS));
714
+ return await withTimeout$2(q.getAvailableModels({ fetchStrategy: "live" }), readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS));
676
715
  } finally {
677
716
  await q.close().catch(() => void 0);
678
717
  }
@@ -711,7 +750,7 @@ function priceFactorOf(entry) {
711
750
  async function* inertInput$2() {
712
751
  await new Promise(() => {});
713
752
  }
714
- function withTimeout$1(promise, ms) {
753
+ function withTimeout$2(promise, ms) {
715
754
  return new Promise((resolve, reject) => {
716
755
  const timer = setTimeout(() => {
717
756
  reject(/* @__PURE__ */ new Error(`qoder request timed out after ${ms}ms`));
@@ -1031,6 +1070,44 @@ function feedToText(feed) {
1031
1070
  if (typeof feed === "string") return feed;
1032
1071
  return feed.map((part) => part.type === "text" ? part.text : textOnlyImageText(part.attachment)).filter((text) => text.length > 0).join("\n\n");
1033
1072
  }
1073
+ /**
1074
+ * Split a feed into text and resolved images for providers with a vision API.
1075
+ *
1076
+ * The two non-Qoder adapters (CodeBuddy, MiniMax) speak their own content-block
1077
+ * shapes, so this returns a neutral list rather than a provider shape: text
1078
+ * parts pass through, an image uses its bytes when the host could read them,
1079
+ * and an unreadable image keeps a note naming what was dropped instead of
1080
+ * silently disappearing from the prompt.
1081
+ */
1082
+ function resolvedFeedParts(feed, images) {
1083
+ const parts = [];
1084
+ if (typeof feed === "string") {
1085
+ if (feed.length > 0) parts.push({
1086
+ type: "text",
1087
+ text: feed
1088
+ });
1089
+ return parts;
1090
+ }
1091
+ for (const part of feed) {
1092
+ if (part.type === "text") {
1093
+ if (part.text.length > 0) parts.push({
1094
+ type: "text",
1095
+ text: part.text
1096
+ });
1097
+ continue;
1098
+ }
1099
+ const resolved = images.get(String(part.attachment.attachmentId));
1100
+ parts.push(resolved === void 0 ? {
1101
+ type: "image-unreadable",
1102
+ attachment: part.attachment
1103
+ } : {
1104
+ type: "image",
1105
+ data: resolved.data,
1106
+ mediaType: resolved.mediaType
1107
+ });
1108
+ }
1109
+ return parts;
1110
+ }
1034
1111
  /** Literal characters in a feed; images contribute their pixels, not text. */
1035
1112
  function feedTextLength(feed) {
1036
1113
  if (typeof feed === "string") return feed.length;
@@ -1913,7 +1990,7 @@ var QoderSession = class {
1913
1990
  text: feed
1914
1991
  }] : [...feed];
1915
1992
  this.feedFallback = fallback !== void 0 && content.some((block) => block.type === "image") ? fallback : void 0;
1916
- this.turnInputChars += contentChars(content);
1993
+ this.turnInputChars += contentChars$1(content);
1917
1994
  this.channel.push({
1918
1995
  type: "user",
1919
1996
  message: {
@@ -2369,7 +2446,7 @@ function estimateImageTokens(width, height) {
2369
2446
  return Math.max(1, Math.ceil(width * height / 750));
2370
2447
  }
2371
2448
  /** Literal characters one channel content list contributes to the fallback estimate. */
2372
- function contentChars(content) {
2449
+ function contentChars$1(content) {
2373
2450
  return content.reduce((total, block) => total + (block.type === "text" ? block.text.length : 0), 0);
2374
2451
  }
2375
2452
  /** Safely stringify the SDK error payload for turn diagnostics. */
@@ -2638,8 +2715,8 @@ var QoderUsage = class {
2638
2715
  }
2639
2716
  });
2640
2717
  try {
2641
- const usage = await withTimeout$1(q.getUsageInfo(), timeoutMs);
2642
- const account = await withTimeout$1(q.accountInfo(), timeoutMs).catch(() => void 0);
2718
+ const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
2719
+ const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
2643
2720
  return {
2644
2721
  at,
2645
2722
  ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
@@ -2670,9 +2747,9 @@ var QoderUsage = class {
2670
2747
  * @module dsh-llm-qoder/adapter
2671
2748
  */
2672
2749
  /** Shared empty values, so an unset list or map allocates nothing per read. */
2673
- const NO_MODELS$1 = [];
2750
+ const NO_MODELS$2 = [];
2674
2751
  const NO_WINDOWS = {};
2675
- const NO_ALIASES$1 = {};
2752
+ const NO_ALIASES$2 = {};
2676
2753
  /** The primary provider route (the CN account's own models). */
2677
2754
  const QODER_PROVIDER = "qoder-cn";
2678
2755
  /** The international edition's route; a second adapter instance serves it. */
@@ -2723,7 +2800,7 @@ function cliContextWindow(live, declared) {
2723
2800
  if (available !== void 0 && available.includes(declared)) return declared;
2724
2801
  return live.defaultContextWindow ?? largestWindow(available) ?? live.maxInputTokens;
2725
2802
  }
2726
- function modelInfo$1(provider, entry) {
2803
+ function modelInfo$2(provider, entry) {
2727
2804
  return {
2728
2805
  provider,
2729
2806
  id: entry.id,
@@ -2816,7 +2893,7 @@ var QoderAdapter = class extends LlmAdapter {
2816
2893
  return readLive(this.options.modelContextWindows, NO_WINDOWS);
2817
2894
  }
2818
2895
  get disabledModels() {
2819
- const source = readLive(this.options.disabledModels, NO_MODELS$1);
2896
+ const source = readLive(this.options.disabledModels, NO_MODELS$2);
2820
2897
  const cached = this.disabledCache;
2821
2898
  if (cached !== void 0 && cached.source === source) return cached.set;
2822
2899
  const set = new Set(source);
@@ -2827,7 +2904,7 @@ var QoderAdapter = class extends LlmAdapter {
2827
2904
  return set;
2828
2905
  }
2829
2906
  get modelAliases() {
2830
- return readLive(this.options.modelAliases, NO_ALIASES$1);
2907
+ return readLive(this.options.modelAliases, NO_ALIASES$2);
2831
2908
  }
2832
2909
  get defaultReasoningEffort() {
2833
2910
  return readLiveOptional(this.options.defaultReasoningEffort);
@@ -2910,7 +2987,7 @@ var QoderAdapter = class extends LlmAdapter {
2910
2987
  return this.modelContextWindows;
2911
2988
  }
2912
2989
  async listModels(provider) {
2913
- return (await this.catalog.models()).filter((entry) => this.isVisible(entry.id)).map((entry) => modelInfo$1(provider, entry));
2990
+ return (await this.catalog.models()).filter((entry) => this.isVisible(entry.id)).map((entry) => modelInfo$2(provider, entry));
2914
2991
  }
2915
2992
  async resolveModel(provider, model, _signal) {
2916
2993
  const target = resolveQoderModelId(model, this.modelAliases);
@@ -2937,7 +3014,7 @@ var QoderAdapter = class extends LlmAdapter {
2937
3014
  name: model,
2938
3015
  inputModalities: ["text"]
2939
3016
  } : {
2940
- ...modelInfo$1(provider, configured),
3017
+ ...modelInfo$2(provider, configured),
2941
3018
  id: model
2942
3019
  },
2943
3020
  context: { contextWindow: this.windowOverride(target) ?? 2e5 },
@@ -3272,6 +3349,34 @@ var CodeBuddyStateStore = class {
3272
3349
  *
3273
3350
  * @module dsh-agent-sdk-bridge/codebuddy
3274
3351
  */
3352
+ /**
3353
+ * Literal characters in a channel payload; images contribute pixels, not text.
3354
+ *
3355
+ * The per-turn input estimate charges text only, matching how the Qoder path
3356
+ * counts a feed, so a picture cannot inflate the reported prompt size.
3357
+ */
3358
+ function contentChars(content) {
3359
+ return content.reduce((total, block) => total + (block.type === "text" ? block.text.length : 0), 0);
3360
+ }
3361
+ /**
3362
+ * Wrap one turn's content the way the SDK's `send()` expects it.
3363
+ *
3364
+ * A plain string keeps the historical shape; image turns are wrapped in a
3365
+ * `UserMessage`, because a bare `ContentBlock[]` is not accepted and dropping
3366
+ * the wrapper silently loses the picture.
3367
+ */
3368
+ function toCodeBuddyUserMessage(sessionId, content) {
3369
+ if (typeof content === "string") return content;
3370
+ return {
3371
+ type: "user",
3372
+ session_id: sessionId,
3373
+ message: {
3374
+ role: "user",
3375
+ content
3376
+ },
3377
+ parent_tool_use_id: null
3378
+ };
3379
+ }
3275
3380
  /** Default context capacity assumed for a CodeBuddy model that declares none. */
3276
3381
  const CODEBUDDY_DEFAULT_CONTEXT_WINDOW = 2e5;
3277
3382
  /** Default output cap when the catalog declares none. */
@@ -3414,13 +3519,13 @@ async function withSession(region, run, timeoutMs, options = {}) {
3414
3519
  persistSession: false
3415
3520
  });
3416
3521
  try {
3417
- await withTimeout(session.connect(), timeoutMs);
3418
- return await withTimeout(run(session), timeoutMs);
3522
+ await withTimeout$1(session.connect(), timeoutMs);
3523
+ return await withTimeout$1(run(session), timeoutMs);
3419
3524
  } finally {
3420
3525
  session.close();
3421
3526
  }
3422
3527
  }
3423
- function withTimeout(promise, ms) {
3528
+ function withTimeout$1(promise, ms) {
3424
3529
  return new Promise((resolve, reject) => {
3425
3530
  const timer = setTimeout(() => {
3426
3531
  reject(/* @__PURE__ */ new Error(`CodeBuddy request timed out after ${ms}ms`));
@@ -3621,8 +3726,8 @@ async function readAccount(region, timeoutMs) {
3621
3726
  }
3622
3727
  });
3623
3728
  try {
3624
- await withTimeout(q.connect(), timeoutMs);
3625
- return await withTimeout(q.accountInfo(), timeoutMs);
3729
+ await withTimeout$1(q.connect(), timeoutMs);
3730
+ return await withTimeout$1(q.accountInfo(), timeoutMs);
3626
3731
  } finally {
3627
3732
  await q.return().catch(() => void 0);
3628
3733
  }
@@ -3716,7 +3821,7 @@ function formatLocalTime(date) {
3716
3821
  async function readBearerToken(region) {
3717
3822
  const cached = tokenFor(region);
3718
3823
  if (cached !== void 0) return cached;
3719
- const result = await withTimeout((await loadCodeBuddySdk()).unstable_v2_authenticate({
3824
+ const result = await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_authenticate({
3720
3825
  environment: codeBuddyEnvironment(region),
3721
3826
  timeout: 3e3,
3722
3827
  onAuthUrl: () => {}
@@ -3846,7 +3951,7 @@ var CodeBuddyAuth = class {
3846
3951
  async logout(region) {
3847
3952
  let failure;
3848
3953
  try {
3849
- await withTimeout((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
3954
+ await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
3850
3955
  } catch (error) {
3851
3956
  failure = error instanceof Error ? error.message : String(error);
3852
3957
  }
@@ -3867,7 +3972,7 @@ var CodeBuddyAuth = class {
3867
3972
  const { region } = status;
3868
3973
  try {
3869
3974
  const sdk = await loadCodeBuddySdk();
3870
- await withTimeout(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
3975
+ await withTimeout$1(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
3871
3976
  if (!this.current(run)) return;
3872
3977
  bearerTokens.delete(region);
3873
3978
  const result = await sdk.unstable_v2_authenticate({
@@ -4008,7 +4113,7 @@ var CodeBuddySession = class {
4008
4113
  }
4009
4114
  this.pairing.beginHostRequest(delivered, freshUserTurn);
4010
4115
  }
4011
- /** Run one host turn; `feed` is new user text, or null for a tool continuation. */
4116
+ /** Run one host turn; `feed` is new user content, or null for a tool continuation. */
4012
4117
  async *stream(options, feed) {
4013
4118
  if (this.queue !== null) throw new Error(`CodeBuddy session ${this.sessionId} already has a turn in flight`);
4014
4119
  if (this.disposed) throw new Error(`CodeBuddy session ${this.sessionId} was disposed`);
@@ -4032,8 +4137,11 @@ var CodeBuddySession = class {
4032
4137
  try {
4033
4138
  await session.setModel(this.model);
4034
4139
  if (feed !== null && feed.length > 0) {
4035
- this.inputChars += feed.length;
4036
- await session.send(feed);
4140
+ const content = typeof feed === "string" ? feed : feed.filter((block) => block.type !== "text" || block.text.length > 0);
4141
+ if (content.length > 0) {
4142
+ this.inputChars += typeof content === "string" ? content.length : contentChars(content);
4143
+ await session.send(toCodeBuddyUserMessage(this.sessionId, content));
4144
+ }
4037
4145
  }
4038
4146
  this.consume(session);
4039
4147
  for await (const item of this.queue) {
@@ -4563,8 +4671,8 @@ async function codeBuddyColdStream(region, prompt, model, options) {
4563
4671
  */
4564
4672
  /** The CodeBuddy provider route. */
4565
4673
  const CODEBUDDY_PROVIDER = "codebuddy";
4566
- const NO_MODELS = [];
4567
- const NO_ALIASES = {};
4674
+ const NO_MODELS$1 = [];
4675
+ const NO_ALIASES$1 = {};
4568
4676
  /** Map a harness-side id onto a CodeBuddy model value. */
4569
4677
  function resolveCodeBuddyModelId(model, aliases = {}) {
4570
4678
  const configured = aliases[model] ?? aliases[model.toLowerCase()];
@@ -4572,7 +4680,7 @@ function resolveCodeBuddyModelId(model, aliases = {}) {
4572
4680
  const stripped = model.startsWith("codebuddy-") ? model.slice(10) : model;
4573
4681
  return stripped.length > 0 ? stripped : "default-model";
4574
4682
  }
4575
- function modelInfo(provider, model) {
4683
+ function modelInfo$1(provider, model) {
4576
4684
  return {
4577
4685
  provider,
4578
4686
  id: model.id,
@@ -4603,7 +4711,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4603
4711
  return readLive(this.options.region ?? (() => "global"), "global");
4604
4712
  }
4605
4713
  disabledFor(region) {
4606
- const source = this.options.disabledModels?.(region) ?? NO_MODELS;
4714
+ const source = this.options.disabledModels?.(region) ?? NO_MODELS$1;
4607
4715
  const key = source.join("\0");
4608
4716
  const cached = this.disabledCache.get(region);
4609
4717
  if (cached?.key === key) return cached.set;
@@ -4615,7 +4723,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4615
4723
  return set;
4616
4724
  }
4617
4725
  get aliases() {
4618
- return readLive(this.options.modelAliases, NO_ALIASES);
4726
+ return readLive(this.options.modelAliases, NO_ALIASES$1);
4619
4727
  }
4620
4728
  get displayName() {
4621
4729
  return readLive(this.options.displayName, "CodeBuddy");
@@ -4672,6 +4780,74 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4672
4780
  isModelDisabled(id, region = this.region) {
4673
4781
  return this.disabledFor(region).has(id);
4674
4782
  }
4783
+ /** Whether the resolved model accepts images (drives whether pixels are sent). */
4784
+ async modelVision(model) {
4785
+ const target = resolveCodeBuddyModelId(model, this.aliases);
4786
+ return (await this.catalog.models().catch(() => [])).find((entry) => entry.id === target)?.vision === true;
4787
+ }
4788
+ /**
4789
+ * Resolve a feed's images into base64 for the CLI's vision blocks.
4790
+ *
4791
+ * Only references the host can actually read become pixels; the rest keep
4792
+ * their handle text, so one unreadable attachment degrades that part of the
4793
+ * prompt instead of failing the whole turn.
4794
+ */
4795
+ async resolveFeedImages(feed, vision, signal) {
4796
+ const map = /* @__PURE__ */ new Map();
4797
+ const readImage = this.options.readImage;
4798
+ if (!vision || readImage === void 0) return map;
4799
+ for (const ref of feedImageRefs(feed)) {
4800
+ const key = String(ref.attachmentId);
4801
+ if (map.has(key)) continue;
4802
+ try {
4803
+ const image = await readImage(ref, signal);
4804
+ if (image !== void 0) map.set(key, {
4805
+ data: Buffer.from(image.bytes).toString("base64"),
4806
+ mediaType: image.mediaType
4807
+ });
4808
+ } catch {}
4809
+ }
4810
+ return map;
4811
+ }
4812
+ /**
4813
+ * Turn a feed into what one CLI turn receives.
4814
+ *
4815
+ * A text-only feed stays a plain string (the historical shape). A feed with
4816
+ * readable images becomes the SDK's `ContentBlock[]`, because that is the
4817
+ * only shape the CLI sends to the model as pixels.
4818
+ */
4819
+ async buildFeed(feed, vision, signal) {
4820
+ if (typeof feed === "string") return feed;
4821
+ if (!vision) return feedToText(feed);
4822
+ const parts = resolvedFeedParts(feed, await this.resolveFeedImages(feed, vision, signal));
4823
+ if (!parts.some((part) => part.type !== "text")) return parts.map((part) => part.type === "text" ? part.text : "").join("\n\n");
4824
+ const content = [];
4825
+ for (const part of parts) {
4826
+ if (part.type === "text") {
4827
+ content.push({
4828
+ type: "text",
4829
+ text: part.text
4830
+ });
4831
+ continue;
4832
+ }
4833
+ if (part.type === "image-unreadable") {
4834
+ content.push({
4835
+ type: "text",
4836
+ text: textOnlyImageText(part.attachment)
4837
+ });
4838
+ continue;
4839
+ }
4840
+ content.push({
4841
+ type: "image",
4842
+ source: {
4843
+ type: "base64",
4844
+ media_type: part.mediaType,
4845
+ data: part.data
4846
+ }
4847
+ });
4848
+ }
4849
+ return content;
4850
+ }
4675
4851
  contextWindowFor(id, region = this.region) {
4676
4852
  return this.options.modelContextWindows?.(region)[id];
4677
4853
  }
@@ -4680,7 +4856,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4680
4856
  if (!this.isSignedIn(region)) return [];
4681
4857
  const models = await this.catalog.models(region);
4682
4858
  const disabled = this.disabledFor(region);
4683
- return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo(provider, model));
4859
+ return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo$1(provider, model));
4684
4860
  }
4685
4861
  async resolveModel(provider, model) {
4686
4862
  const target = resolveCodeBuddyModelId(model, this.aliases);
@@ -4751,7 +4927,8 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4751
4927
  session.ensureTools(options.tools ?? []);
4752
4928
  session.fedMessages = options.messages;
4753
4929
  session.fedSystem = options.system;
4754
- const feed = plan.feed === null ? null : feedToText(plan.feed);
4930
+ const vision = await this.modelVision(options.model);
4931
+ const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, vision, options.signal);
4755
4932
  yield* session.stream(options, feed);
4756
4933
  }
4757
4934
  async *firstTurn(session, options, region, model, effort) {
@@ -4763,7 +4940,8 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4763
4940
  session.ensureTools(options.tools ?? []);
4764
4941
  session.fedMessages = options.messages;
4765
4942
  session.fedSystem = options.system;
4766
- const feed = feedToText(renderInitialFeed(void 0, options.messages));
4943
+ const vision = await this.modelVision(options.model);
4944
+ const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages), vision, options.signal);
4767
4945
  yield* session.stream(options, feed);
4768
4946
  }
4769
4947
  cwdOf(options) {
@@ -4774,60 +4952,112 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4774
4952
  }
4775
4953
  };
4776
4954
  //#endregion
4777
- //#region src/setup.ts
4955
+ //#region src/minimax-cli.ts
4778
4956
  /**
4779
- * Runs the bundled Windows helper that installs and signs into a Qoder CLI
4780
- * (one helper per edition: `qoderclicn` for CN, `qodercli` for international).
4781
- *
4782
- * The settings page cannot do this by itself: a browser has no way to start a
4783
- * local process, and the plugin's own process is the one that already talks to
4784
- * the CLI. So the page asks this module, and this module spawns
4785
- * {@link SCRIPT_NAME} — the same script a user can double-click — with one of
4786
- * two fixed flags, and buffers its output so the page can show progress while
4787
- * the browser sign-in is still open.
4957
+ * The MiniMax Code CLI (`mcode`): locating it and running its installer.
4788
4958
  *
4789
- * Nothing user-supplied reaches the command line: the mode is an allow-list of
4790
- * two keys mapped to two literal flags, and the script path comes from this
4791
- * package's own layout. The helper is idempotent, so a second press re-checks
4792
- * rather than reinstalling.
4959
+ * MiniMax ships `@minimax-ai/code` as a global npm package whose `mcode`
4960
+ * launcher is a Node shim. Its native SQLite dependency is installed by a
4961
+ * postinstall script, and npm 12 blocks install scripts unless they are named
4962
+ * with `--allow-scripts`; a plain `npm i -g` leaves a CLI that cannot start.
4963
+ * The installer below therefore passes the flags the package documents.
4793
4964
  *
4794
- * @module dsh-agent-sdk-bridge/setup
4965
+ * @module dsh-agent-sdk-bridge/minimax-cli
4795
4966
  */
4796
- /** File name of the CN helper, shipped under this package's `scripts/` directory. */
4797
- const SCRIPT_NAME = "setup-qoderclicn.bat";
4798
- /** The helper script for one edition. */
4799
- function scriptNameOf(brand) {
4800
- return brandProfile(brand).setupScript ?? "setup-qoderclicn.bat";
4967
+ /** The npm package and the version verified to work with native SQLite. */
4968
+ const PACKAGE = "@minimax-ai/code";
4969
+ const INSTALL_VERSION = "0.6.12";
4970
+ const INSTALL_FLAGS = [
4971
+ "--ignore-scripts=false",
4972
+ "--include=optional",
4973
+ "--allow-scripts=@minimax-ai/code,better-sqlite3",
4974
+ "--registry",
4975
+ "https://registry.npmjs.org/",
4976
+ "--foreground-scripts"
4977
+ ];
4978
+ function fromJsEntry(path) {
4979
+ return {
4980
+ command: process.execPath,
4981
+ args: [path],
4982
+ cliPath: path
4983
+ };
4801
4984
  }
4802
- /** The one command-line flag each mode maps to. Never a user-supplied string. */
4803
- const FLAGS = {
4804
- configure: "--gui",
4805
- login: "--login",
4806
- uninstall: "--uninstall"
4807
- };
4808
- /** Whether a value is one of the modes the page may request. */
4809
- function isSetupMode(value) {
4810
- return value === "configure" || value === "login" || value === "uninstall";
4985
+ function fromShim(shim) {
4986
+ if (shim.endsWith(".cmd") || shim.endsWith(".bat")) {
4987
+ try {
4988
+ const text = readFileSync(shim, "utf8");
4989
+ const match = /["']([^"']*node_modules[\\/]@minimax-ai[\\/]code[\\/]cli\.js)["']/.exec(text);
4990
+ if (match !== null && existsSync(match[1])) return fromJsEntry(match[1]);
4991
+ } catch {}
4992
+ const sibling = join(dirname(shim), "node_modules", "@minimax-ai", "code", "cli.js");
4993
+ if (existsSync(sibling)) return fromJsEntry(sibling);
4994
+ return {
4995
+ command: process.env.ComSpec ?? "cmd.exe",
4996
+ args: [
4997
+ "/d",
4998
+ "/c",
4999
+ shim
5000
+ ]
5001
+ };
5002
+ }
5003
+ if (shim.endsWith(".js") || shim.endsWith(".mjs")) return fromJsEntry(shim);
5004
+ try {
5005
+ const real = realpathSync(shim);
5006
+ if (real.endsWith(".js") || real.endsWith(".mjs")) return fromJsEntry(real);
5007
+ } catch {}
5008
+ return {
5009
+ command: shim,
5010
+ args: []
5011
+ };
4811
5012
  }
4812
- /** Cap on kept output, so a chatty `npm install` cannot grow without bound. */
4813
- const MAX_LINES = 400;
4814
- /** The latest run per edition: the two installers may run independently. */
4815
- const current = /* @__PURE__ */ new Map();
4816
5013
  /**
4817
- * Locate one edition's helper inside this package.
4818
- *
4819
- * The host half is bundled to `lib/index.js`, and tests import `src/*.ts`, so
4820
- * both layouts resolve to the same `scripts/` directory one level up.
5014
+ * Locate `mcode`.
4821
5015
  *
4822
- * @param brand - which edition's script to find.
5016
+ * `MCODE_CLI_PATH` wins (a cli.js path or an executable); otherwise the PATH
5017
+ * shims and the global npm prefixes are checked. The explicit cli.js lookup
5018
+ * matters on Windows, where spawning a `.cmd` for ACP would put cmd.exe between
5019
+ * the protocol streams.
4823
5020
  */
4824
- function setupScriptPath(brand = "cn") {
4825
- const here = path.dirname(fileURLToPath(import.meta.url));
4826
- const script = scriptNameOf(brand);
4827
- for (const candidate of [path.resolve(here, "..", "scripts", script), path.resolve(here, "scripts", script)]) if (existsSync(candidate)) return candidate;
5021
+ function resolveMinimaxCli() {
5022
+ const override = process.env.MCODE_CLI_PATH?.trim();
5023
+ if (override !== void 0 && override.length > 0 && existsSync(override)) return fromShim(override);
5024
+ const names = process.platform === "win32" ? [
5025
+ "mcode.cmd",
5026
+ "mcode.exe",
5027
+ "mcode"
5028
+ ] : ["mcode"];
5029
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
5030
+ if (directory.trim() === "") continue;
5031
+ for (const name of names) {
5032
+ const candidate = join(directory, name);
5033
+ if (existsSync(candidate)) return fromShim(candidate);
5034
+ }
5035
+ }
5036
+ const home = homedir();
5037
+ const candidates = process.platform === "win32" ? [
5038
+ join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "npm", "node_modules", PACKAGE, "cli.js"),
5039
+ join(process.env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "npm", "node_modules", PACKAGE, "cli.js"),
5040
+ join(process.env.ProgramFiles ?? "C:\\Program Files", "nodejs", "node_modules", PACKAGE, "cli.js")
5041
+ ] : [
5042
+ join(home, ".npm-global", "lib", "node_modules", PACKAGE, "cli.js"),
5043
+ join("/usr", "local", "lib", "node_modules", PACKAGE, "cli.js"),
5044
+ join("/usr", "lib", "node_modules", PACKAGE, "cli.js"),
5045
+ join(home, ".local", "lib", "node_modules", PACKAGE, "cli.js")
5046
+ ];
5047
+ for (const candidate of candidates) if (existsSync(candidate)) return fromJsEntry(candidate);
4828
5048
  }
4829
- /** Append decoded text to a run, splitting it into displayable lines. */
4830
- function absorb(run, chunk, done) {
5049
+ /** The spawn argument list for one CLI invocation. */
5050
+ function minimaxCliArgs(spec, args) {
5051
+ return [...spec.args, ...args];
5052
+ }
5053
+ /** Whether a value names an installer action. */
5054
+ function isMinimaxSetupMode(value) {
5055
+ return value === "install" || value === "uninstall";
5056
+ }
5057
+ /** Cap on kept output. */
5058
+ const MAX_LINES$1 = 400;
5059
+ let current$1;
5060
+ function absorb$1(run, chunk, done) {
4831
5061
  run.pending += run.decoder.decode(chunk, { stream: !done });
4832
5062
  const parts = run.pending.split(/\r\n|\r|\n/);
4833
5063
  run.pending = done ? "" : parts.pop() ?? "";
@@ -4836,43 +5066,48 @@ function absorb(run, chunk, done) {
4836
5066
  run.lines.push(part);
4837
5067
  }
4838
5068
  if (done && run.pending.trim() !== "") run.lines.push(run.pending.trim());
4839
- while (run.lines.length > MAX_LINES) {
5069
+ while (run.lines.length > MAX_LINES$1) {
4840
5070
  run.lines.shift();
4841
5071
  run.truncated = true;
4842
5072
  }
4843
5073
  }
4844
5074
  /**
4845
- * Start one edition's helper. Only one run per edition at a time; a finished
4846
- * one stays readable.
5075
+ * Start the npm installer or uninstaller.
4847
5076
  *
4848
- * @param brand - which edition to configure.
4849
- * @param mode - the fixed flag the page may ask for.
4850
- * @param onFinish - called once with the exit code.
5077
+ * The command is fixed: the mode is an allow-list and no user input reaches
5078
+ * argv. npm itself is run through cmd.exe on Windows because npm is a `.cmd`
5079
+ * shim and Node refuses to spawn it directly on recent versions.
4851
5080
  */
4852
- function startSetup(brand, mode, onFinish) {
4853
- const previous = current.get(brand);
4854
- if (previous !== void 0 && previous.finishedAt === void 0) return {
5081
+ function startMinimaxSetup(mode, onFinish) {
5082
+ if (current$1 !== void 0 && current$1.finishedAt === void 0) return {
4855
5083
  started: false,
4856
5084
  reason: "busy",
4857
- error: "已经有一次配置在跑了,请等它结束。"
5085
+ error: "已经有一次 MiniMax CLI 安装在跑了,请等它结束。"
4858
5086
  };
4859
- if (process.platform !== "win32") {
4860
- const command = brandProfile(brand).cliCommands[0];
4861
- return {
4862
- started: false,
4863
- reason: "unsupported",
4864
- error: `一键${mode === "uninstall" ? "卸载" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
4865
- };
4866
- }
4867
- const script = setupScriptPath(brand);
4868
- if (script === void 0) return {
5087
+ if (process.platform !== "win32" && mode === "install") return {
4869
5088
  started: false,
4870
- reason: "missing-script",
4871
- error: `插件包里没有 ${scriptNameOf(brand)},缺少 scripts/ 目录。`
5089
+ reason: "unsupported",
5090
+ error: "一键安装 MiniMax CLI 目前只支持 Windows;请在终端手动执行 npm install -g @minimax-ai/code。"
4872
5091
  };
5092
+ const npmArgs = mode === "install" ? [
5093
+ "install",
5094
+ "--global",
5095
+ `${PACKAGE}@${INSTALL_VERSION}`,
5096
+ ...INSTALL_FLAGS
5097
+ ] : [
5098
+ "uninstall",
5099
+ "--global",
5100
+ PACKAGE
5101
+ ];
5102
+ const command = process.platform === "win32" ? process.env.ComSpec ?? "cmd.exe" : "npm";
5103
+ const args = process.platform === "win32" ? [
5104
+ "/d",
5105
+ "/c",
5106
+ "npm",
5107
+ ...npmArgs
5108
+ ] : npmArgs;
4873
5109
  const run = {
4874
5110
  child: void 0,
4875
- brand,
4876
5111
  mode,
4877
5112
  startedAt: Date.now(),
4878
5113
  lines: [],
@@ -4880,12 +5115,7 @@ function startSetup(brand, mode, onFinish) {
4880
5115
  decoder: new TextDecoder("utf-8"),
4881
5116
  truncated: false
4882
5117
  };
4883
- const child = spawn(process.env.ComSpec ?? "cmd.exe", [
4884
- "/d",
4885
- "/c",
4886
- script,
4887
- FLAGS[mode]
4888
- ], {
5118
+ const child = spawn(command, args, {
4889
5119
  cwd: homedir(),
4890
5120
  windowsHide: true,
4891
5121
  stdio: [
@@ -4895,7 +5125,7 @@ function startSetup(brand, mode, onFinish) {
4895
5125
  ]
4896
5126
  });
4897
5127
  run.child = child;
4898
- current.set(brand, run);
5128
+ current$1 = run;
4899
5129
  const finish = (code) => {
4900
5130
  if (run.finishedAt !== void 0) return;
4901
5131
  run.finishedAt = Date.now();
@@ -4906,31 +5136,30 @@ function startSetup(brand, mode, onFinish) {
4906
5136
  run.lines.push(`收尾回调失败:${error instanceof Error ? error.message : String(error)}`);
4907
5137
  }
4908
5138
  };
4909
- child.stdout?.on("data", (chunk) => absorb(run, chunk, false));
4910
- child.stderr?.on("data", (chunk) => absorb(run, chunk, false));
5139
+ child.stdout?.on("data", (chunk) => absorb$1(run, chunk, false));
5140
+ child.stderr?.on("data", (chunk) => absorb$1(run, chunk, false));
4911
5141
  child.on("error", (error) => {
4912
- run.lines.push(`无法启动 ${scriptNameOf(brand)}:${error instanceof Error ? error.message : String(error)}`);
5142
+ run.lines.push(`无法启动 npm:${error instanceof Error ? error.message : String(error)}`);
4913
5143
  finish(null);
4914
5144
  });
4915
5145
  child.on("close", (code) => {
4916
- absorb(run, /* @__PURE__ */ new Uint8Array(), true);
5146
+ absorb$1(run, /* @__PURE__ */ new Uint8Array(), true);
4917
5147
  finish(code);
4918
5148
  });
4919
5149
  return { started: true };
4920
5150
  }
4921
- /**
4922
- * The latest run of one edition, with any not-yet-newlined tail included for
4923
- * live display.
4924
- *
4925
- * @param brand - which edition's run to report.
4926
- */
4927
- function readSetupStatus(brand = "cn") {
4928
- const run = current.get(brand);
4929
- if (run === void 0) return {
5151
+ /** The latest installer run, with any not-yet-newlined tail included. */
5152
+ function readMinimaxSetupStatus() {
5153
+ const spec = resolveMinimaxCli();
5154
+ const installed = spec !== void 0;
5155
+ if (current$1 === void 0) return {
4930
5156
  running: false,
4931
5157
  lines: [],
4932
- truncated: false
5158
+ truncated: false,
5159
+ installed,
5160
+ ...spec?.cliPath === void 0 ? {} : { cliPath: spec.cliPath }
4933
5161
  };
5162
+ const run = current$1;
4934
5163
  const lines = run.pending.trim() === "" ? run.lines : [...run.lines, run.pending.trim()];
4935
5164
  return {
4936
5165
  running: run.finishedAt === void 0,
@@ -4941,53 +5170,2772 @@ function readSetupStatus(brand = "cn") {
4941
5170
  code: run.code ?? null
4942
5171
  },
4943
5172
  lines,
4944
- truncated: run.truncated
5173
+ truncated: run.truncated,
5174
+ installed,
5175
+ ...spec?.cliPath === void 0 ? {} : { cliPath: spec.cliPath }
4945
5176
  };
4946
5177
  }
5178
+ /** Abandon a running installer. */
5179
+ function stopMinimaxSetup() {
5180
+ if (current$1 !== void 0 && current$1.finishedAt === void 0) current$1.child.kill();
5181
+ }
5182
+ /** A small object facade for callers that prefer a service shape. */
5183
+ var MinimaxCliSetup = class {
5184
+ start = startMinimaxSetup;
5185
+ status = readMinimaxSetupStatus;
5186
+ stop = stopMinimaxSetup;
5187
+ };
5188
+ //#endregion
5189
+ //#region src/minimax.ts
4947
5190
  /**
4948
- * Abandon the running helper, if any.
5191
+ * MiniMax Code over the Agent Client Protocol.
4949
5192
  *
4950
- * Called when the plugin is disposed. Killing `cmd.exe` does not reap the CLI it
4951
- * already launched, but the helper's own wait is bounded, so nothing hangs on
4952
- * the far end.
5193
+ * `mcode acp` is a stdio ACP server: the plugin starts one process per warm
5194
+ * host session, negotiates capabilities, creates one ACP session, and streams
5195
+ * `session/update` notifications back to the harness. Host tools are injected
5196
+ * as an HTTP MCP server (`mcpServers` in `session/new`), so a tool call the
5197
+ * model makes reaches this plugin and then the harness, exactly like the
5198
+ * CodeBuddy path.
5199
+ *
5200
+ * Two MiniMax behaviours shape this module:
5201
+ *
5202
+ * - ACP has no way to turn off the CLI's built-in tools. The model may call
5203
+ * `bash`/`write`/`read` directly, which would bypass the harness. The client
5204
+ * watches `tool_call` notifications and cancels the prompt before execution;
5205
+ * the turn is then retried with a correction. Host MCP tools are the only
5206
+ * calls allowed through.
5207
+ * - The CLI stores one auth state per region and selects it with
5208
+ * `MAVIS_REGION`; every process is pinned so the mainland and international
5209
+ * accounts can coexist.
5210
+ *
5211
+ * @module dsh-agent-sdk-bridge/minimax
4953
5212
  */
4954
- function stopSetup() {
4955
- for (const run of current.values()) if (run.finishedAt === void 0) run.child.kill();
5213
+ /** Default context capacity shown for a MiniMax model that declares none. */
5214
+ const MINIMAX_DEFAULT_CONTEXT_WINDOW = 512e3;
5215
+ /** Default output cap; the published MiniMax models allow 128k. */
5216
+ const MINIMAX_DEFAULT_MAX_TOKENS = 128e3;
5217
+ /** How long one model catalog stays fresh. */
5218
+ const MINIMAX_CACHE_TTL_MS = 3e5;
5219
+ /** Bound for one ACP control round trip. */
5220
+ const MINIMAX_FETCH_TIMEOUT_MS = 3e4;
5221
+ /** The MCP server name the model sees; its tools are `mcp__dsh-host__*`. */
5222
+ const MINIMAX_MCP_SERVER = "dsh-host";
5223
+ /** Context choices the hosted models publish. */
5224
+ const MINIMAX_CONTEXT_CHOICES = [MINIMAX_DEFAULT_CONTEXT_WINDOW, 1e6];
5225
+ /** How many native-tool corrections a turn may trigger before it fails. */
5226
+ const MAX_NATIVE_TOOL_RETRIES = 2;
5227
+ /** The per-user CLI state directory. */
5228
+ function minimaxDataDir() {
5229
+ const override = process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim();
5230
+ return override !== void 0 && override.length > 0 ? override : join(homedir(), ".minimax");
4956
5231
  }
4957
- //#endregion
4958
- //#region src/api.ts
4959
- /** Route prefix this plugin owns; the client resolves it relative to the page. */
4960
- const API_PREFIX = "/api/llm-qoder-cn";
4961
- /** Answer one request with JSON. */
4962
- function send(res, status, payload) {
4963
- const body = JSON.stringify(payload);
4964
- res.writeHead(status, {
4965
- "content-type": "application/json; charset=utf-8",
4966
- "cache-control": "no-store",
4967
- "content-length": Buffer.byteLength(body)
4968
- });
4969
- res.end(body);
5232
+ /** Path of one region's auth-state file. */
5233
+ function minimaxAuthStatePath(region) {
5234
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || "prod";
5235
+ return join(minimaxDataDir(), "auth", buildEnv, minimaxCliRegion(region), "mcode-public", "auth-state.json");
4970
5236
  }
4971
- /** Build model rows for a Qoder adapter. */
4972
- async function buildRows(adapter) {
4973
- return (await adapter.describeCatalog()).map((entry) => {
4974
- const override = adapter.contextWindowFor(entry.value);
4975
- const upstream = entry.defaultContextWindow ?? (entry.availableContextWindows !== void 0 && entry.availableContextWindows.length > 0 ? Math.max(...entry.availableContextWindows) : entry.maxInputTokens) ?? 2e5;
4976
- const choices = new Set(entry.availableContextWindows ?? []);
4977
- choices.add(upstream);
4978
- if (override !== void 0) choices.add(override);
4979
- const priceFactor = priceFactorOf(entry);
4980
- return {
4981
- id: entry.value,
4982
- name: entry.displayName.length > 0 ? entry.displayName : entry.value,
4983
- ...entry.description.length > 0 ? { description: entry.description } : {},
4984
- enabled: !adapter.isModelDisabled(entry.value),
4985
- vision: entry.isVl === true,
4986
- contextWindow: override ?? upstream,
4987
- contextWindows: [...choices].sort((a, b) => a - b),
4988
- defaultContextWindow: upstream,
4989
- ...override === void 0 ? {} : { override },
4990
- ...priceFactor === void 0 ? {} : { priceFactor },
5237
+ /** Path of the credential file the CLI writes its OAuth token to. */
5238
+ function minimaxAuthRecordPath(region) {
5239
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || "prod";
5240
+ return join(minimaxDataDir(), "auth", buildEnv, minimaxCliRegion(region), "mcode-public", "auth.json");
5241
+ }
5242
+ /** The CLI command name, for error text. */
5243
+ function minimaxCliCommand() {
5244
+ return "mcode";
5245
+ }
5246
+ /** The host-side MCP namespace the CLI exposes for the injected server. */
5247
+ const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, "_")}__`];
5248
+ /** Whether a CLI tool name belongs to this plugin's MCP server. */
5249
+ function isHostMcpTool(name) {
5250
+ return HOST_TOOL_PREFIXES.some((prefix) => name.startsWith(prefix));
5251
+ }
5252
+ /** The host-side name of an MCP tool, without the namespace. */
5253
+ function hostMcpToolName(name) {
5254
+ for (const prefix of HOST_TOOL_PREFIXES) if (name.startsWith(prefix)) return name.slice(prefix.length);
5255
+ return name;
5256
+ }
5257
+ /** Thinking-effort values an ACP config option advertises, minus `default`. */
5258
+ function effortValues(options) {
5259
+ if (!Array.isArray(options)) return [];
5260
+ return options.map((entry) => typeof entry?.value === "string" ? entry.value : "").filter((value) => value.length > 0 && value !== "default");
5261
+ }
5262
+ /** Build one row from a model option entry and the efforts that model accepts. */
5263
+ function modelRow(entry, efforts) {
5264
+ if (typeof entry?.value !== "string" || entry.value.length === 0) return void 0;
5265
+ return {
5266
+ id: entry.value,
5267
+ name: typeof entry.name === "string" && entry.name.length > 0 ? entry.name : entry.value,
5268
+ ...typeof entry.description === "string" && entry.description.length > 0 ? { description: entry.description } : {},
5269
+ contextWindows: [...MINIMAX_CONTEXT_CHOICES],
5270
+ defaultContextWindow: MINIMAX_DEFAULT_CONTEXT_WINDOW,
5271
+ vision: true,
5272
+ reasoning: efforts.length > 0,
5273
+ reasoningEfforts: [...efforts]
5274
+ };
5275
+ }
5276
+ /** The model config option's values as rows. */
5277
+ function minimaxModelsFromConfigOptions(options) {
5278
+ if (!Array.isArray(options)) return [];
5279
+ const modelOption = options.find((option) => option?.category === "model" || option?.id === "model");
5280
+ const efforts = effortValues(options.find((option) => option?.id === "thinkingEffort" || option?.category === "thought_level")?.options);
5281
+ if (!Array.isArray(modelOption?.options)) return [];
5282
+ const seen = /* @__PURE__ */ new Set();
5283
+ const models = [];
5284
+ for (const entry of modelOption.options) {
5285
+ if (typeof entry?.value !== "string" || entry.value.length === 0 || seen.has(entry.value)) continue;
5286
+ seen.add(entry.value);
5287
+ const row = modelRow(entry, efforts);
5288
+ if (row !== void 0) models.push(row);
5289
+ }
5290
+ return models;
5291
+ }
5292
+ /**
5293
+ * Read one region's stored auth state, without spawning anything.
5294
+ *
5295
+ * The file records its own region; a copy left over from another build or a
5296
+ * CLI that rotates its layout must not be read as this region's login.
5297
+ */
5298
+ function readAuthState(region) {
5299
+ try {
5300
+ const parsed = JSON.parse(readFileSync(minimaxAuthStatePath(region), "utf8"));
5301
+ if (typeof parsed.region === "string" && parsed.region !== minimaxCliRegion(region)) return void 0;
5302
+ return {
5303
+ ...typeof parsed.status === "string" ? { status: parsed.status } : {},
5304
+ ...typeof parsed.expiresAtMs === "number" ? { expiresAtMs: parsed.expiresAtMs } : {}
5305
+ };
5306
+ } catch {
5307
+ return;
5308
+ }
5309
+ }
5310
+ /** Whether the region has a stored login. */
5311
+ function minimaxSignedIn(region) {
5312
+ return readAuthState(region)?.status === "authenticated";
5313
+ }
5314
+ /** Signed account gateway (the CLI's `agent` host). */
5315
+ const MINIMAX_ACCOUNT_HOSTS = {
5316
+ cn: "https://agent.minimaxi.com",
5317
+ global: "https://agent.minimax.io"
5318
+ };
5319
+ /** Host serving the coding-plan quota. */
5320
+ const MINIMAX_QUOTA_HOSTS = {
5321
+ cn: "https://www.minimaxi.com",
5322
+ global: "https://platform.minimax.io"
5323
+ };
5324
+ /** Salt the CLI signs account requests with. */
5325
+ const MINIMAX_ACCOUNT_SALT = "I*7Cf%WZ#S&%1RlZJ&C2";
5326
+ /** Bound for one account/quota read. */
5327
+ const MINIMAX_USAGE_TIMEOUT_MS = 15e3;
5328
+ /** How long one quota reading stays fresh. */
5329
+ const MINIMAX_USAGE_CACHE_TTL_MS = 6e4;
5330
+ /** Bound for one region-reachability probe. */
5331
+ const MINIMAX_REGION_PROBE_TIMEOUT_MS = 5e3;
5332
+ /** How long one reachability verdict stays fresh. */
5333
+ const MINIMAX_REGION_ACCESS_TTL_MS = 3e4;
5334
+ /** Domains the two sites serve their API and console from. */
5335
+ const MINIMAX_INTL_DOMAIN = "minimax.io";
5336
+ const MINIMAX_CN_DOMAIN = "minimaxi.com";
5337
+ function hostMatches(hostname, domain) {
5338
+ return hostname === domain || hostname.endsWith(`.${domain}`);
5339
+ }
5340
+ /**
5341
+ * Whether a URL points at the other site.
5342
+ *
5343
+ * MiniMax's edge answers a request from the wrong side of the border with a
5344
+ * 307 to the other site (`.io` -> `.minimaxi.com` and the reverse). The two
5345
+ * are different origins, so a redirect also drops the Authorization header;
5346
+ * that is why the CLI reports `401 token is required` instead of an
5347
+ * actionable error, and why a stale token is not the real cause.
5348
+ */
5349
+ function minimaxHostBelongsToOtherRegion(region, target) {
5350
+ let hostname;
5351
+ try {
5352
+ hostname = typeof target === "string" ? new URL(target).hostname : target.hostname;
5353
+ } catch {
5354
+ return false;
5355
+ }
5356
+ return region === "global" ? hostMatches(hostname, MINIMAX_CN_DOMAIN) : hostMatches(hostname, MINIMAX_INTL_DOMAIN);
5357
+ }
5358
+ /** The sentence the card and the chat surface show for a refused region. */
5359
+ function minimaxRegionBlockMessage(region) {
5360
+ return region === "global" ? "本机 IP 不在 MiniMax 国际站的服务区域,国际站已拒绝连接(请求被重定向到国内站)。请切换到国内站,或更换网络后重试。" : "本机 IP 不在 MiniMax 国内站的服务区域,国内站已拒绝连接(请求被重定向到国际站)。请切换到国际站,或更换网络后重试。";
5361
+ }
5362
+ /** A region whose hosts refused this machine's network. */
5363
+ var MinimaxRegionBlockedError = class extends Error {
5364
+ region;
5365
+ constructor(region) {
5366
+ super(minimaxRegionBlockMessage(region));
5367
+ this.region = region;
5368
+ this.name = "MinimaxRegionBlockedError";
5369
+ }
5370
+ };
5371
+ const regionAccessCache = /* @__PURE__ */ new Map();
5372
+ /**
5373
+ * Probes already on the wire.
5374
+ *
5375
+ * A region switch asks for the quota and the catalog at the same time, and
5376
+ * both need the same verdict; sharing the request keeps them from disagreeing
5377
+ * and spares the remote host a duplicate round trip.
5378
+ */
5379
+ const regionAccessInflight = /* @__PURE__ */ new Map();
5380
+ /** Forget a cached reachability verdict. */
5381
+ function invalidateMinimaxRegionAccess(region) {
5382
+ if (region === void 0) regionAccessCache.clear();
5383
+ else regionAccessCache.delete(region);
5384
+ }
5385
+ function rememberRegionAccess(region, blocked) {
5386
+ regionAccessCache.set(region, {
5387
+ at: Date.now(),
5388
+ blocked
5389
+ });
5390
+ }
5391
+ /** The last verdict, for synchronous rendering under the card. */
5392
+ function minimaxRegionBlockedCached(region) {
5393
+ const cached = regionAccessCache.get(region);
5394
+ return cached?.blocked === true && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS;
5395
+ }
5396
+ /**
5397
+ * Probe the region's account host for a cross-region redirect.
5398
+ *
5399
+ * Only a redirect to the other site's domain counts as a block. A timeout or
5400
+ * DNS failure leaves the previous verdict alone, so callers report the real
5401
+ * network error instead of blaming the IP.
5402
+ */
5403
+ async function minimaxRegionBlocked(region, options = {}) {
5404
+ const cached = regionAccessCache.get(region);
5405
+ if (options.fresh !== true && cached !== void 0 && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS) return cached.blocked;
5406
+ let pending = regionAccessInflight.get(region);
5407
+ if (pending === void 0) {
5408
+ pending = probeRegionAccess(region, options).finally(() => {
5409
+ regionAccessInflight.delete(region);
5410
+ });
5411
+ regionAccessInflight.set(region, pending);
5412
+ }
5413
+ return await pending;
5414
+ }
5415
+ async function probeRegionAccess(region, options) {
5416
+ const cached = regionAccessCache.get(region);
5417
+ const fetchImpl = options.fetchImpl ?? fetch;
5418
+ const timeout = AbortSignal.timeout(MINIMAX_REGION_PROBE_TIMEOUT_MS);
5419
+ const signal = options.signal === void 0 ? timeout : AbortSignal.any([options.signal, timeout]);
5420
+ try {
5421
+ const response = await fetchImpl(`${MINIMAX_ACCOUNT_HOSTS[region]}/`, {
5422
+ redirect: "manual",
5423
+ signal,
5424
+ headers: { Accept: "text/html,application/json" }
5425
+ });
5426
+ const location = response.headers.get("location");
5427
+ const blocked = response.status >= 300 && response.status < 400 && location !== null && minimaxHostBelongsToOtherRegion(region, location);
5428
+ rememberRegionAccess(region, blocked);
5429
+ return blocked;
5430
+ } catch {
5431
+ return cached?.blocked === true;
5432
+ }
5433
+ }
5434
+ /** Whether one response is the edge redirecting this machine to the other site. */
5435
+ function redirectTargetsOtherRegion(region, requestUrl, response) {
5436
+ if (response.status < 300 || response.status >= 400) return false;
5437
+ const location = response.headers.get("location");
5438
+ if (location === null) return false;
5439
+ try {
5440
+ return minimaxHostBelongsToOtherRegion(region, new URL(location, requestUrl));
5441
+ } catch {
5442
+ return false;
5443
+ }
5444
+ }
5445
+ function asRecord(value) {
5446
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5447
+ }
5448
+ function asNumber(value) {
5449
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
5450
+ if (typeof value === "string" && value.trim() !== "") {
5451
+ const parsed = Number(value);
5452
+ return Number.isFinite(parsed) ? parsed : void 0;
5453
+ }
5454
+ }
5455
+ function asString(value) {
5456
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5457
+ }
5458
+ /** Read the OAuth access token the CLI stored for one region. */
5459
+ function readStoredToken(region) {
5460
+ try {
5461
+ const parsed = JSON.parse(readFileSync(minimaxAuthRecordPath(region), "utf8"));
5462
+ for (const record of Object.values(parsed.records ?? {})) {
5463
+ const token = record?.accessToken;
5464
+ if (typeof token === "string" && token.trim().length > 0) return token.trim();
5465
+ }
5466
+ } catch {}
5467
+ }
5468
+ function minimaxMd5(value) {
5469
+ return createHash("md5").update(value).digest("hex");
5470
+ }
5471
+ /** Build one signed-gateway URL exactly as the CLI does. */
5472
+ function minimaxAccountUrl(region, path, nowMs, realUserId) {
5473
+ const url = new URL(path, MINIMAX_ACCOUNT_HOSTS[region]);
5474
+ const lang = region === "cn" ? "zh" : "en";
5475
+ url.search = new URLSearchParams({
5476
+ device_platform: "mcode",
5477
+ biz_id: "3",
5478
+ app_id: "3001",
5479
+ version_code: "22201",
5480
+ unix: String(nowMs),
5481
+ timezone_offset: String((/* @__PURE__ */ new Date()).getTimezoneOffset() * -60),
5482
+ sys_language: lang,
5483
+ lang,
5484
+ device_id: "0",
5485
+ os_name: process.platform,
5486
+ browser_name: "mcode",
5487
+ user_id: realUserId?.trim() || "0",
5488
+ client: "mcode"
5489
+ }).toString();
5490
+ return url;
5491
+ }
5492
+ /** One request to the signed gateway, with the CLI's signature headers. */
5493
+ async function minimaxAccountCall(region, path, call) {
5494
+ const now = Date.now();
5495
+ const url = minimaxAccountUrl(region, path, now, call.realUserId);
5496
+ const target = `${url.pathname}${url.search}`;
5497
+ const body = call.body === void 0 ? "" : JSON.stringify(call.body);
5498
+ const seconds = Math.floor(now / 1e3);
5499
+ const response = await call.fetchImpl(url, {
5500
+ method: call.method ?? "GET",
5501
+ redirect: "manual",
5502
+ headers: {
5503
+ Accept: "application/json",
5504
+ "Content-Type": "application/json",
5505
+ "User-Agent": "MiniMaxCode",
5506
+ Authorization: `Bearer ${call.token}`,
5507
+ yy: minimaxMd5(`${encodeURIComponent(target)}_${body}${minimaxMd5(String(now))}ooui`),
5508
+ "x-timestamp": String(seconds),
5509
+ "x-signature": minimaxMd5(`${seconds}${MINIMAX_ACCOUNT_SALT}${body}`)
5510
+ },
5511
+ ...body === "" ? {} : { body },
5512
+ ...call.signal === void 0 ? {} : { signal: call.signal }
5513
+ });
5514
+ if (redirectTargetsOtherRegion(region, url, response)) {
5515
+ rememberRegionAccess(region, true);
5516
+ throw new MinimaxRegionBlockedError(region);
5517
+ }
5518
+ if (response.status >= 300 && response.status < 400) throw new Error(`MiniMax 账号接口返回了意外的重定向(HTTP ${response.status})。`);
5519
+ if (!response.ok) {
5520
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) throw new MinimaxRegionBlockedError(region);
5521
+ throw new Error(response.status === 401 || response.status === 403 ? "MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。" : `MiniMax 账号接口返回 HTTP ${response.status}。`);
5522
+ }
5523
+ const payload = asRecord(await response.json());
5524
+ if (payload === void 0) throw new Error("MiniMax 账号接口返回了无法解析的响应。");
5525
+ const statusInfo = asRecord(payload.statusInfo);
5526
+ const statusCode = asNumber(statusInfo?.code);
5527
+ if (statusCode !== void 0 && statusCode !== 0) throw new Error(asString(statusInfo?.message) ?? `MiniMax 账号接口错误 ${statusCode}。`);
5528
+ const baseResp = asRecord(payload.base_resp);
5529
+ const baseCode = asNumber(baseResp?.status_code);
5530
+ if (baseCode !== void 0 && baseCode !== 0) throw new Error(asString(baseResp?.status_msg) ?? `MiniMax 账号接口错误 ${baseCode}。`);
5531
+ return payload;
5532
+ }
5533
+ /**
5534
+ * Literal characters in a prompt payload; images contribute pixels, not text.
5535
+ *
5536
+ * The per-turn input estimate must charge text only, exactly as the Qoder path
5537
+ * counts a feed, so sending a picture cannot inflate the reported prompt size.
5538
+ */
5539
+ function feedTextLengthOf(prompt) {
5540
+ if (prompt === null) return 0;
5541
+ if (typeof prompt === "string") return prompt.length;
5542
+ return prompt.reduce((total, block) => total + (block.type === "text" ? block.text.length : 0), 0);
5543
+ }
5544
+ /** One window's numbers, named the way the coding-plan endpoint reports them. */
5545
+ function quotaWindow(bucket, kind) {
5546
+ const prefix = kind === "interval" ? "current_interval" : "current_weekly";
5547
+ const unlimited = asNumber(bucket[`${prefix}_status`]) === 3;
5548
+ const percent = asNumber(bucket[`${prefix}_remaining_percent`]);
5549
+ const total = asNumber(bucket[`${prefix}_total_count`]);
5550
+ const used = asNumber(bucket[`${prefix}_usage_count`]);
5551
+ const remaining = percent ?? (total !== void 0 && total > 0 && used !== void 0 ? used / total * 100 : void 0);
5552
+ const resetAt = asNumber(bucket[kind === "interval" ? "end_time" : "weekly_end_time"]);
5553
+ if (remaining === void 0 && !unlimited && (resetAt === void 0 || resetAt <= 0)) return void 0;
5554
+ return {
5555
+ ...remaining === void 0 || unlimited ? {} : { remainingPercent: Math.round(Math.min(100, Math.max(0, remaining))) },
5556
+ ...resetAt !== void 0 && resetAt > 0 ? { resetAt } : {},
5557
+ unlimited,
5558
+ ...kind === "interval" && used !== void 0 ? { remainingCount: Math.max(0, used) } : {},
5559
+ ...kind === "interval" && total !== void 0 ? { totalCount: Math.max(0, total) } : {}
5560
+ };
5561
+ }
5562
+ /** Turn one `model_remains` bucket into its 5-hour and weekly rows. */
5563
+ function windowRows(id, label, bucket) {
5564
+ const rows = [];
5565
+ const interval = quotaWindow(bucket, "interval");
5566
+ if (interval !== void 0) rows.push({
5567
+ id: `${id}:5h`,
5568
+ label: `${label} · 5 小时`,
5569
+ ...interval
5570
+ });
5571
+ const weekly = quotaWindow(bucket, "weekly");
5572
+ if (weekly !== void 0) rows.push({
5573
+ id: `${id}:7d`,
5574
+ label: `${label} · 本周`,
5575
+ ...weekly
5576
+ });
5577
+ return rows;
5578
+ }
5579
+ /** Parse `/v1/api/openplatform/coding_plan/remains`. */
5580
+ function parseMinimaxRemains(payload) {
5581
+ if (payload === void 0) return [];
5582
+ const code = asNumber(asRecord(payload.base_resp)?.status_code);
5583
+ if (code !== void 0 && code !== 0) return [];
5584
+ const buckets = Array.isArray(payload.model_remains) ? payload.model_remains.map(asRecord).filter((bucket) => bucket !== void 0) : [];
5585
+ const rows = [];
5586
+ const general = buckets[0];
5587
+ if (general !== void 0) rows.push(...windowRows("general", "通用", general));
5588
+ const video = buckets.find((bucket) => {
5589
+ const name = asString(bucket.model_name) ?? "";
5590
+ return /video/i.test(name) && (asNumber(bucket.current_interval_total_count) ?? 0) > 0;
5591
+ });
5592
+ if (video !== void 0) rows.push(...windowRows("video", "视频", video));
5593
+ return rows;
5594
+ }
5595
+ /**
5596
+ * Build a snapshot from the three account documents.
5597
+ *
5598
+ * Split out from the network path so the mapping is testable without a live
5599
+ * account: the membership record is the source of the plan and credit
5600
+ * balance, `remains` only exists for token-plan subscribers.
5601
+ */
5602
+ function minimaxUsageFromParts(parts) {
5603
+ const userInfo = parts.userInfo ?? {};
5604
+ const membership = parts.membership ?? {};
5605
+ const personal = parts.workspaces?.find((workspace) => asNumber(workspace.workspace_type) === 0) ?? parts.workspaces?.[0];
5606
+ const name = asString(userInfo.name);
5607
+ const email = asString(userInfo.email);
5608
+ const avatar = asString(userInfo.avatar);
5609
+ const userId = asString(userInfo.userID);
5610
+ const account = name === void 0 && email === void 0 && avatar === void 0 && userId === void 0 ? void 0 : {
5611
+ ...name === void 0 ? {} : { name },
5612
+ ...email === void 0 ? {} : { email },
5613
+ ...avatar === void 0 ? {} : { avatar },
5614
+ ...userId === void 0 ? {} : { userId }
5615
+ };
5616
+ const summary = asRecord(membership.op_credit_summary) ?? asRecord(personal?.op_credit_summary);
5617
+ const remaining = asNumber(summary?.total_remaining_amount) ?? asNumber(personal?.opcredit_balance) ?? asNumber(membership.opcredit_balance);
5618
+ const purchased = asNumber(summary?.purchased_remaining_amount);
5619
+ const free = asNumber(summary?.free_remaining_amount);
5620
+ const credits = remaining === void 0 ? void 0 : {
5621
+ remaining,
5622
+ ...purchased === void 0 ? {} : { purchasedRemaining: purchased },
5623
+ ...free === void 0 ? {} : { freeRemaining: free }
5624
+ };
5625
+ const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true;
5626
+ const kind = hasTokenPlan ? "token-plan" : credits !== void 0 && credits.remaining > 0 ? "credits" : "free";
5627
+ const planName = asString(membership.plan_name) ?? asString(personal?.plan_name);
5628
+ const tier = asString(membership.token_plan_tier) ?? asString(personal?.token_plan_tier);
5629
+ const expiresRaw = asNumber(membership.token_plan_expires_at) ?? asNumber(personal?.token_plan_expires_at) ?? asNumber(membership.expires_at);
5630
+ const expiresAt = expiresRaw !== void 0 && expiresRaw > 0 ? expiresRaw : void 0;
5631
+ const subscriptionType = asString(membership.subscription_type);
5632
+ const windows = parseMinimaxRemains(parts.remains);
5633
+ return {
5634
+ at: parts.at ?? Date.now(),
5635
+ region: parts.region,
5636
+ signedIn: true,
5637
+ installed: parts.installed ?? true,
5638
+ ...account === void 0 ? {} : { account },
5639
+ plan: {
5640
+ kind,
5641
+ hasTokenPlan,
5642
+ ...planName === void 0 ? {} : { name: planName },
5643
+ ...tier === void 0 ? {} : { tier },
5644
+ ...expiresAt === void 0 ? {} : { expiresAt },
5645
+ ...subscriptionType === void 0 ? {} : { subscriptionType }
5646
+ },
5647
+ ...credits === void 0 ? {} : { credits },
5648
+ ...windows.length === 0 ? {} : { windows }
5649
+ };
5650
+ }
5651
+ /** Read the quota for a token-plan subscriber; a plain account has none. */
5652
+ async function readMinimaxRemains(region, token, groupId, fetchImpl, signal) {
5653
+ const url = new URL("/v1/api/openplatform/coding_plan/remains", MINIMAX_QUOTA_HOSTS[region]);
5654
+ const response = await fetchImpl(url, {
5655
+ redirect: "manual",
5656
+ headers: {
5657
+ Accept: "application/json",
5658
+ Authorization: `Bearer ${token}`,
5659
+ "X-Group-Id": groupId
5660
+ },
5661
+ signal
5662
+ });
5663
+ if (redirectTargetsOtherRegion(region, url, response)) {
5664
+ rememberRegionAccess(region, true);
5665
+ throw new MinimaxRegionBlockedError(region);
5666
+ }
5667
+ if (response.status >= 300 && response.status < 400) return void 0;
5668
+ if (!response.ok) {
5669
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) throw new MinimaxRegionBlockedError(region);
5670
+ if (response.status === 401 || response.status === 403) throw new Error("MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。");
5671
+ return;
5672
+ }
5673
+ return asRecord(await response.json());
5674
+ }
5675
+ const usageCache = /* @__PURE__ */ new Map();
5676
+ const usageInflight = /* @__PURE__ */ new Map();
5677
+ /** Drop a cached quota reading, so the next request re-reads it. */
5678
+ function invalidateMinimaxUsage(region) {
5679
+ if (region === void 0) {
5680
+ usageCache.clear();
5681
+ return;
5682
+ }
5683
+ usageCache.delete(region);
5684
+ }
5685
+ /**
5686
+ * Read one region's account, plan and quota.
5687
+ *
5688
+ * A failed account call keeps the login state and reports the reason in
5689
+ * `error`; the settings card shows the account it already knows with that
5690
+ * message instead of silently claiming nothing is configured.
5691
+ */
5692
+ async function minimaxUsage(region, options = {}) {
5693
+ const installed = resolveMinimaxCli() !== void 0;
5694
+ const token = options.token ?? readStoredToken(region);
5695
+ if (!(token !== void 0 || minimaxSignedIn(region))) return {
5696
+ at: Date.now(),
5697
+ region,
5698
+ signedIn: false,
5699
+ installed
5700
+ };
5701
+ if (await minimaxRegionBlocked(region, {
5702
+ fresh: options.fresh,
5703
+ fetchImpl: options.fetchImpl,
5704
+ signal: options.signal
5705
+ })) return {
5706
+ at: Date.now(),
5707
+ region,
5708
+ signedIn: true,
5709
+ installed,
5710
+ regionBlocked: true,
5711
+ error: minimaxRegionBlockMessage(region)
5712
+ };
5713
+ if (token === void 0) return {
5714
+ at: Date.now(),
5715
+ region,
5716
+ signedIn: true,
5717
+ installed,
5718
+ error: "未找到 MiniMax 登录凭据,请重新登录。"
5719
+ };
5720
+ if (options.token === void 0 && options.fresh !== true) {
5721
+ const cached = usageCache.get(region);
5722
+ if (cached !== void 0 && Date.now() - cached.at < 6e4) return cached.snapshot;
5723
+ }
5724
+ let pending = usageInflight.get(region);
5725
+ if (pending === void 0) {
5726
+ pending = readUsage(region, token, installed, options).finally(() => {
5727
+ usageInflight.delete(region);
5728
+ });
5729
+ usageInflight.set(region, pending);
5730
+ }
5731
+ const snapshot = await pending;
5732
+ if (snapshot.error === void 0 && options.token === void 0) usageCache.set(region, {
5733
+ at: snapshot.at,
5734
+ snapshot
5735
+ });
5736
+ return snapshot;
5737
+ }
5738
+ async function readUsage(region, token, installed, options) {
5739
+ const timeout = AbortSignal.timeout(MINIMAX_USAGE_TIMEOUT_MS);
5740
+ const signal = options.signal === void 0 ? timeout : AbortSignal.any([options.signal, timeout]);
5741
+ const fetchImpl = options.fetchImpl ?? fetch;
5742
+ try {
5743
+ const info = await minimaxAccountCall(region, "/v1/api/user/info", {
5744
+ token,
5745
+ fetchImpl,
5746
+ signal
5747
+ });
5748
+ const userInfo = asRecord(asRecord(info.data)?.userInfo) ?? asRecord(info.userInfo) ?? {};
5749
+ const realUserId = asString(userInfo.realUserID) ?? asString(userInfo.real_user_id);
5750
+ const extra = await minimaxAccountCall(region, "/matrix/api/v1/user/get_user_extra_info", {
5751
+ method: "POST",
5752
+ body: {},
5753
+ realUserId,
5754
+ token,
5755
+ fetchImpl,
5756
+ signal
5757
+ });
5758
+ const workspaces = (Array.isArray(extra.workspaces) ? extra.workspaces : Array.isArray(asRecord(extra.data)?.workspaces) ? asRecord(extra.data)?.workspaces : []).map(asRecord).filter((workspace) => workspace !== void 0);
5759
+ const personal = workspaces.find((workspace) => asNumber(workspace.workspace_type) === 0) ?? workspaces[0];
5760
+ const workspaceId = asNumber(personal?.workspace_id);
5761
+ const membership = workspaceId === void 0 ? {} : await minimaxAccountCall(region, "/matrix/api/v1/commerce/get_membership_info", {
5762
+ method: "POST",
5763
+ body: { workspace_id: workspaceId },
5764
+ realUserId,
5765
+ token,
5766
+ fetchImpl,
5767
+ signal
5768
+ });
5769
+ const groupId = asString(membership.op_group_id) ?? asString(personal?.op_group_id);
5770
+ return minimaxUsageFromParts({
5771
+ region,
5772
+ installed,
5773
+ userInfo,
5774
+ workspaces,
5775
+ membership,
5776
+ remains: (membership.has_token_plan === true || personal?.has_token_plan === true) && groupId !== void 0 ? await readMinimaxRemains(region, token, groupId, fetchImpl, signal) : void 0
5777
+ });
5778
+ } catch (error) {
5779
+ const blocked = error instanceof MinimaxRegionBlockedError;
5780
+ return {
5781
+ at: Date.now(),
5782
+ region,
5783
+ signedIn: true,
5784
+ installed,
5785
+ ...blocked ? { regionBlocked: true } : {},
5786
+ error: blocked ? minimaxRegionBlockMessage(region) : error instanceof Error ? error.message : String(error)
5787
+ };
5788
+ }
5789
+ }
5790
+ /** Trim CLI output to a short, token-free sentence. */
5791
+ function outputTail(lines) {
5792
+ return lines.slice(-4).map((line) => line.replace(/mmo(at|rt)_[A-Za-z0-9_-]+/g, "mmo***")).join(" ").slice(0, 400);
5793
+ }
5794
+ /**
5795
+ * Browser login/logout, one run per region.
5796
+ *
5797
+ * The CLI owns the OAuth device flow and the credential file. The plugin only
5798
+ * starts the process, surfaces the authorization URL while it waits, and then
5799
+ * re-reads the auth-state file to decide whether the region is signed in.
5800
+ */
5801
+ var MinimaxAuth = class {
5802
+ runs = /* @__PURE__ */ new Map();
5803
+ status(region) {
5804
+ const run = this.runs.get(region);
5805
+ if (run !== void 0) return run.status;
5806
+ const state = readAuthState(region);
5807
+ return {
5808
+ running: false,
5809
+ region,
5810
+ signedIn: state?.status === "authenticated",
5811
+ ...state?.expiresAtMs === void 0 ? {} : { expiresAt: state.expiresAtMs }
5812
+ };
5813
+ }
5814
+ /** Start the CLI's browser login. */
5815
+ start(region, onFinish) {
5816
+ const existing = this.runs.get(region);
5817
+ if (existing !== void 0 && existing.status.running) return {
5818
+ started: false,
5819
+ error: "该区域正在登录,请先在浏览器中完成授权。"
5820
+ };
5821
+ const spec = resolveMinimaxCli();
5822
+ if (spec === void 0) return {
5823
+ started: false,
5824
+ error: "未安装 MiniMax Code CLI(mcode),请先安装后再登录。"
5825
+ };
5826
+ const status = {
5827
+ running: true,
5828
+ region,
5829
+ signedIn: false,
5830
+ startedAt: Date.now()
5831
+ };
5832
+ const run = {
5833
+ status,
5834
+ child: void 0,
5835
+ lines: [],
5836
+ finish: (_code) => {}
5837
+ };
5838
+ const env = {
5839
+ ...process.env,
5840
+ MAVIS_REGION: minimaxCliRegion(region)
5841
+ };
5842
+ delete env.MAVIS_AGENT;
5843
+ delete env.MAVIS_SESSION;
5844
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
5845
+ "login",
5846
+ "--region",
5847
+ region === "cn" ? "cn" : "global"
5848
+ ]), {
5849
+ cwd: homedir(),
5850
+ env,
5851
+ windowsHide: true,
5852
+ stdio: [
5853
+ "ignore",
5854
+ "pipe",
5855
+ "pipe"
5856
+ ]
5857
+ });
5858
+ run.child = child;
5859
+ this.runs.set(region, run);
5860
+ const absorb = (chunk) => {
5861
+ const text = String(chunk);
5862
+ for (const line of text.split(/\r?\n/)) {
5863
+ const trimmed = line.trim();
5864
+ if (trimmed === "") continue;
5865
+ run.lines.push(trimmed);
5866
+ const match = /^(?:Open:\s*)?(https?:\/\/\S+)/.exec(trimmed);
5867
+ if (match !== null) status.url = match[1];
5868
+ }
5869
+ while (run.lines.length > 40) run.lines.shift();
5870
+ };
5871
+ child.stdout?.on("data", absorb);
5872
+ child.stderr?.on("data", absorb);
5873
+ const finish = (code) => {
5874
+ if (!status.running) return;
5875
+ status.running = false;
5876
+ status.finishedAt = Date.now();
5877
+ const state = readAuthState(region);
5878
+ status.signedIn = state?.status === "authenticated";
5879
+ if (state?.expiresAtMs !== void 0) status.expiresAt = state.expiresAtMs;
5880
+ if (code !== 0) status.error = outputTail(run.lines) || "登录未完成";
5881
+ else if (!status.signedIn) status.error = outputTail(run.lines) || "登录未完成";
5882
+ try {
5883
+ onFinish?.(status.signedIn);
5884
+ } catch {}
5885
+ };
5886
+ run.finish = finish;
5887
+ child.on("error", (error) => {
5888
+ status.error = `无法启动 mcode:${error.message}`;
5889
+ finish(null);
5890
+ });
5891
+ child.on("close", (code) => {
5892
+ finish(code);
5893
+ });
5894
+ return { started: true };
5895
+ }
5896
+ /** Sign one region out; the other region is untouched. */
5897
+ async logout(region) {
5898
+ const spec = resolveMinimaxCli();
5899
+ if (spec === void 0) return {
5900
+ running: false,
5901
+ region,
5902
+ signedIn: false,
5903
+ error: "未安装 MiniMax Code CLI(mcode)。"
5904
+ };
5905
+ const env = {
5906
+ ...process.env,
5907
+ MAVIS_REGION: minimaxCliRegion(region)
5908
+ };
5909
+ delete env.MAVIS_AGENT;
5910
+ delete env.MAVIS_SESSION;
5911
+ const result = await new Promise((resolve) => {
5912
+ const lines = [];
5913
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
5914
+ "logout",
5915
+ "--region",
5916
+ region === "cn" ? "cn" : "global"
5917
+ ]), {
5918
+ cwd: homedir(),
5919
+ env,
5920
+ windowsHide: true,
5921
+ stdio: [
5922
+ "ignore",
5923
+ "pipe",
5924
+ "pipe"
5925
+ ]
5926
+ });
5927
+ const absorb = (chunk) => {
5928
+ for (const line of String(chunk).split(/\r?\n/)) if (line.trim() !== "") lines.push(line.trim());
5929
+ while (lines.length > 40) lines.shift();
5930
+ };
5931
+ child.stdout?.on("data", absorb);
5932
+ child.stderr?.on("data", absorb);
5933
+ const timer = setTimeout(() => {
5934
+ child.kill();
5935
+ resolve({
5936
+ code: null,
5937
+ lines
5938
+ });
5939
+ }, 2e4);
5940
+ child.on("error", () => {
5941
+ clearTimeout(timer);
5942
+ resolve({
5943
+ code: null,
5944
+ lines
5945
+ });
5946
+ });
5947
+ child.on("close", (code) => {
5948
+ clearTimeout(timer);
5949
+ resolve({
5950
+ code,
5951
+ lines
5952
+ });
5953
+ });
5954
+ });
5955
+ this.runs.delete(region);
5956
+ const state = readAuthState(region);
5957
+ return {
5958
+ running: false,
5959
+ region,
5960
+ signedIn: state?.status === "authenticated",
5961
+ ...state?.expiresAtMs === void 0 ? {} : { expiresAt: state.expiresAtMs },
5962
+ ...result.code !== 0 ? { error: outputTail(result.lines) || "退出登录未完成" } : {}
5963
+ };
5964
+ }
5965
+ /** Cancel any login process (plugin disposal). */
5966
+ stop() {
5967
+ for (const run of this.runs.values()) if (run.status.running) run.child.kill();
5968
+ }
5969
+ };
5970
+ /** A single-consumer async event queue. */
5971
+ var EventQueue = class {
5972
+ items = [];
5973
+ waiter = null;
5974
+ closed = false;
5975
+ push(event) {
5976
+ if (this.closed) return;
5977
+ if (this.waiter !== null) {
5978
+ const settle = this.waiter;
5979
+ this.waiter = null;
5980
+ settle(event);
5981
+ return;
5982
+ }
5983
+ this.items.push(event);
5984
+ }
5985
+ close() {
5986
+ if (this.closed) return;
5987
+ this.closed = true;
5988
+ if (this.waiter !== null) {
5989
+ const settle = this.waiter;
5990
+ this.waiter = null;
5991
+ settle(void 0);
5992
+ }
5993
+ }
5994
+ get isClosed() {
5995
+ return this.closed;
5996
+ }
5997
+ next() {
5998
+ const item = this.items.shift();
5999
+ if (item !== void 0) return Promise.resolve(item);
6000
+ if (this.closed) return Promise.resolve(void 0);
6001
+ return new Promise((resolve) => {
6002
+ this.waiter = resolve;
6003
+ });
6004
+ }
6005
+ };
6006
+ /** Render a harness tool result for the MCP caller. */
6007
+ function renderToolResult(content) {
6008
+ const text = (value) => {
6009
+ if (typeof value === "string") return value;
6010
+ if (value === null || value === void 0) return "";
6011
+ try {
6012
+ return JSON.stringify(value);
6013
+ } catch {
6014
+ return String(value);
6015
+ }
6016
+ };
6017
+ if (Array.isArray(content)) {
6018
+ const parts = [];
6019
+ for (const block of content) {
6020
+ if (typeof block === "string") {
6021
+ parts.push(block);
6022
+ continue;
6023
+ }
6024
+ if (block !== null && typeof block === "object" && block.type === "text") {
6025
+ parts.push(text(block.text));
6026
+ continue;
6027
+ }
6028
+ parts.push(text(block));
6029
+ }
6030
+ const joined = parts.join("\n").trim();
6031
+ return { content: [{
6032
+ type: "text",
6033
+ text: joined === "" ? "(宿主工具没有返回内容)" : joined
6034
+ }] };
6035
+ }
6036
+ const joined = text(content).trim();
6037
+ return { content: [{
6038
+ type: "text",
6039
+ text: joined === "" ? "(宿主工具没有返回内容)" : joined
6040
+ }] };
6041
+ }
6042
+ /**
6043
+ * One `mcode acp` process and its ACP session.
6044
+ *
6045
+ * The class only speaks protocol: model/effort config, prompts, cancellation,
6046
+ * and the translation of `session/update` into {@link SessionEvent}s. Turn
6047
+ * policy (tool calls, retries, harness chunks) lives in {@link MinimaxSession}.
6048
+ */
6049
+ var MinimaxAcp = class {
6050
+ child = null;
6051
+ conn = null;
6052
+ sessionId;
6053
+ configOptions = [];
6054
+ systemFile;
6055
+ tempDir;
6056
+ closing = false;
6057
+ stderr = [];
6058
+ options;
6059
+ constructor(options) {
6060
+ this.options = options;
6061
+ }
6062
+ /** The model/effort options the CLI currently offers. */
6063
+ get optionsList() {
6064
+ return this.configOptions;
6065
+ }
6066
+ /** The selected model config value. */
6067
+ get currentModel() {
6068
+ const option = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
6069
+ return typeof option?.currentValue === "string" ? option.currentValue : void 0;
6070
+ }
6071
+ /** Start the process and create one ACP session. */
6072
+ async start() {
6073
+ const spec = resolveMinimaxCli();
6074
+ if (spec === void 0) throw new Error("未安装 MiniMax Code CLI(mcode)。请在设置页安装,或运行 npm install -g @minimax-ai/code。");
6075
+ const timeout = this.options.timeoutMs ?? 3e4;
6076
+ const directory = mkdtempSync(join(tmpdir(), "dsh-minimax-acp-"));
6077
+ const systemFile = join(directory, "system.md");
6078
+ writeFileSync(systemFile, this.options.systemPrompt, "utf8");
6079
+ this.systemFile = systemFile;
6080
+ this.tempDir = directory;
6081
+ const env = {
6082
+ ...process.env,
6083
+ MAVIS_REGION: minimaxCliRegion(this.options.region),
6084
+ ...this.options.disableTools === true ? { MAVIS_LOCAL_RUNTIME_DISABLE_TOOLS: "1" } : {}
6085
+ };
6086
+ delete env.MAVIS_AGENT;
6087
+ delete env.MAVIS_SESSION;
6088
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
6089
+ "acp",
6090
+ "--system-prompt-file",
6091
+ systemFile
6092
+ ]), {
6093
+ cwd: this.options.cwd,
6094
+ env,
6095
+ windowsHide: true,
6096
+ stdio: [
6097
+ "pipe",
6098
+ "pipe",
6099
+ "pipe"
6100
+ ]
6101
+ });
6102
+ this.child = child;
6103
+ child.stderr?.on("data", (chunk) => {
6104
+ for (const line of String(chunk).split(/\r?\n/)) if (line.trim() !== "") this.stderr.push(line.trim());
6105
+ while (this.stderr.length > 30) this.stderr.shift();
6106
+ });
6107
+ child.on("exit", (code, signal) => {
6108
+ if (this.closing) return;
6109
+ const detail = outputTail(this.stderr) || `mcode acp 退出(code=${String(code)}, signal=${String(signal)})`;
6110
+ this.options.onExit?.(new Error(detail));
6111
+ });
6112
+ if (child.stdin === null || child.stdout === null) throw new Error("mcode acp 没有可用的 stdio。");
6113
+ const client = {
6114
+ sessionUpdate: (params) => {
6115
+ if (params.sessionId !== void 0 && this.sessionId !== void 0 && params.sessionId !== this.sessionId) return;
6116
+ const update = params.update;
6117
+ if (update === null || typeof update !== "object") return;
6118
+ switch (update.sessionUpdate) {
6119
+ case "agent_message_chunk": {
6120
+ const text = typeof update.content?.text === "string" ? update.content.text : "";
6121
+ if (text.length > 0) this.options.onUpdate?.({
6122
+ kind: "text",
6123
+ text
6124
+ });
6125
+ return;
6126
+ }
6127
+ case "agent_thought_chunk": {
6128
+ const text = typeof update.content?.text === "string" ? update.content.text : "";
6129
+ if (text.length > 0) this.options.onUpdate?.({
6130
+ kind: "reasoning",
6131
+ text
6132
+ });
6133
+ return;
6134
+ }
6135
+ case "usage_update": {
6136
+ const used = typeof update.used === "number" ? update.used : 0;
6137
+ const size = typeof update.size === "number" ? update.size : 0;
6138
+ if (size > 0) this.options.onUpdate?.({
6139
+ kind: "usage",
6140
+ used,
6141
+ size
6142
+ });
6143
+ return;
6144
+ }
6145
+ case "tool_call":
6146
+ case "tool_call_update": {
6147
+ const name = typeof update.title === "string" && update.title.length > 0 ? update.title : typeof update.name === "string" ? update.name : "";
6148
+ if (name.length === 0) return;
6149
+ if (!isHostMcpTool(name)) {
6150
+ if (update.sessionUpdate === "tool_call" || update.status === "in_progress") this.options.onUpdate?.({
6151
+ kind: "native-tool",
6152
+ name
6153
+ });
6154
+ return;
6155
+ }
6156
+ return;
6157
+ }
6158
+ default: return;
6159
+ }
6160
+ },
6161
+ requestPermission: async (params) => {
6162
+ const name = typeof params?.toolCall?.title === "string" && params.toolCall.title.length > 0 ? params.toolCall.title : typeof params?.toolCall?.name === "string" ? params.toolCall.name : "";
6163
+ const options = Array.isArray(params?.options) ? params.options : [];
6164
+ if (isHostMcpTool(name)) {
6165
+ const allow = options.find((entry) => entry?.kind === "allow_once") ?? options.find((entry) => entry?.kind === "allow_always") ?? options[0];
6166
+ if (allow !== void 0) return { outcome: {
6167
+ outcome: "selected",
6168
+ optionId: allow.optionId
6169
+ } };
6170
+ return { outcome: { outcome: "cancelled" } };
6171
+ }
6172
+ this.options.onPermissionDenied?.(name);
6173
+ const deny = options.find((entry) => entry?.kind === "reject_once") ?? options.find((entry) => entry?.kind === "reject_always");
6174
+ return deny === void 0 ? { outcome: { outcome: "cancelled" } } : { outcome: {
6175
+ outcome: "selected",
6176
+ optionId: deny.optionId
6177
+ } };
6178
+ }
6179
+ };
6180
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
6181
+ const conn = new ClientSideConnection(() => client, stream);
6182
+ this.conn = conn;
6183
+ await withTimeout(conn.initialize({
6184
+ protocolVersion: PROTOCOL_VERSION,
6185
+ clientCapabilities: {
6186
+ fs: {
6187
+ readTextFile: false,
6188
+ writeTextFile: false
6189
+ },
6190
+ terminal: false
6191
+ },
6192
+ clientInfo: {
6193
+ name: "dsh-agent-sdk-bridge",
6194
+ version: "1.1.0"
6195
+ }
6196
+ }), timeout, "mcode acp initialize");
6197
+ const mcpServers = this.options.mcpUrl === void 0 ? [] : [{
6198
+ type: "http",
6199
+ name: MINIMAX_MCP_SERVER,
6200
+ url: this.options.mcpUrl,
6201
+ headers: [{
6202
+ name: "Authorization",
6203
+ value: `Bearer ${this.options.mcpToken ?? ""}`
6204
+ }]
6205
+ }];
6206
+ const session = await withTimeout(conn.newSession({
6207
+ cwd: this.options.cwd,
6208
+ mcpServers
6209
+ }), timeout, "mcode acp session/new");
6210
+ this.sessionId = session.sessionId;
6211
+ this.configOptions = Array.isArray(session.configOptions) ? [...session.configOptions] : [];
6212
+ }
6213
+ /**
6214
+ * Run one prompt; resolves when the agent's turn ends.
6215
+ *
6216
+ * ACP carries images as `{ type: 'image', data, mimeType }` blocks next to
6217
+ * text, which is what makes a pasted picture reach the model at all; a plain
6218
+ * string keeps the historical text-only shape.
6219
+ */
6220
+ async prompt(prompt) {
6221
+ if (this.conn === null || this.sessionId === void 0) throw new Error("ACP 会话尚未启动。");
6222
+ const blocks = typeof prompt === "string" ? [{
6223
+ type: "text",
6224
+ text: prompt
6225
+ }] : [...prompt];
6226
+ const response = await this.conn.prompt({
6227
+ sessionId: this.sessionId,
6228
+ prompt: blocks
6229
+ });
6230
+ return { stopReason: String(response.stopReason) };
6231
+ }
6232
+ /** Ask the agent to stop the active turn. */
6233
+ async cancel() {
6234
+ if (this.conn === null || this.sessionId === void 0) return;
6235
+ try {
6236
+ await this.conn.cancel({ sessionId: this.sessionId });
6237
+ } catch {}
6238
+ }
6239
+ /** Set a session config option and remember the updated list. */
6240
+ async setConfig(id, value) {
6241
+ if (this.conn === null || this.sessionId === void 0) return;
6242
+ const option = this.configOptions.find((entry) => entry?.id === id);
6243
+ if (option === void 0) return;
6244
+ if (option.currentValue === value) return;
6245
+ if (!(Array.isArray(option.options) ? option.options.some((entry) => entry?.value === value) : true)) return;
6246
+ const response = await this.conn.setSessionConfigOption({
6247
+ sessionId: this.sessionId,
6248
+ configId: id,
6249
+ value
6250
+ });
6251
+ if (Array.isArray(response.configOptions)) this.configOptions = [...response.configOptions];
6252
+ }
6253
+ /**
6254
+ * List the models the CLI actually accepts, with each model's own efforts.
6255
+ *
6256
+ * The advertised option list can contain values the agent rejects (0.6.12
6257
+ * lists a `M3.1-Flash` non-thinking value and answers `Invalid model
6258
+ * reasoning` when it is selected). Selecting each value once is the only
6259
+ * reliable filter, and it also reveals that non-thinking models drop the
6260
+ * `thinkingEffort` option entirely, so reasoning has to be reported per
6261
+ * model rather than once for the catalog.
6262
+ */
6263
+ async probeModels() {
6264
+ const modelOption = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
6265
+ if (!Array.isArray(modelOption?.options)) return [];
6266
+ const initial = typeof modelOption.currentValue === "string" ? modelOption.currentValue : void 0;
6267
+ const seen = /* @__PURE__ */ new Set();
6268
+ const models = [];
6269
+ for (const entry of modelOption.options) {
6270
+ if (typeof entry?.value !== "string" || entry.value.length === 0 || seen.has(entry.value)) continue;
6271
+ seen.add(entry.value);
6272
+ try {
6273
+ await this.setConfig(String(modelOption.id), entry.value);
6274
+ } catch {
6275
+ continue;
6276
+ }
6277
+ const row = modelRow(entry, effortValues(this.configOptions.find((option) => option?.id === "thinkingEffort" || option?.category === "thought_level")?.options));
6278
+ if (row !== void 0) models.push(row);
6279
+ }
6280
+ if (initial !== void 0 && this.currentModel !== initial) try {
6281
+ await this.setConfig(String(modelOption.id), initial);
6282
+ } catch {}
6283
+ return models;
6284
+ }
6285
+ /** Select the model (and, when supported, the thinking effort). */
6286
+ async selectModel(model, effort) {
6287
+ const modelOption = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
6288
+ if (modelOption !== void 0) {
6289
+ if ((Array.isArray(modelOption.options) ? modelOption.options.map((entry) => entry?.value) : []).includes(model)) await this.setConfig(String(modelOption.id), model);
6290
+ }
6291
+ if (effort !== void 0 && effort.length > 0 && effort !== "default") {
6292
+ const effortOption = this.configOptions.find((entry) => entry?.id === "thinkingEffort" || entry?.category === "thought_level");
6293
+ if (effortOption !== void 0) try {
6294
+ await this.setConfig(String(effortOption.id), effort);
6295
+ } catch {}
6296
+ }
6297
+ }
6298
+ /** Exit the session and reap the process. */
6299
+ async close() {
6300
+ if (this.closing) return;
6301
+ this.closing = true;
6302
+ const conn = this.conn;
6303
+ const sessionId = this.sessionId;
6304
+ this.conn = null;
6305
+ this.sessionId = void 0;
6306
+ if (conn !== null && sessionId !== void 0) await withTimeout(conn.closeSession({ sessionId }), 3e3, "mcode acp session/close").catch(() => void 0);
6307
+ this.child?.kill();
6308
+ this.child = null;
6309
+ if (this.tempDir !== void 0) {
6310
+ try {
6311
+ rmSync(this.tempDir, {
6312
+ recursive: true,
6313
+ force: true
6314
+ });
6315
+ } catch {}
6316
+ this.tempDir = void 0;
6317
+ }
6318
+ this.systemFile = void 0;
6319
+ }
6320
+ };
6321
+ /** A one-shot ACP process used by the catalog and title side channels. */
6322
+ async function withAcp(region, timeoutMs, run, options = {}) {
6323
+ const cwd = mkdtempSync(join(tmpdir(), "dsh-minimax-side-"));
6324
+ const acp = new MinimaxAcp({
6325
+ region,
6326
+ cwd,
6327
+ systemPrompt: options.systemPrompt ?? "You are a helper. Do not use tools.",
6328
+ disableTools: options.disableTools ?? true,
6329
+ timeoutMs
6330
+ });
6331
+ try {
6332
+ await acp.start();
6333
+ return await run(acp);
6334
+ } finally {
6335
+ await acp.close();
6336
+ try {
6337
+ rmSync(cwd, {
6338
+ recursive: true,
6339
+ force: true
6340
+ });
6341
+ } catch {}
6342
+ }
6343
+ }
6344
+ /** Read the model list for one region (cached). */
6345
+ var MinimaxCatalog = class {
6346
+ region;
6347
+ ttlMs;
6348
+ timeoutMs;
6349
+ snapshots = /* @__PURE__ */ new Map();
6350
+ inflight = /* @__PURE__ */ new Map();
6351
+ failures = /* @__PURE__ */ new Map();
6352
+ constructor(region, ttlMs = MINIMAX_CACHE_TTL_MS, timeoutMs = MINIMAX_FETCH_TIMEOUT_MS) {
6353
+ this.region = region;
6354
+ this.ttlMs = ttlMs;
6355
+ this.timeoutMs = timeoutMs;
6356
+ }
6357
+ /** Models for one region; a failed refresh keeps the last good list. */
6358
+ async models(requested) {
6359
+ const region = requested ?? readLive(this.region, "cn");
6360
+ if (await minimaxRegionBlocked(region)) {
6361
+ this.invalidate(region);
6362
+ return [];
6363
+ }
6364
+ const ttl = readLive(this.ttlMs, MINIMAX_CACHE_TTL_MS);
6365
+ const cached = this.snapshots.get(region);
6366
+ if (cached !== void 0 && Date.now() - cached.at < ttl) return cached.models;
6367
+ let pending = this.inflight.get(region);
6368
+ if (pending === void 0) {
6369
+ pending = this.fetch(region).finally(() => {
6370
+ this.inflight.delete(region);
6371
+ });
6372
+ this.inflight.set(region, pending);
6373
+ }
6374
+ try {
6375
+ const models = await pending;
6376
+ this.snapshots.set(region, {
6377
+ at: Date.now(),
6378
+ models
6379
+ });
6380
+ this.failures.delete(region);
6381
+ return models;
6382
+ } catch (error) {
6383
+ this.failures.set(region, error instanceof Error ? error.message : String(error));
6384
+ return cached?.models ?? [];
6385
+ }
6386
+ }
6387
+ /** Why the last refresh failed, or undefined when it succeeded. */
6388
+ error(requested) {
6389
+ return this.failures.get(requested ?? readLive(this.region, "cn"));
6390
+ }
6391
+ invalidate(region) {
6392
+ if (region === void 0) {
6393
+ this.snapshots.clear();
6394
+ this.failures.clear();
6395
+ return;
6396
+ }
6397
+ this.snapshots.delete(region);
6398
+ this.failures.delete(region);
6399
+ }
6400
+ async fetch(region) {
6401
+ if (!minimaxSignedIn(region)) throw new Error(`${region === "cn" ? "MiniMax 国内站" : "MiniMax 国际站"}尚未登录,请先在设置页登录。`);
6402
+ if (await minimaxRegionBlocked(region)) throw new MinimaxRegionBlockedError(region);
6403
+ return await withAcp(region, readLive(this.timeoutMs, MINIMAX_FETCH_TIMEOUT_MS), async (acp) => acp.probeModels(), {
6404
+ systemPrompt: "You are a helper used only to list models. Do not call any tool.",
6405
+ disableTools: true
6406
+ });
6407
+ }
6408
+ };
6409
+ /** One shared HTTP MCP server for every warm MiniMax session. */
6410
+ var MinimaxMcpServer = class {
6411
+ server;
6412
+ port = 0;
6413
+ bridges = /* @__PURE__ */ new Map();
6414
+ /** The base URL, or undefined before {@link start}. */
6415
+ get baseUrl() {
6416
+ return this.server === void 0 ? void 0 : `http://127.0.0.1:${this.port}`;
6417
+ }
6418
+ /** Bind to an ephemeral loopback port. */
6419
+ async start() {
6420
+ if (this.server !== void 0) return;
6421
+ const server = createServer((req, res) => {
6422
+ this.handle(req, res);
6423
+ });
6424
+ await new Promise((resolve, reject) => {
6425
+ server.once("error", reject);
6426
+ server.listen(0, "127.0.0.1", () => resolve());
6427
+ });
6428
+ const address = server.address();
6429
+ if (address === null || typeof address === "string") {
6430
+ server.close();
6431
+ throw new Error("无法为 MiniMax 宿主工具分配本地端口。");
6432
+ }
6433
+ this.port = address.port;
6434
+ this.server = server;
6435
+ }
6436
+ /** Add one session's bridge under a random token. */
6437
+ register(bridge) {
6438
+ if (this.server === void 0) throw new Error("MiniMax MCP server 尚未启动。");
6439
+ const token = randomBytes(24).toString("hex");
6440
+ this.bridges.set(token, bridge);
6441
+ return {
6442
+ url: `${this.baseUrl}/mcp/${token}`,
6443
+ token
6444
+ };
6445
+ }
6446
+ unregister(token) {
6447
+ this.bridges.delete(token);
6448
+ }
6449
+ /** Close the server and release every session. */
6450
+ close() {
6451
+ this.bridges.clear();
6452
+ this.server?.close();
6453
+ this.server = void 0;
6454
+ }
6455
+ async handle(req, res) {
6456
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
6457
+ const match = /^\/mcp\/([a-f0-9]+)$/.exec(url.pathname);
6458
+ const bridge = match === null ? void 0 : this.bridges.get(match[1]);
6459
+ if (bridge === void 0) {
6460
+ res.writeHead(404, { "content-type": "application/json" }).end("{\"error\":\"unknown MCP session\"}");
6461
+ return;
6462
+ }
6463
+ if (req.method === "GET") {
6464
+ res.writeHead(405).end();
6465
+ return;
6466
+ }
6467
+ if (req.method === "DELETE") {
6468
+ res.writeHead(200).end();
6469
+ return;
6470
+ }
6471
+ if (req.method !== "POST") {
6472
+ res.writeHead(405).end();
6473
+ return;
6474
+ }
6475
+ if (req.headers.authorization !== `Bearer ${match?.[1] ?? ""}`) {
6476
+ res.writeHead(403).end();
6477
+ return;
6478
+ }
6479
+ let raw = "";
6480
+ for await (const chunk of req) {
6481
+ raw += chunk;
6482
+ if (raw.length > 8388608) {
6483
+ res.writeHead(413).end();
6484
+ return;
6485
+ }
6486
+ }
6487
+ let message;
6488
+ try {
6489
+ message = JSON.parse(raw);
6490
+ } catch {
6491
+ res.writeHead(400).end();
6492
+ return;
6493
+ }
6494
+ const id = message?.id;
6495
+ const reply = (payload) => {
6496
+ const body = JSON.stringify(payload);
6497
+ res.writeHead(200, {
6498
+ "content-type": "application/json",
6499
+ "mcp-session-id": match?.[1] ?? "dsh-host"
6500
+ }).end(body);
6501
+ };
6502
+ if (message?.method === void 0) {
6503
+ res.writeHead(202).end();
6504
+ return;
6505
+ }
6506
+ if (id === void 0) {
6507
+ res.writeHead(202).end();
6508
+ return;
6509
+ }
6510
+ try {
6511
+ switch (message.method) {
6512
+ case "initialize":
6513
+ reply({
6514
+ jsonrpc: "2.0",
6515
+ id,
6516
+ result: {
6517
+ protocolVersion: message.params?.protocolVersion ?? "2025-06-18",
6518
+ capabilities: { tools: {} },
6519
+ serverInfo: {
6520
+ name: MINIMAX_MCP_SERVER,
6521
+ version: "1.0.0"
6522
+ }
6523
+ }
6524
+ });
6525
+ return;
6526
+ case "ping":
6527
+ reply({
6528
+ jsonrpc: "2.0",
6529
+ id,
6530
+ result: {}
6531
+ });
6532
+ return;
6533
+ case "tools/list":
6534
+ reply({
6535
+ jsonrpc: "2.0",
6536
+ id,
6537
+ result: { tools: bridge.tools() }
6538
+ });
6539
+ return;
6540
+ case "tools/call": {
6541
+ const name = typeof message.params?.name === "string" ? message.params.name : "";
6542
+ const args = message.params?.arguments !== null && typeof message.params?.arguments === "object" ? message.params.arguments : {};
6543
+ reply({
6544
+ jsonrpc: "2.0",
6545
+ id,
6546
+ result: await bridge.call(name, args)
6547
+ });
6548
+ return;
6549
+ }
6550
+ default:
6551
+ reply({
6552
+ jsonrpc: "2.0",
6553
+ id,
6554
+ error: {
6555
+ code: -32601,
6556
+ message: `Unknown method ${String(message.method)}`
6557
+ }
6558
+ });
6559
+ return;
6560
+ }
6561
+ } catch (error) {
6562
+ reply({
6563
+ jsonrpc: "2.0",
6564
+ id,
6565
+ result: {
6566
+ content: [{
6567
+ type: "text",
6568
+ text: error instanceof Error ? error.message : String(error)
6569
+ }],
6570
+ isError: true
6571
+ }
6572
+ });
6573
+ }
6574
+ }
6575
+ };
6576
+ /** One session's view of the MCP server. */
6577
+ var MinimaxMcpBridge = class {
6578
+ callHost;
6579
+ schemas = [];
6580
+ constructor(callHost) {
6581
+ this.callHost = callHost;
6582
+ }
6583
+ setTools(tools) {
6584
+ this.schemas = tools;
6585
+ }
6586
+ tools() {
6587
+ return this.schemas.map((schema) => ({
6588
+ name: schema.name,
6589
+ description: schema.description.length > 0 ? schema.description : schema.name,
6590
+ inputSchema: schema.parameters !== null && typeof schema.parameters === "object" ? schema.parameters : {
6591
+ type: "object",
6592
+ properties: {}
6593
+ }
6594
+ }));
6595
+ }
6596
+ async call(name, args) {
6597
+ if (!this.schemas.some((schema) => schema.name === name)) return {
6598
+ content: [{
6599
+ type: "text",
6600
+ text: `未知工具:${name}`
6601
+ }],
6602
+ isError: true
6603
+ };
6604
+ return await this.callHost(name, args);
6605
+ }
6606
+ };
6607
+ /**
6608
+ * Round one token count up to a whole number.
6609
+ *
6610
+ * The harness validates every usage bucket as `number().int().nonnegative()`.
6611
+ * The text estimator prices by script and therefore returns fractions; a
6612
+ * fractional reading is accepted when it streams but makes the durable usage
6613
+ * projection fail, and the conversation then refuses to load at all (the
6614
+ * "failed to project session" error). Counts must leave this module whole.
6615
+ */
6616
+ function wholeTokens(value) {
6617
+ return Math.max(1, Math.ceil(value));
6618
+ }
6619
+ /** Build a turn's usage from its character counts and the reported context. */
6620
+ function minimaxTurnUsage(counts) {
6621
+ const inputTokens = wholeTokens(counts.contextUsed ?? estimateTextTokens(counts.inputChars, 0));
6622
+ const outputTokens = wholeTokens(estimateTextTokens(counts.outputChars + counts.reasoningChars, 0));
6623
+ const reasoningTokens = counts.reasoningChars === 0 ? void 0 : Math.min(outputTokens, wholeTokens(estimateTextTokens(counts.reasoningChars, 0)));
6624
+ return {
6625
+ inputTokens,
6626
+ outputTokens,
6627
+ ...reasoningTokens === void 0 ? {} : { reasoningTokens },
6628
+ cacheReadTokens: 0,
6629
+ cacheWriteTokens: 0,
6630
+ totalTokens: inputTokens + outputTokens
6631
+ };
6632
+ }
6633
+ /** A prompt that asks the model to retry without native tools. */
6634
+ const NATIVE_TOOL_CORRECTION = [
6635
+ "SYSTEM NOTICE (not from the user):",
6636
+ "The built-in tools (bash, read, write, edit, glob, grep, web_fetch, task, and every other native tool)",
6637
+ "are disabled in this deployment. Any call to them is cancelled before execution.",
6638
+ "The only valid tools are the host MCP tools whose names begin with mcp__dsh-host__.",
6639
+ "Re-answer the user's last request using only those host tools. Do not mention this notice."
6640
+ ].join("\n");
6641
+ /** The tool policy appended to the host system prompt. */
6642
+ const HOST_TOOL_POLICY = [
6643
+ "## Host tool protocol",
6644
+ "You are the model backend of DeepSeek Harness.",
6645
+ "The ONLY tools you may call are the host MCP tools exposed by the `dsh-host` MCP server;",
6646
+ "their names begin with `mcp__dsh-host__`. The built-in tools (bash, read, write, edit, glob,",
6647
+ "grep, web_fetch, task, and every other native tool) are disabled in this deployment: calling",
6648
+ "one aborts the turn before execution. Never mention this rule to the user."
6649
+ ].join("\n");
6650
+ /**
6651
+ * One warm MiniMax conversation for a harness session id.
6652
+ *
6653
+ * The ACP agent owns the history. A turn ends either when the prompt finishes
6654
+ * or when a host tool call is handed to the harness; in the latter case the
6655
+ * ACP prompt stays open until the harness returns the result on its next
6656
+ * request, exactly like the CodeBuddy bridge.
6657
+ */
6658
+ var MinimaxSession = class {
6659
+ sessionId;
6660
+ mcpServer;
6661
+ acp = null;
6662
+ events = new EventQueue();
6663
+ bridge;
6664
+ pending = /* @__PURE__ */ new Map();
6665
+ toolResultTimeoutMs;
6666
+ abortGraceMs;
6667
+ callNonce = randomUUID().slice(0, 8);
6668
+ toolCounter = 0;
6669
+ promptInFlight = false;
6670
+ activeTurn = false;
6671
+ disposed = false;
6672
+ region = "cn";
6673
+ model = "";
6674
+ effort;
6675
+ systemPrompt = "";
6676
+ workspace;
6677
+ /** The harness workspace; absent means the session owns a temp directory. */
6678
+ requestedCwd;
6679
+ ownsWorkspace = false;
6680
+ mcpToken;
6681
+ toolSchemas = [];
6682
+ nativeViolation = false;
6683
+ cancelSent = false;
6684
+ correctionCount = 0;
6685
+ observedContextWindow;
6686
+ /** Was the last turn closed with tool-calls, leaving the ACP prompt open? */
6687
+ awaitingToolResults = false;
6688
+ /** Host messages already fed to the ACP session, for continuation planning. */
6689
+ fedMessages;
6690
+ /** Host system prompt last applied; informational for the adapter. */
6691
+ fedSystem;
6692
+ constructor(sessionId, initialModel, mcpServer, runtime = {}) {
6693
+ this.sessionId = sessionId;
6694
+ this.mcpServer = mcpServer;
6695
+ this.model = initialModel;
6696
+ this.toolResultTimeoutMs = readLive(runtime.toolResultTimeoutMs, 12e4);
6697
+ this.abortGraceMs = readLive(runtime.abortGraceMs, 5e3);
6698
+ this.bridge = new MinimaxMcpBridge((name, args) => this.handleToolCall(name, args));
6699
+ }
6700
+ /** Model context window observed from a real turn, when one was reported. */
6701
+ get contextWindow() {
6702
+ return this.observedContextWindow;
6703
+ }
6704
+ /**
6705
+ * Whether the ACP session still owns an unfinished turn.
6706
+ *
6707
+ * A turn closed with `tool-calls` keeps its prompt open while the host runs
6708
+ * the tools, so this stays true between the two host requests. A brand-new
6709
+ * user message in that state cannot be injected; the adapter rebuilds the
6710
+ * session and feeds the whole history instead.
6711
+ */
6712
+ get busy() {
6713
+ return this.promptInFlight || this.activeTurn;
6714
+ }
6715
+ /**
6716
+ * Point the session at a region, model and system prompt.
6717
+ *
6718
+ * @returns true when the warm ACP process was dropped, which means the
6719
+ * conversation state must be rebuilt from the durable history.
6720
+ */
6721
+ configure(region, model, options = {}) {
6722
+ const nextSystem = options.system ?? "";
6723
+ const nextCwd = options.cwd;
6724
+ let reset = false;
6725
+ if (this.acp !== null && (nextSystem !== this.systemPrompt || region !== this.region || nextCwd !== this.requestedCwd)) {
6726
+ this.dropAcp();
6727
+ this.fedMessages = void 0;
6728
+ reset = true;
6729
+ }
6730
+ this.region = region;
6731
+ this.model = model;
6732
+ this.effort = options.effort;
6733
+ this.systemPrompt = nextSystem;
6734
+ this.requestedCwd = nextCwd;
6735
+ return reset;
6736
+ }
6737
+ /** Register the host tools this session's MCP server advertises. */
6738
+ ensureTools(tools) {
6739
+ this.toolSchemas = tools;
6740
+ this.bridge.setTools(tools);
6741
+ }
6742
+ /** Hand the host's tool results to parked handlers. */
6743
+ deliverToolResults(tail) {
6744
+ let freshUserTurn = false;
6745
+ for (const message of tail) {
6746
+ if (message.role === "user") {
6747
+ freshUserTurn = true;
6748
+ continue;
6749
+ }
6750
+ if (message.role !== "tool") continue;
6751
+ const callId = message.toolCallId === void 0 ? "" : String(message.toolCallId);
6752
+ const pending = this.pending.get(callId);
6753
+ if (pending === void 0) continue;
6754
+ clearTimeout(pending.timer);
6755
+ this.pending.delete(callId);
6756
+ pending.resolve({
6757
+ ...renderToolResult(message.content),
6758
+ ...message.isError === true ? { isError: true } : {}
6759
+ });
6760
+ }
6761
+ if (freshUserTurn && this.pending.size > 0) {
6762
+ for (const [callId, pending] of this.pending) {
6763
+ clearTimeout(pending.timer);
6764
+ pending.reject(/* @__PURE__ */ new Error("宿主开始了新的用户轮次,未返回的工具结果已取消。"));
6765
+ this.pending.delete(callId);
6766
+ }
6767
+ if (this.promptInFlight) this.acp?.cancel();
6768
+ this.awaitingToolResults = false;
6769
+ }
6770
+ }
6771
+ /** Run one harness turn. `feed` is new user content, or null for a continuation. */
6772
+ async *stream(options, feed) {
6773
+ if (this.disposed) throw new Error(`MiniMax session ${this.sessionId} was disposed`);
6774
+ if (this.activeTurn) throw new Error(`MiniMax session ${this.sessionId} already has a turn in flight`);
6775
+ this.activeTurn = true;
6776
+ const signal = options.signal;
6777
+ const turn = {
6778
+ blockIndex: 0,
6779
+ inputChars: feedTextLengthOf(feed),
6780
+ outputChars: 0,
6781
+ reasoningChars: 0
6782
+ };
6783
+ let abortRequested = false;
6784
+ let abortTimer;
6785
+ let onAbortListener;
6786
+ try {
6787
+ await this.ensureStarted();
6788
+ if (!this.promptInFlight) {
6789
+ await this.startPrompt(feed ?? "");
6790
+ this.awaitingToolResults = false;
6791
+ } else if (feed !== null && feedTextLengthOf(feed) > 0 && !this.awaitingToolResults) throw new Error("MiniMax 会话正忙:上一轮尚未结束。");
6792
+ const onAbort = () => {
6793
+ abortRequested = true;
6794
+ this.acp?.cancel();
6795
+ abortTimer = setTimeout(() => {
6796
+ this.dropAcp();
6797
+ }, this.abortGraceMs);
6798
+ };
6799
+ onAbortListener = onAbort;
6800
+ signal?.addEventListener("abort", onAbort, { once: true });
6801
+ while (true) {
6802
+ if (signal?.aborted === true) {
6803
+ if (!abortRequested) onAbort();
6804
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话被宿主中止。"));
6805
+ this.promptInFlight = false;
6806
+ this.awaitingToolResults = false;
6807
+ yield* this.finish(turn, {
6808
+ kind: "aborted",
6809
+ failure: {
6810
+ message: "MiniMax turn aborted by host",
6811
+ code: "ABORTED"
6812
+ }
6813
+ });
6814
+ return;
6815
+ }
6816
+ const event = await raceAbort(this.events.next(), signal);
6817
+ if (event === void 0) {
6818
+ if (abortRequested) continue;
6819
+ yield* this.finish(turn, {
6820
+ kind: "error",
6821
+ failure: {
6822
+ message: "MiniMax ACP stream closed",
6823
+ code: "STREAM_CLOSED"
6824
+ }
6825
+ });
6826
+ return;
6827
+ }
6828
+ switch (event.kind) {
6829
+ case "text":
6830
+ turn.outputChars += event.text.length;
6831
+ if (turn.textBlock === void 0) {
6832
+ turn.textBlock = {
6833
+ index: turn.blockIndex++,
6834
+ text: ""
6835
+ };
6836
+ yield {
6837
+ type: "block-start",
6838
+ index: turn.textBlock.index,
6839
+ blockType: "text"
6840
+ };
6841
+ }
6842
+ turn.textBlock.text += event.text;
6843
+ yield {
6844
+ type: "text-delta",
6845
+ index: turn.textBlock.index,
6846
+ text: event.text
6847
+ };
6848
+ continue;
6849
+ case "reasoning":
6850
+ turn.reasoningChars += event.text.length;
6851
+ if (turn.reasoningBlock === void 0) {
6852
+ turn.reasoningBlock = {
6853
+ index: turn.blockIndex++,
6854
+ text: ""
6855
+ };
6856
+ yield {
6857
+ type: "block-start",
6858
+ index: turn.reasoningBlock.index,
6859
+ blockType: "reasoning"
6860
+ };
6861
+ }
6862
+ turn.reasoningBlock.text += event.text;
6863
+ yield {
6864
+ type: "reasoning-delta",
6865
+ index: turn.reasoningBlock.index,
6866
+ text: event.text
6867
+ };
6868
+ continue;
6869
+ case "usage":
6870
+ if (event.size > 0) this.observedContextWindow = event.size;
6871
+ if (event.used > 0) turn.contextUsed = event.used;
6872
+ continue;
6873
+ case "host-tool": {
6874
+ if (turn.textBlock !== void 0) {
6875
+ yield {
6876
+ type: "block-end",
6877
+ index: turn.textBlock.index,
6878
+ block: {
6879
+ type: "text",
6880
+ text: turn.textBlock.text
6881
+ }
6882
+ };
6883
+ turn.textBlock = void 0;
6884
+ }
6885
+ if (turn.reasoningBlock !== void 0) {
6886
+ yield {
6887
+ type: "block-end",
6888
+ index: turn.reasoningBlock.index,
6889
+ block: {
6890
+ type: "reasoning",
6891
+ text: turn.reasoningBlock.text
6892
+ }
6893
+ };
6894
+ turn.reasoningBlock = void 0;
6895
+ }
6896
+ const index = turn.blockIndex++;
6897
+ yield {
6898
+ type: "block-start",
6899
+ index,
6900
+ blockType: "tool-call"
6901
+ };
6902
+ const args = JSON.stringify(event.args);
6903
+ yield {
6904
+ type: "tool-call-delta",
6905
+ index,
6906
+ id: ToolCallId(event.callId),
6907
+ name: event.name,
6908
+ argumentsDelta: args
6909
+ };
6910
+ yield {
6911
+ type: "block-end",
6912
+ index,
6913
+ block: {
6914
+ type: "tool-call",
6915
+ id: ToolCallId(event.callId),
6916
+ name: event.name,
6917
+ arguments: args
6918
+ }
6919
+ };
6920
+ this.awaitingToolResults = true;
6921
+ yield* this.finish(turn, { kind: "tool-calls" });
6922
+ return;
6923
+ }
6924
+ case "native-tool":
6925
+ if (!this.cancelSent) {
6926
+ this.cancelSent = true;
6927
+ this.nativeViolation = true;
6928
+ await this.acp?.cancel();
6929
+ }
6930
+ continue;
6931
+ case "prompt-done":
6932
+ this.promptInFlight = false;
6933
+ this.cancelSent = false;
6934
+ if (abortRequested) {
6935
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话被宿主中止。"));
6936
+ yield* this.finish(turn, {
6937
+ kind: "aborted",
6938
+ failure: {
6939
+ message: "MiniMax turn aborted by host",
6940
+ code: "ABORTED"
6941
+ }
6942
+ });
6943
+ return;
6944
+ }
6945
+ if (this.nativeViolation) {
6946
+ this.nativeViolation = false;
6947
+ this.correctionCount += 1;
6948
+ if (this.correctionCount <= MAX_NATIVE_TOOL_RETRIES) {
6949
+ await new Promise((resolve) => setTimeout(resolve, 350));
6950
+ try {
6951
+ await this.startPrompt(NATIVE_TOOL_CORRECTION);
6952
+ this.awaitingToolResults = false;
6953
+ continue;
6954
+ } catch (error) {
6955
+ yield* this.finish(turn, {
6956
+ kind: "error",
6957
+ failure: {
6958
+ message: `MiniMax 内置工具不可用,重试失败:${error instanceof Error ? error.message : String(error)}`,
6959
+ code: "BACKEND_TURN_ERROR"
6960
+ }
6961
+ });
6962
+ return;
6963
+ }
6964
+ }
6965
+ yield* this.finish(turn, {
6966
+ kind: "error",
6967
+ failure: {
6968
+ message: "MiniMax 连续尝试调用内置工具。本插件只允许宿主 MCP 工具,已取消本轮。",
6969
+ code: "BACKEND_TURN_ERROR"
6970
+ }
6971
+ });
6972
+ return;
6973
+ }
6974
+ if (event.stopReason === "end_turn" || event.stopReason === "max_tokens") {
6975
+ yield* this.finish(turn, event.stopReason === "max_tokens" ? { kind: "max-tokens" } : { kind: "stop" });
6976
+ return;
6977
+ }
6978
+ if (event.stopReason === "cancelled") {
6979
+ yield* this.finish(turn, {
6980
+ kind: "aborted",
6981
+ failure: {
6982
+ message: "MiniMax turn cancelled",
6983
+ code: "ABORTED"
6984
+ }
6985
+ });
6986
+ return;
6987
+ }
6988
+ yield* this.finish(turn, { kind: "stop" });
6989
+ return;
6990
+ case "prompt-error":
6991
+ this.promptInFlight = false;
6992
+ this.cancelSent = false;
6993
+ yield* this.finish(turn, {
6994
+ kind: "error",
6995
+ failure: {
6996
+ message: event.error.message,
6997
+ code: "BACKEND_TURN_ERROR"
6998
+ }
6999
+ });
7000
+ return;
7001
+ case "closed":
7002
+ this.promptInFlight = false;
7003
+ yield* this.finish(turn, {
7004
+ kind: "error",
7005
+ failure: {
7006
+ message: event.error.message,
7007
+ code: "BACKEND_TURN_ERROR"
7008
+ }
7009
+ });
7010
+ return;
7011
+ }
7012
+ }
7013
+ } finally {
7014
+ if (onAbortListener !== void 0) signal?.removeEventListener("abort", onAbortListener);
7015
+ if (abortTimer !== void 0) clearTimeout(abortTimer);
7016
+ this.activeTurn = false;
7017
+ }
7018
+ }
7019
+ /** Tear the ACP process down; parked handlers settle with a cancellation. */
7020
+ close() {
7021
+ if (this.disposed) return;
7022
+ this.disposed = true;
7023
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话已关闭。"));
7024
+ this.events.close();
7025
+ const workspace = this.workspace;
7026
+ const owned = this.ownsWorkspace;
7027
+ this.workspace = void 0;
7028
+ this.ownsWorkspace = false;
7029
+ this.dropAcp().finally(() => {
7030
+ if (workspace === void 0 || !owned) return;
7031
+ try {
7032
+ rmSync(workspace, {
7033
+ recursive: true,
7034
+ force: true
7035
+ });
7036
+ } catch {}
7037
+ });
7038
+ }
7039
+ async ensureStarted() {
7040
+ if (this.acp !== null) return;
7041
+ await this.mcpServer.start();
7042
+ if (this.workspace === void 0) {
7043
+ if (this.requestedCwd !== void 0) {
7044
+ this.workspace = this.requestedCwd;
7045
+ this.ownsWorkspace = false;
7046
+ } else {
7047
+ this.workspace = mkdtempSync(join(tmpdir(), "dsh-minimax-session-"));
7048
+ this.ownsWorkspace = true;
7049
+ }
7050
+ }
7051
+ this.bridge.setTools(this.toolSchemas);
7052
+ const registered = this.mcpServer.register(this.bridge);
7053
+ this.mcpToken = registered.token;
7054
+ const system = `${this.systemPrompt.trim()}\n\n${HOST_TOOL_POLICY}\n`;
7055
+ const acp = new MinimaxAcp({
7056
+ region: this.region,
7057
+ cwd: this.workspace,
7058
+ systemPrompt: system,
7059
+ mcpUrl: registered.url,
7060
+ mcpToken: registered.token,
7061
+ onUpdate: (update) => {
7062
+ this.events.push(update);
7063
+ },
7064
+ onExit: (error) => {
7065
+ this.events.push({
7066
+ kind: "closed",
7067
+ error
7068
+ });
7069
+ }
7070
+ });
7071
+ try {
7072
+ await acp.start();
7073
+ await acp.selectModel(this.model, this.effort);
7074
+ this.acp = acp;
7075
+ } catch (error) {
7076
+ await acp.close();
7077
+ this.mcpServer.unregister(registered.token);
7078
+ this.mcpToken = void 0;
7079
+ throw error;
7080
+ }
7081
+ }
7082
+ async startPrompt(prompt) {
7083
+ const acp = this.acp;
7084
+ if (acp === null) throw new Error("MiniMax ACP 尚未启动。");
7085
+ this.promptInFlight = true;
7086
+ this.cancelSent = false;
7087
+ this.launchPrompt(acp, prompt, 0);
7088
+ }
7089
+ /**
7090
+ * Start one ACP prompt and publish its outcome.
7091
+ *
7092
+ * Cancelling a turn makes the next `session/prompt` fail with "Session
7093
+ * already has an active Turn" for a short while even though the cancelled
7094
+ * prompt has already resolved. That race is routine here: the native-tool
7095
+ * correction is sent immediately after such a cancel, so it is retried with
7096
+ * a short backoff instead of being reported as a failed turn.
7097
+ */
7098
+ async launchPrompt(acp, prompt, attempt) {
7099
+ try {
7100
+ const response = await acp.prompt(prompt);
7101
+ this.events.push({
7102
+ kind: "prompt-done",
7103
+ stopReason: response.stopReason
7104
+ });
7105
+ } catch (error) {
7106
+ const message = error instanceof Error ? error.message : String(error);
7107
+ if (/401 token is required/i.test(message)) {
7108
+ minimaxRegionBlocked(this.region, { fresh: true });
7109
+ const hint = minimaxRegionBlockedCached(this.region) ? minimaxRegionBlockMessage(this.region) : this.region === "global" ? "MiniMax 国际站拒绝了本机连接(401 token is required)。通常是本机网络 IP 不在国际站服务区域;请检查网络后重试,或切换到国内站。" : "MiniMax 国内站拒绝了本机连接(401 token is required)。请检查网络或重新登录后重试。";
7110
+ this.events.push({
7111
+ kind: "prompt-error",
7112
+ error: new Error(hint)
7113
+ });
7114
+ return;
7115
+ }
7116
+ if (/active Turn|already has an active/i.test(message) && attempt < 4 && !this.disposed && this.acp === acp) {
7117
+ await new Promise((resolve) => setTimeout(resolve, 200 * 2 ** attempt));
7118
+ if (!this.disposed && this.acp === acp) {
7119
+ await this.launchPrompt(acp, prompt, attempt + 1);
7120
+ return;
7121
+ }
7122
+ }
7123
+ this.events.push({
7124
+ kind: "prompt-error",
7125
+ error: error instanceof Error ? error : new Error(message)
7126
+ });
7127
+ }
7128
+ }
7129
+ async dropAcp() {
7130
+ const acp = this.acp;
7131
+ this.acp = null;
7132
+ this.promptInFlight = false;
7133
+ this.awaitingToolResults = false;
7134
+ if (acp !== null) await acp.close();
7135
+ if (this.mcpToken !== void 0) {
7136
+ this.mcpServer.unregister(this.mcpToken);
7137
+ this.mcpToken = void 0;
7138
+ }
7139
+ }
7140
+ async handleToolCall(name, args) {
7141
+ if (this.disposed) return {
7142
+ content: [{
7143
+ type: "text",
7144
+ text: "MiniMax 会话已关闭。"
7145
+ }],
7146
+ isError: true
7147
+ };
7148
+ const callId = `mm-${this.callNonce}-${++this.toolCounter}`;
7149
+ const result = new Promise((resolve, reject) => {
7150
+ const timer = setTimeout(() => {
7151
+ this.pending.delete(callId);
7152
+ reject(/* @__PURE__ */ new Error(`宿主工具 ${name} 在 ${Math.round(this.toolResultTimeoutMs / 1e3)} 秒内没有返回结果。`));
7153
+ }, this.toolResultTimeoutMs);
7154
+ this.pending.set(callId, {
7155
+ resolve,
7156
+ reject,
7157
+ timer
7158
+ });
7159
+ });
7160
+ this.events.push({
7161
+ kind: "host-tool",
7162
+ callId,
7163
+ name,
7164
+ args
7165
+ });
7166
+ try {
7167
+ return await result;
7168
+ } catch (error) {
7169
+ return {
7170
+ content: [{
7171
+ type: "text",
7172
+ text: error instanceof Error ? error.message : String(error)
7173
+ }],
7174
+ isError: true
7175
+ };
7176
+ }
7177
+ }
7178
+ async *finish(turn, reason) {
7179
+ if (turn.textBlock !== void 0) yield {
7180
+ type: "block-end",
7181
+ index: turn.textBlock.index,
7182
+ block: {
7183
+ type: "text",
7184
+ text: turn.textBlock.text
7185
+ }
7186
+ };
7187
+ if (turn.reasoningBlock !== void 0) yield {
7188
+ type: "block-end",
7189
+ index: turn.reasoningBlock.index,
7190
+ block: {
7191
+ type: "reasoning",
7192
+ text: turn.reasoningBlock.text
7193
+ }
7194
+ };
7195
+ yield {
7196
+ type: "usage",
7197
+ usage: minimaxTurnUsage({
7198
+ ...turn.contextUsed === void 0 ? {} : { contextUsed: turn.contextUsed },
7199
+ inputChars: turn.inputChars,
7200
+ outputChars: turn.outputChars,
7201
+ reasoningChars: turn.reasoningChars
7202
+ })
7203
+ };
7204
+ yield {
7205
+ type: "finish",
7206
+ reason
7207
+ };
7208
+ if (reason.kind !== "tool-calls" && !this.disposed) this.correctionCount = 0;
7209
+ }
7210
+ };
7211
+ /** Reject every parked handler with the same reason. */
7212
+ function rejectPending(pending, error) {
7213
+ for (const [callId, entry] of pending) {
7214
+ clearTimeout(entry.timer);
7215
+ entry.reject(error);
7216
+ pending.delete(callId);
7217
+ }
7218
+ }
7219
+ /** Wait for a promise, or give up after `ms`. */
7220
+ function withTimeout(promise, ms, label) {
7221
+ return new Promise((resolve, reject) => {
7222
+ const timer = setTimeout(() => {
7223
+ reject(/* @__PURE__ */ new Error(`${label} timed out after ${ms}ms`));
7224
+ }, ms);
7225
+ promise.then((value) => {
7226
+ clearTimeout(timer);
7227
+ resolve(value);
7228
+ }, (error) => {
7229
+ clearTimeout(timer);
7230
+ reject(error);
7231
+ });
7232
+ });
7233
+ }
7234
+ /** Await a queue read, giving up when the harness aborts the turn. */
7235
+ function raceAbort(promise, signal) {
7236
+ if (signal === void 0) return promise;
7237
+ if (signal.aborted) return Promise.resolve(void 0);
7238
+ return new Promise((resolve, reject) => {
7239
+ const onAbort = () => {
7240
+ signal.removeEventListener("abort", onAbort);
7241
+ resolve(void 0);
7242
+ };
7243
+ signal.addEventListener("abort", onAbort, { once: true });
7244
+ promise.then((value) => {
7245
+ signal.removeEventListener("abort", onAbort);
7246
+ resolve(value);
7247
+ }, (error) => {
7248
+ signal.removeEventListener("abort", onAbort);
7249
+ reject(error);
7250
+ });
7251
+ });
7252
+ }
7253
+ /** Warm session pool, keyed by harness session id. */
7254
+ var MinimaxSessionManager = class {
7255
+ maxSessions;
7256
+ mcpServer;
7257
+ runtime;
7258
+ sessions = /* @__PURE__ */ new Map();
7259
+ constructor(maxSessions, mcpServer, runtime = {}) {
7260
+ this.maxSessions = maxSessions;
7261
+ this.mcpServer = mcpServer;
7262
+ this.runtime = runtime;
7263
+ }
7264
+ forSession(sessionId, region, model) {
7265
+ const existing = this.sessions.get(sessionId);
7266
+ if (existing !== void 0) {
7267
+ if (existing.region !== region) {
7268
+ existing.session.close();
7269
+ this.sessions.delete(sessionId);
7270
+ } else {
7271
+ this.sessions.delete(sessionId);
7272
+ this.sessions.set(sessionId, existing);
7273
+ return existing.session;
7274
+ }
7275
+ }
7276
+ const session = new MinimaxSession(sessionId, model, this.mcpServer, this.runtime);
7277
+ this.sessions.set(sessionId, {
7278
+ session,
7279
+ region
7280
+ });
7281
+ const cap = readLive(this.maxSessions, 8);
7282
+ while (this.sessions.size > cap) {
7283
+ const oldest = this.sessions.keys().next();
7284
+ if (oldest.done === true) break;
7285
+ const victim = this.sessions.get(oldest.value);
7286
+ this.sessions.delete(oldest.value);
7287
+ victim?.session.close();
7288
+ }
7289
+ return session;
7290
+ }
7291
+ dispose(sessionId) {
7292
+ const entry = this.sessions.get(sessionId);
7293
+ if (entry === void 0) return;
7294
+ this.sessions.delete(sessionId);
7295
+ entry.session.close();
7296
+ }
7297
+ closeAll() {
7298
+ for (const entry of this.sessions.values()) entry.session.close();
7299
+ this.sessions.clear();
7300
+ }
7301
+ };
7302
+ /** A one-shot turn, used for titles and compaction summaries. */
7303
+ async function minimaxColdStream(region, prompt, model, options) {
7304
+ const chunks = [];
7305
+ let text = "";
7306
+ const cwd = mkdtempSync(join(tmpdir(), "dsh-minimax-cold-"));
7307
+ const acp = new MinimaxAcp({
7308
+ region,
7309
+ cwd,
7310
+ systemPrompt: "You are a concise helper used only for titles and summaries. Do not call any tool.",
7311
+ disableTools: true,
7312
+ onUpdate: (update) => {
7313
+ if (update.kind === "text") text += update.text;
7314
+ }
7315
+ });
7316
+ const signal = options.signal;
7317
+ const onAbort = () => {
7318
+ acp.cancel();
7319
+ };
7320
+ signal?.addEventListener("abort", onAbort, { once: true });
7321
+ try {
7322
+ await acp.start();
7323
+ if (model !== void 0) await acp.selectModel(model);
7324
+ const response = await acp.prompt(prompt);
7325
+ if (signal?.aborted === true || response.stopReason === "cancelled") {
7326
+ chunks.push({
7327
+ type: "finish",
7328
+ reason: {
7329
+ kind: "aborted",
7330
+ failure: {
7331
+ message: "aborted by host",
7332
+ code: "ABORTED"
7333
+ }
7334
+ }
7335
+ });
7336
+ return chunks;
7337
+ }
7338
+ if (text.trim().length === 0) {
7339
+ chunks.push({
7340
+ type: "finish",
7341
+ reason: {
7342
+ kind: "error",
7343
+ failure: {
7344
+ message: "MiniMax side-channel returned no content",
7345
+ code: EMPTY_RESPONSE_CODE
7346
+ }
7347
+ }
7348
+ });
7349
+ return chunks;
7350
+ }
7351
+ chunks.push({
7352
+ type: "block-start",
7353
+ index: 0,
7354
+ blockType: "text"
7355
+ });
7356
+ for (let index = 0; index < text.length; index += 192) chunks.push({
7357
+ type: "text-delta",
7358
+ index: 0,
7359
+ text: text.slice(index, index + 192)
7360
+ });
7361
+ chunks.push({
7362
+ type: "block-end",
7363
+ index: 0,
7364
+ block: {
7365
+ type: "text",
7366
+ text
7367
+ }
7368
+ });
7369
+ chunks.push({
7370
+ type: "usage",
7371
+ usage: minimaxTurnUsage({
7372
+ inputChars: prompt.length,
7373
+ outputChars: text.length,
7374
+ reasoningChars: 0
7375
+ })
7376
+ });
7377
+ chunks.push({
7378
+ type: "finish",
7379
+ reason: { kind: "stop" }
7380
+ });
7381
+ return chunks;
7382
+ } finally {
7383
+ signal?.removeEventListener("abort", onAbort);
7384
+ await acp.close();
7385
+ try {
7386
+ rmSync(cwd, {
7387
+ recursive: true,
7388
+ force: true
7389
+ });
7390
+ } catch {}
7391
+ }
7392
+ }
7393
+ //#endregion
7394
+ //#region src/minimax-adapter.ts
7395
+ /**
7396
+ * `MinimaxAdapter`: route the harness LLM seam onto a MiniMax Code account.
7397
+ *
7398
+ * The ACP agent owns the conversation; this adapter decides what new text to
7399
+ * send, which model/effort to select, and how the ACP tool calls map onto the
7400
+ * harness's tool seam. One provider serves both login regions; the region is a
7401
+ * live config choice and every ACP process is pinned to it.
7402
+ *
7403
+ * @module dsh-agent-sdk-bridge/minimax-adapter
7404
+ */
7405
+ /** The MiniMax Code provider route. */
7406
+ const MINIMAX_PROVIDER = "minimax-acp";
7407
+ const NO_MODELS = [];
7408
+ const NO_ALIASES = {};
7409
+ /** Map a harness-side id onto an ACP model value. */
7410
+ function resolveMinimaxModelId(model, aliases = {}) {
7411
+ const configured = aliases[model] ?? aliases[model.toLowerCase()];
7412
+ if (configured !== void 0 && configured.length > 0) return configured;
7413
+ return model.startsWith("minimax-") ? model.slice(8) : model;
7414
+ }
7415
+ function modelInfo(provider, model) {
7416
+ return {
7417
+ provider,
7418
+ id: model.id,
7419
+ name: model.name,
7420
+ ...model.description === void 0 ? {} : { description: model.description },
7421
+ inputModalities: model.vision ? ["text", "image"] : ["text"]
7422
+ };
7423
+ }
7424
+ /** The MiniMax Code-backed adapter. */
7425
+ var MinimaxAdapter = class extends LlmAdapter {
7426
+ options;
7427
+ sessions;
7428
+ catalog;
7429
+ auth = new MinimaxAuth();
7430
+ mcpServer = new MinimaxMcpServer();
7431
+ disabledCache = /* @__PURE__ */ new Map();
7432
+ constructor(options = {}) {
7433
+ super();
7434
+ this.options = options;
7435
+ this.sessions = new MinimaxSessionManager(options.maxSessions ?? 8, this.mcpServer, {
7436
+ toolResultTimeoutMs: options.toolResultTimeoutMs,
7437
+ abortGraceMs: options.abortGraceMs
7438
+ });
7439
+ this.catalog = new MinimaxCatalog(options.region ?? (() => "cn"), options.modelCacheTtlMs ?? 3e5, options.catalogFetchTimeoutMs ?? 3e4);
7440
+ }
7441
+ get region() {
7442
+ return readLive(this.options.region ?? (() => "cn"), "cn");
7443
+ }
7444
+ disabledFor(region) {
7445
+ const source = this.options.disabledModels?.(region) ?? NO_MODELS;
7446
+ const key = source.join("\0");
7447
+ const cached = this.disabledCache.get(region);
7448
+ if (cached?.key === key) return cached.set;
7449
+ const set = new Set(source);
7450
+ this.disabledCache.set(region, {
7451
+ key,
7452
+ set
7453
+ });
7454
+ return set;
7455
+ }
7456
+ get aliases() {
7457
+ return readLive(this.options.modelAliases, NO_ALIASES);
7458
+ }
7459
+ get displayName() {
7460
+ return readLive(this.options.displayName, "MiniMax Code");
7461
+ }
7462
+ providerInfo(provider) {
7463
+ return {
7464
+ id: provider,
7465
+ name: this.displayName
7466
+ };
7467
+ }
7468
+ /** The live catalog, unfiltered (the page must show switched-off models). */
7469
+ async describeCatalog(region = this.region) {
7470
+ if (!this.isSignedIn(region)) return [];
7471
+ if (await minimaxRegionBlocked(region)) return [];
7472
+ return this.catalog.models(region);
7473
+ }
7474
+ /** Whether the region's endpoints are refusing this machine's network. */
7475
+ regionBlocked(region = this.region) {
7476
+ return minimaxRegionBlockedCached(region);
7477
+ }
7478
+ /** Whether the selected (or given) region has a stored login. */
7479
+ isSignedIn(region = this.region) {
7480
+ return this.auth.status(region).signedIn || minimaxSignedIn(region);
7481
+ }
7482
+ /** Why the last catalog read failed, for the page's guidance. */
7483
+ catalogError(region = this.region) {
7484
+ if (resolveMinimaxCli() === void 0) return "未安装 MiniMax Code CLI(mcode)。请先安装后再登录。";
7485
+ if (minimaxRegionBlockedCached(region)) return minimaxRegionBlockMessage(region);
7486
+ if (!this.isSignedIn(region)) return "请先登录 MiniMax Code,登录后才会读取并显示模型目录。";
7487
+ return this.catalog.error(region);
7488
+ }
7489
+ /**
7490
+ * Drop the cached catalog and the region verdict behind it.
7491
+ *
7492
+ * The page calls this with `fresh=1` on a region switch, which is exactly
7493
+ * when the network may have changed; keeping a 30-second "blocked" verdict
7494
+ * would hide the catalog the switch was meant to reveal.
7495
+ */
7496
+ invalidateCatalog(region) {
7497
+ this.catalog.invalidate(region);
7498
+ invalidateMinimaxRegionAccess(region);
7499
+ }
7500
+ /** Login status, installer state and (when signed in) the account's quota. */
7501
+ async usageInfo(fresh = false, region) {
7502
+ const target = region ?? this.region;
7503
+ const installed = resolveMinimaxCli() !== void 0;
7504
+ const status = this.auth.status(target);
7505
+ if (!(status.signedIn || minimaxSignedIn(target))) return {
7506
+ at: Date.now(),
7507
+ region: target,
7508
+ signedIn: false,
7509
+ installed,
7510
+ ...installed ? {} : { error: "未安装 MiniMax Code CLI(mcode)。" },
7511
+ ...status.error === void 0 ? {} : { error: status.error }
7512
+ };
7513
+ const snapshot = await minimaxUsage(target, { fresh });
7514
+ return {
7515
+ ...snapshot,
7516
+ signedIn: true,
7517
+ installed,
7518
+ ...snapshot.error !== void 0 || status.error === void 0 ? {} : { error: status.error }
7519
+ };
7520
+ }
7521
+ /** Drop cached quota readings and the region verdict (login, logout, CLI). */
7522
+ invalidateUsage(region) {
7523
+ invalidateMinimaxUsage(region);
7524
+ invalidateMinimaxRegionAccess(region);
7525
+ }
7526
+ /** Login progress for one region; the page polls this. */
7527
+ authStatus(region) {
7528
+ return this.auth.status(region);
7529
+ }
7530
+ startLogin(region) {
7531
+ return this.auth.start(region, (ok) => {
7532
+ if (!ok) return;
7533
+ this.sessions.closeAll();
7534
+ this.invalidateCatalog(region);
7535
+ this.invalidateUsage(region);
7536
+ invalidateMinimaxRegionAccess(region);
7537
+ });
7538
+ }
7539
+ async logout(region) {
7540
+ const result = await this.auth.logout(region);
7541
+ this.sessions.closeAll();
7542
+ this.invalidateCatalog(region);
7543
+ this.invalidateUsage(region);
7544
+ invalidateMinimaxRegionAccess(region);
7545
+ return result;
7546
+ }
7547
+ isModelDisabled(id, region = this.region) {
7548
+ return this.disabledFor(region).has(id);
7549
+ }
7550
+ contextWindowFor(id, region = this.region) {
7551
+ return this.options.modelContextWindows?.(region)[id];
7552
+ }
7553
+ async listModels(provider) {
7554
+ const region = this.region;
7555
+ if (!this.isSignedIn(region)) return [];
7556
+ if (await minimaxRegionBlocked(region)) return [];
7557
+ const models = await this.catalog.models(region);
7558
+ const disabled = this.disabledFor(region);
7559
+ return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo(provider, model));
7560
+ }
7561
+ async resolveModel(provider, model) {
7562
+ const region = this.region;
7563
+ const target = resolveMinimaxModelId(model, this.aliases);
7564
+ const live = (await this.catalog.models(region)).find((entry) => entry.id === target);
7565
+ if (live !== void 0) {
7566
+ const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, live.reasoning);
7567
+ return {
7568
+ provider,
7569
+ id: model,
7570
+ name: live.name,
7571
+ ...live.description === void 0 ? {} : { description: live.description },
7572
+ inputModalities: live.vision ? ["text", "image"] : ["text"],
7573
+ context: { contextWindow: this.contextWindowFor(target, region) ?? live.defaultContextWindow },
7574
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
7575
+ ...reasoning === void 0 ? {} : { reasoning }
7576
+ };
7577
+ }
7578
+ const reasoning = reasoningInfo(void 0, readLiveOptional(this.options.defaultReasoningEffort), true);
7579
+ return {
7580
+ provider,
7581
+ id: model,
7582
+ name: model,
7583
+ inputModalities: ["text"],
7584
+ context: { contextWindow: this.contextWindowFor(target, region) ?? 512e3 },
7585
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
7586
+ ...reasoning === void 0 ? {} : { reasoning }
7587
+ };
7588
+ }
7589
+ async prepareCall(provider, model, signal) {
7590
+ return {
7591
+ model: await this.resolveModel(provider, model),
7592
+ stream: (options) => this.dispatch(options)
7593
+ };
7594
+ }
7595
+ async *stream(options) {
7596
+ yield* this.dispatch(options);
7597
+ }
7598
+ async *dispatch(options) {
7599
+ const region = this.region;
7600
+ if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "MiniMax 国内站" : "MiniMax 国际站"}尚未登录,请先在设置 → MiniMax Code 中登录。`);
7601
+ if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
7602
+ const model = resolveMinimaxModelId(options.model, this.aliases);
7603
+ if (options.sessionId === void 0 || options.purpose !== void 0) {
7604
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages)) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
7605
+ for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
7606
+ return;
7607
+ }
7608
+ const sessionId = String(options.sessionId);
7609
+ const effort = options.reasoningEffort ?? readLiveOptional(this.options.defaultReasoningEffort);
7610
+ let session = this.sessions.forSession(sessionId, region, model);
7611
+ if (session.fedMessages === void 0) {
7612
+ yield* this.firstTurn(session, options, region, model, effort);
7613
+ return;
7614
+ }
7615
+ const tail = options.messages.slice(session.fedMessages.length);
7616
+ session.deliverToolResults(tail);
7617
+ const plan = planContinuation(session.fedMessages, options.messages);
7618
+ if (plan.rebuild) {
7619
+ this.sessions.dispose(sessionId);
7620
+ session = this.sessions.forSession(sessionId, region, model);
7621
+ yield* this.firstTurn(session, options, region, model, effort);
7622
+ return;
7623
+ }
7624
+ if (plan.feed !== null && session.busy) {
7625
+ this.sessions.dispose(sessionId);
7626
+ session = this.sessions.forSession(sessionId, region, model);
7627
+ yield* this.firstTurn(session, options, region, model, effort);
7628
+ return;
7629
+ }
7630
+ if (session.configure(region, model, {
7631
+ effort,
7632
+ system: options.system,
7633
+ cwd: this.cwdOf(options)
7634
+ }) || plan.feed === null && !session.busy) {
7635
+ this.sessions.dispose(sessionId);
7636
+ session = this.sessions.forSession(sessionId, region, model);
7637
+ yield* this.firstTurn(session, options, region, model, effort);
7638
+ return;
7639
+ }
7640
+ session.ensureTools(options.tools ?? []);
7641
+ session.fedMessages = options.messages;
7642
+ session.fedSystem = options.system;
7643
+ const vision = await this.modelVision(model, region);
7644
+ const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, vision, options.signal);
7645
+ yield* session.stream(options, feed);
7646
+ }
7647
+ async *firstTurn(session, options, region, model, effort) {
7648
+ session.configure(region, model, {
7649
+ effort,
7650
+ system: options.system,
7651
+ cwd: this.cwdOf(options)
7652
+ });
7653
+ session.ensureTools(options.tools ?? []);
7654
+ session.fedMessages = options.messages;
7655
+ session.fedSystem = options.system;
7656
+ const vision = await this.modelVision(model, region);
7657
+ const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages), vision, options.signal);
7658
+ yield* session.stream(options, feed);
7659
+ }
7660
+ /** Whether the resolved model accepts images (drives whether pixels are sent). */
7661
+ async modelVision(model, region) {
7662
+ const target = resolveMinimaxModelId(model, this.aliases);
7663
+ return (await this.catalog.models(region).catch(() => [])).find((entry) => entry.id === target)?.vision === true;
7664
+ }
7665
+ /**
7666
+ * Turn a feed into what one ACP prompt carries.
7667
+ *
7668
+ * A text-only feed stays a plain string (the historical shape). A feed with
7669
+ * readable images becomes ACP content blocks, because an image block is the
7670
+ * only thing the agent receives as pixels. An image the host could not read
7671
+ * keeps its handle text, so it degrades one part instead of failing the turn.
7672
+ */
7673
+ async buildFeed(feed, vision, signal) {
7674
+ if (typeof feed === "string") return feed;
7675
+ if (!vision) return feedToText(feed);
7676
+ const images = /* @__PURE__ */ new Map();
7677
+ const readImage = this.options.readImage;
7678
+ if (readImage !== void 0) for (const ref of feedImageRefs(feed)) {
7679
+ const key = String(ref.attachmentId);
7680
+ if (images.has(key)) continue;
7681
+ try {
7682
+ const image = await readImage(ref, signal);
7683
+ if (image !== void 0) images.set(key, {
7684
+ data: Buffer.from(image.bytes).toString("base64"),
7685
+ mediaType: image.mediaType
7686
+ });
7687
+ } catch {}
7688
+ }
7689
+ const parts = resolvedFeedParts(feed, images);
7690
+ if (!parts.some((part) => part.type !== "text")) return parts.map((part) => part.type === "text" ? part.text : "").join("\n\n");
7691
+ const content = [];
7692
+ for (const part of parts) {
7693
+ if (part.type === "text") {
7694
+ content.push({
7695
+ type: "text",
7696
+ text: part.text
7697
+ });
7698
+ continue;
7699
+ }
7700
+ if (part.type === "image-unreadable") {
7701
+ content.push({
7702
+ type: "text",
7703
+ text: textOnlyImageText(part.attachment)
7704
+ });
7705
+ continue;
7706
+ }
7707
+ content.push({
7708
+ type: "image",
7709
+ data: part.data,
7710
+ mimeType: part.mediaType
7711
+ });
7712
+ }
7713
+ return content;
7714
+ }
7715
+ cwdOf(options) {
7716
+ return options.cwd;
7717
+ }
7718
+ close() {
7719
+ this.sessions.closeAll();
7720
+ this.mcpServer.close();
7721
+ this.auth.stop();
7722
+ }
7723
+ };
7724
+ //#endregion
7725
+ //#region src/setup.ts
7726
+ /**
7727
+ * Runs the bundled Windows helper that installs and signs into a Qoder CLI
7728
+ * (one helper per edition: `qoderclicn` for CN, `qodercli` for international).
7729
+ *
7730
+ * The settings page cannot do this by itself: a browser has no way to start a
7731
+ * local process, and the plugin's own process is the one that already talks to
7732
+ * the CLI. So the page asks this module, and this module spawns
7733
+ * {@link SCRIPT_NAME} — the same script a user can double-click — with one of
7734
+ * two fixed flags, and buffers its output so the page can show progress while
7735
+ * the browser sign-in is still open.
7736
+ *
7737
+ * Nothing user-supplied reaches the command line: the mode is an allow-list of
7738
+ * two keys mapped to two literal flags, and the script path comes from this
7739
+ * package's own layout. The helper is idempotent, so a second press re-checks
7740
+ * rather than reinstalling.
7741
+ *
7742
+ * @module dsh-agent-sdk-bridge/setup
7743
+ */
7744
+ /** File name of the CN helper, shipped under this package's `scripts/` directory. */
7745
+ const SCRIPT_NAME = "setup-qoderclicn.bat";
7746
+ /** The helper script for one edition. */
7747
+ function scriptNameOf(brand) {
7748
+ return brandProfile(brand).setupScript ?? "setup-qoderclicn.bat";
7749
+ }
7750
+ /** The one command-line flag each mode maps to. Never a user-supplied string. */
7751
+ const FLAGS = {
7752
+ configure: "--gui",
7753
+ login: "--login",
7754
+ uninstall: "--uninstall"
7755
+ };
7756
+ /** Whether a value is one of the modes the page may request. */
7757
+ function isSetupMode(value) {
7758
+ return value === "configure" || value === "login" || value === "uninstall";
7759
+ }
7760
+ /** Cap on kept output, so a chatty `npm install` cannot grow without bound. */
7761
+ const MAX_LINES = 400;
7762
+ /** The latest run per edition: the two installers may run independently. */
7763
+ const current = /* @__PURE__ */ new Map();
7764
+ /**
7765
+ * Locate one edition's helper inside this package.
7766
+ *
7767
+ * The host half is bundled to `lib/index.js`, and tests import `src/*.ts`, so
7768
+ * both layouts resolve to the same `scripts/` directory one level up.
7769
+ *
7770
+ * @param brand - which edition's script to find.
7771
+ */
7772
+ function setupScriptPath(brand = "cn") {
7773
+ const here = path.dirname(fileURLToPath(import.meta.url));
7774
+ const script = scriptNameOf(brand);
7775
+ for (const candidate of [path.resolve(here, "..", "scripts", script), path.resolve(here, "scripts", script)]) if (existsSync(candidate)) return candidate;
7776
+ }
7777
+ /** Append decoded text to a run, splitting it into displayable lines. */
7778
+ function absorb(run, chunk, done) {
7779
+ run.pending += run.decoder.decode(chunk, { stream: !done });
7780
+ const parts = run.pending.split(/\r\n|\r|\n/);
7781
+ run.pending = done ? "" : parts.pop() ?? "";
7782
+ for (const part of parts) {
7783
+ if (part.trim() === "") continue;
7784
+ run.lines.push(part);
7785
+ }
7786
+ if (done && run.pending.trim() !== "") run.lines.push(run.pending.trim());
7787
+ while (run.lines.length > MAX_LINES) {
7788
+ run.lines.shift();
7789
+ run.truncated = true;
7790
+ }
7791
+ }
7792
+ /**
7793
+ * Start one edition's helper. Only one run per edition at a time; a finished
7794
+ * one stays readable.
7795
+ *
7796
+ * @param brand - which edition to configure.
7797
+ * @param mode - the fixed flag the page may ask for.
7798
+ * @param onFinish - called once with the exit code.
7799
+ */
7800
+ function startSetup(brand, mode, onFinish) {
7801
+ const previous = current.get(brand);
7802
+ if (previous !== void 0 && previous.finishedAt === void 0) return {
7803
+ started: false,
7804
+ reason: "busy",
7805
+ error: "已经有一次配置在跑了,请等它结束。"
7806
+ };
7807
+ if (process.platform !== "win32") {
7808
+ const command = brandProfile(brand).cliCommands[0];
7809
+ return {
7810
+ started: false,
7811
+ reason: "unsupported",
7812
+ error: `一键${mode === "uninstall" ? "卸载" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
7813
+ };
7814
+ }
7815
+ const script = setupScriptPath(brand);
7816
+ if (script === void 0) return {
7817
+ started: false,
7818
+ reason: "missing-script",
7819
+ error: `插件包里没有 ${scriptNameOf(brand)},缺少 scripts/ 目录。`
7820
+ };
7821
+ const run = {
7822
+ child: void 0,
7823
+ brand,
7824
+ mode,
7825
+ startedAt: Date.now(),
7826
+ lines: [],
7827
+ pending: "",
7828
+ decoder: new TextDecoder("utf-8"),
7829
+ truncated: false
7830
+ };
7831
+ const child = spawn(process.env.ComSpec ?? "cmd.exe", [
7832
+ "/d",
7833
+ "/c",
7834
+ script,
7835
+ FLAGS[mode]
7836
+ ], {
7837
+ cwd: homedir(),
7838
+ windowsHide: true,
7839
+ stdio: [
7840
+ "ignore",
7841
+ "pipe",
7842
+ "pipe"
7843
+ ]
7844
+ });
7845
+ run.child = child;
7846
+ current.set(brand, run);
7847
+ const finish = (code) => {
7848
+ if (run.finishedAt !== void 0) return;
7849
+ run.finishedAt = Date.now();
7850
+ run.code = code;
7851
+ try {
7852
+ onFinish?.(code);
7853
+ } catch (error) {
7854
+ run.lines.push(`收尾回调失败:${error instanceof Error ? error.message : String(error)}`);
7855
+ }
7856
+ };
7857
+ child.stdout?.on("data", (chunk) => absorb(run, chunk, false));
7858
+ child.stderr?.on("data", (chunk) => absorb(run, chunk, false));
7859
+ child.on("error", (error) => {
7860
+ run.lines.push(`无法启动 ${scriptNameOf(brand)}:${error instanceof Error ? error.message : String(error)}`);
7861
+ finish(null);
7862
+ });
7863
+ child.on("close", (code) => {
7864
+ absorb(run, /* @__PURE__ */ new Uint8Array(), true);
7865
+ finish(code);
7866
+ });
7867
+ return { started: true };
7868
+ }
7869
+ /**
7870
+ * The latest run of one edition, with any not-yet-newlined tail included for
7871
+ * live display.
7872
+ *
7873
+ * @param brand - which edition's run to report.
7874
+ */
7875
+ function readSetupStatus(brand = "cn") {
7876
+ const run = current.get(brand);
7877
+ if (run === void 0) return {
7878
+ running: false,
7879
+ lines: [],
7880
+ truncated: false
7881
+ };
7882
+ const lines = run.pending.trim() === "" ? run.lines : [...run.lines, run.pending.trim()];
7883
+ return {
7884
+ running: run.finishedAt === void 0,
7885
+ mode: run.mode,
7886
+ startedAt: run.startedAt,
7887
+ ...run.finishedAt === void 0 ? {} : {
7888
+ finishedAt: run.finishedAt,
7889
+ code: run.code ?? null
7890
+ },
7891
+ lines,
7892
+ truncated: run.truncated
7893
+ };
7894
+ }
7895
+ /**
7896
+ * Abandon the running helper, if any.
7897
+ *
7898
+ * Called when the plugin is disposed. Killing `cmd.exe` does not reap the CLI it
7899
+ * already launched, but the helper's own wait is bounded, so nothing hangs on
7900
+ * the far end.
7901
+ */
7902
+ function stopSetup() {
7903
+ for (const run of current.values()) if (run.finishedAt === void 0) run.child.kill();
7904
+ }
7905
+ //#endregion
7906
+ //#region src/api.ts
7907
+ /** Route prefix this plugin owns; the client resolves it relative to the page. */
7908
+ const API_PREFIX = "/api/llm-qoder-cn";
7909
+ /** Answer one request with JSON. */
7910
+ function send(res, status, payload) {
7911
+ const body = JSON.stringify(payload);
7912
+ res.writeHead(status, {
7913
+ "content-type": "application/json; charset=utf-8",
7914
+ "cache-control": "no-store",
7915
+ "content-length": Buffer.byteLength(body)
7916
+ });
7917
+ res.end(body);
7918
+ }
7919
+ /** Build model rows for a Qoder adapter. */
7920
+ async function buildRows(adapter) {
7921
+ return (await adapter.describeCatalog()).map((entry) => {
7922
+ const override = adapter.contextWindowFor(entry.value);
7923
+ const upstream = entry.defaultContextWindow ?? (entry.availableContextWindows !== void 0 && entry.availableContextWindows.length > 0 ? Math.max(...entry.availableContextWindows) : entry.maxInputTokens) ?? 2e5;
7924
+ const choices = new Set(entry.availableContextWindows ?? []);
7925
+ choices.add(upstream);
7926
+ if (override !== void 0) choices.add(override);
7927
+ const priceFactor = priceFactorOf(entry);
7928
+ return {
7929
+ id: entry.value,
7930
+ name: entry.displayName.length > 0 ? entry.displayName : entry.value,
7931
+ ...entry.description.length > 0 ? { description: entry.description } : {},
7932
+ enabled: !adapter.isModelDisabled(entry.value),
7933
+ vision: entry.isVl === true,
7934
+ contextWindow: override ?? upstream,
7935
+ contextWindows: [...choices].sort((a, b) => a - b),
7936
+ defaultContextWindow: upstream,
7937
+ ...override === void 0 ? {} : { override },
7938
+ ...priceFactor === void 0 ? {} : { priceFactor },
4991
7939
  reasoning: entry.isReasoning !== false
4992
7940
  };
4993
7941
  });
@@ -5014,6 +7962,27 @@ async function buildCodeBuddyRows(adapter, region) {
5014
7962
  };
5015
7963
  });
5016
7964
  }
7965
+ /** Build model rows for the MiniMax adapter, for one login region. */
7966
+ async function buildMinimaxRows(adapter, region) {
7967
+ return (await adapter.describeCatalog(region)).map((entry) => {
7968
+ const override = adapter.contextWindowFor(entry.id, region);
7969
+ const choices = new Set(entry.contextWindows);
7970
+ choices.add(entry.defaultContextWindow);
7971
+ if (override !== void 0) choices.add(override);
7972
+ return {
7973
+ id: entry.id,
7974
+ name: entry.name,
7975
+ ...entry.description === void 0 ? {} : { description: entry.description },
7976
+ enabled: !adapter.isModelDisabled(entry.id, region),
7977
+ vision: entry.vision,
7978
+ contextWindow: override ?? entry.defaultContextWindow,
7979
+ contextWindows: [...choices].sort((a, b) => a - b),
7980
+ defaultContextWindow: entry.defaultContextWindow,
7981
+ ...override === void 0 ? {} : { override },
7982
+ reasoning: entry.reasoning
7983
+ };
7984
+ });
7985
+ }
5017
7986
  /** Largest request body this route accepts. */
5018
7987
  const MAX_BODY_BYTES = 2048;
5019
7988
  /** Read and parse a small JSON request body. */
@@ -5048,30 +8017,34 @@ async function handleApi(req, res, adapters) {
5048
8017
  const method = req.method ?? "GET";
5049
8018
  const queryBrand = brandFrom(url.searchParams.get("brand"));
5050
8019
  if (queryBrand === void 0) {
5051
- send(res, 400, { error: "brand 只接受 cn、global 或 codebuddy" });
8020
+ send(res, 400, { error: "brand 只接受 cn、global、codebuddy 或 minimax" });
5052
8021
  return;
5053
8022
  }
5054
8023
  const adapter = adapters[queryBrand];
5055
8024
  const codebuddy = queryBrand === "codebuddy" ? adapter : void 0;
8025
+ const minimax = queryBrand === "minimax" ? adapter : void 0;
8026
+ const regional = codebuddy !== void 0 || minimax !== void 0;
5056
8027
  if (path === "/models" && method === "GET") {
5057
8028
  const requestedRegion = url.searchParams.get("region");
5058
8029
  const region = requestedRegion === null || requestedRegion === "" ? void 0 : regionFrom(requestedRegion);
5059
- if (codebuddy !== void 0 && region === void 0 && requestedRegion !== null && requestedRegion !== "") {
8030
+ if (regional && region === void 0 && requestedRegion !== null && requestedRegion !== "") {
5060
8031
  send(res, 400, { error: "region 只接受 global 或 cn" });
5061
8032
  return;
5062
8033
  }
5063
8034
  if (url.searchParams.get("fresh") === "1") {
5064
8035
  if (codebuddy !== void 0) codebuddy.invalidateCatalog(region);
8036
+ else if (minimax !== void 0) minimax.invalidateCatalog(region);
5065
8037
  else adapter.invalidateCatalog();
5066
8038
  }
5067
- const signedIn = codebuddy?.isSignedIn(region);
5068
- const rows = codebuddy !== void 0 ? signedIn === false ? [] : await buildCodeBuddyRows(codebuddy, region) : await buildRows(adapter);
5069
- const notice = rows.length === 0 ? codebuddy === void 0 ? adapter.catalogError() : codebuddy.catalogError(region) : void 0;
8039
+ const signedIn = codebuddy?.isSignedIn(region) ?? minimax?.isSignedIn(region);
8040
+ const rows = codebuddy !== void 0 ? signedIn === false ? [] : await buildCodeBuddyRows(codebuddy, region) : minimax !== void 0 ? signedIn === false ? [] : await buildMinimaxRows(minimax, region) : await buildRows(adapter);
8041
+ const notice = rows.length === 0 ? codebuddy !== void 0 ? codebuddy.catalogError(region) : minimax !== void 0 ? minimax.catalogError(region) : adapter.catalogError() : void 0;
5070
8042
  send(res, 200, {
5071
8043
  brand: queryBrand,
5072
8044
  models: rows,
5073
8045
  ...region === void 0 ? {} : { region },
5074
8046
  ...signedIn === void 0 ? {} : { signedIn },
8047
+ ...minimax === void 0 ? {} : { regionBlocked: minimax.regionBlocked(region) },
5075
8048
  ...notice === void 0 ? {} : { notice }
5076
8049
  });
5077
8050
  return;
@@ -5079,21 +8052,22 @@ async function handleApi(req, res, adapters) {
5079
8052
  if (path === "/usage" && method === "GET") {
5080
8053
  const requested = url.searchParams.get("region");
5081
8054
  const region = requested === null || requested === "" ? void 0 : regionFrom(requested);
5082
- if (codebuddy !== void 0 && region === void 0 && requested !== null && requested !== "") {
8055
+ if (regional && region === void 0 && requested !== null && requested !== "") {
5083
8056
  send(res, 400, { error: "region 只接受 global 或 cn" });
5084
8057
  return;
5085
8058
  }
8059
+ const fresh = url.searchParams.get("fresh") === "1";
5086
8060
  send(res, 200, {
5087
8061
  brand: queryBrand,
5088
- ...codebuddy !== void 0 ? await codebuddy.usageInfo(url.searchParams.get("fresh") === "1", region) : await adapter.usageInfo(url.searchParams.get("fresh") === "1"),
5089
- ...codebuddy === void 0 ? {} : { signedIn: codebuddy.isSignedIn(region) }
8062
+ ...codebuddy !== void 0 ? await codebuddy.usageInfo(fresh, region) : minimax !== void 0 ? await minimax.usageInfo(fresh, region) : await adapter.usageInfo(fresh),
8063
+ ...codebuddy === void 0 && minimax === void 0 ? {} : { signedIn: (codebuddy ?? minimax).isSignedIn(region) }
5090
8064
  });
5091
8065
  return;
5092
8066
  }
5093
8067
  if (path === "/auth") {
5094
8068
  if (method === "GET") {
5095
- if (codebuddy === void 0) {
5096
- send(res, 404, { error: "该 provider 没有 CodeBuddy 登录流程" });
8069
+ if (codebuddy === void 0 && minimax === void 0) {
8070
+ send(res, 404, { error: "该 provider 没有浏览器登录流程" });
5097
8071
  return;
5098
8072
  }
5099
8073
  const region = regionFrom(url.searchParams.get("region"));
@@ -5101,9 +8075,12 @@ async function handleApi(req, res, adapters) {
5101
8075
  send(res, 400, { error: "region 只接受 global 或 cn" });
5102
8076
  return;
5103
8077
  }
5104
- send(res, 200, {
8078
+ send(res, 200, codebuddy !== void 0 ? {
5105
8079
  brand: "codebuddy",
5106
8080
  ...codebuddy.authStatus(region)
8081
+ } : {
8082
+ brand: "minimax",
8083
+ ...minimax.authStatus(region)
5107
8084
  });
5108
8085
  return;
5109
8086
  }
@@ -5115,20 +8092,37 @@ async function handleApi(req, res, adapters) {
5115
8092
  send(res, 400, { error: `请求体无法解析:${error instanceof Error ? error.message : String(error)}` });
5116
8093
  return;
5117
8094
  }
5118
- if (brandFrom(body.brand) !== "codebuddy") {
5119
- send(res, 400, { error: "该 provider 没有 CodeBuddy 登录流程" });
8095
+ const postBrand = brandFrom(body.brand);
8096
+ if (postBrand !== "codebuddy" && postBrand !== "minimax") {
8097
+ send(res, 400, { error: "该 provider 没有浏览器登录流程" });
5120
8098
  return;
5121
8099
  }
5122
- const cb = adapters.codebuddy;
5123
8100
  const region = regionFrom(body.region);
5124
8101
  if (region === void 0) {
5125
8102
  send(res, 400, { error: "region 只接受 global 或 cn" });
5126
8103
  return;
5127
8104
  }
5128
- if (body.action === "logout") {
5129
- const result = await cb.logout(region);
5130
- if (!result.ok) {
5131
- send(res, 500, { error: result.error });
8105
+ if (body.action !== "login" && body.action !== "logout") {
8106
+ send(res, 400, { error: "action 只接受 login 或 logout" });
8107
+ return;
8108
+ }
8109
+ if (postBrand === "codebuddy") {
8110
+ const cb = adapters.codebuddy;
8111
+ if (body.action === "logout") {
8112
+ const result = await cb.logout(region);
8113
+ if (!result.ok) {
8114
+ send(res, 500, { error: result.error });
8115
+ return;
8116
+ }
8117
+ send(res, 200, {
8118
+ brand: "codebuddy",
8119
+ ...cb.authStatus(region)
8120
+ });
8121
+ return;
8122
+ }
8123
+ const started = cb.startLogin(region);
8124
+ if (started.started === false) {
8125
+ send(res, 409, { error: started.error });
5132
8126
  return;
5133
8127
  }
5134
8128
  send(res, 200, {
@@ -5137,29 +8131,36 @@ async function handleApi(req, res, adapters) {
5137
8131
  });
5138
8132
  return;
5139
8133
  }
5140
- if (body.action !== "login") {
5141
- send(res, 400, { error: "action 只接受 login 或 logout" });
8134
+ const mm = adapters.minimax;
8135
+ if (body.action === "logout") {
8136
+ send(res, 200, {
8137
+ brand: "minimax",
8138
+ ...await mm.logout(region)
8139
+ });
5142
8140
  return;
5143
8141
  }
5144
- const started = cb.startLogin(region);
8142
+ const started = mm.startLogin(region);
5145
8143
  if (started.started === false) {
5146
8144
  send(res, 409, { error: started.error });
5147
8145
  return;
5148
8146
  }
5149
8147
  send(res, 200, {
5150
- brand: "codebuddy",
5151
- ...cb.authStatus(region)
8148
+ brand: "minimax",
8149
+ ...mm.authStatus(region)
5152
8150
  });
5153
8151
  return;
5154
8152
  }
5155
8153
  }
5156
8154
  if (path === "/setup") {
5157
- if (codebuddy !== void 0) {
5158
- send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
5159
- return;
5160
- }
5161
- const qoder = adapter;
5162
8155
  if (method === "GET") {
8156
+ if (codebuddy !== void 0) {
8157
+ send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
8158
+ return;
8159
+ }
8160
+ if (minimax !== void 0) {
8161
+ send(res, 200, readMinimaxSetupStatus());
8162
+ return;
8163
+ }
5163
8164
  send(res, 200, readSetupStatus(queryBrand));
5164
8165
  return;
5165
8166
  }
@@ -5172,14 +8173,37 @@ async function handleApi(req, res, adapters) {
5172
8173
  return;
5173
8174
  }
5174
8175
  const postBrand = brandFrom(parsed.brand);
5175
- if (postBrand === void 0 || postBrand === "codebuddy") {
5176
- send(res, 400, { error: "该 brand 没有 CLI 安装脚本" });
8176
+ if (postBrand === void 0) {
8177
+ send(res, 400, { error: "brand 只接受 cn、global、codebuddy 或 minimax" });
8178
+ return;
8179
+ }
8180
+ if (postBrand === "codebuddy") {
8181
+ send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
8182
+ return;
8183
+ }
8184
+ if (postBrand === "minimax") {
8185
+ if (!isMinimaxSetupMode(parsed.mode)) {
8186
+ send(res, 400, { error: "mode 只接受 install 或 uninstall" });
8187
+ return;
8188
+ }
8189
+ const mm = adapters.minimax;
8190
+ const result = startMinimaxSetup(parsed.mode, (code) => {
8191
+ if (code !== 0) return;
8192
+ mm.invalidateCatalog();
8193
+ mm.invalidateUsage();
8194
+ });
8195
+ if (!result.started) {
8196
+ send(res, result.reason === "busy" ? 409 : 501, { error: result.error });
8197
+ return;
8198
+ }
8199
+ send(res, 200, readMinimaxSetupStatus());
5177
8200
  return;
5178
8201
  }
5179
8202
  if (!isSetupMode(parsed.mode)) {
5180
8203
  send(res, 400, { error: "mode 只接受 configure、login 或 uninstall" });
5181
8204
  return;
5182
8205
  }
8206
+ const qoder = adapters[postBrand];
5183
8207
  const result = startSetup(postBrand, parsed.mode, (code) => {
5184
8208
  if (code === 0) {
5185
8209
  qoder.invalidateCatalog();
@@ -5193,6 +8217,8 @@ async function handleApi(req, res, adapters) {
5193
8217
  send(res, 200, readSetupStatus(postBrand));
5194
8218
  return;
5195
8219
  }
8220
+ send(res, 405, { error: "不支持的写入路径" });
8221
+ return;
5196
8222
  }
5197
8223
  send(res, method === "GET" ? 404 : 405, { error: method === "GET" ? "not found" : "不支持的写入路径" });
5198
8224
  } catch (error) {
@@ -5263,6 +8289,14 @@ const Config$1 = z$1.object({
5263
8289
  codebuddyGlobalModelContextWindows: z$1.dict(z$1.number()).default({}).description("CodeBuddy 国际版按模型指定的上下文窗口(token 数)。").volatile(),
5264
8290
  codebuddyCnModelContextWindows: z$1.dict(z$1.number()).default({}).description("CodeBuddy 国内版按模型指定的上下文窗口(token 数)。").volatile(),
5265
8291
  codebuddyModelAliases: z$1.dict(z$1.string()).default({}).description("CodeBuddy 额外的模型别名映射:DSH 侧名称 → CodeBuddy 模型 ID。").volatile(),
8292
+ minimaxEnabled: z$1.boolean().default(true).description("启用 MiniMax Code(ACP)。关闭后该设置页、模型列表与 provider 路由都会移除;登录态与模型选择会保留。").volatile(),
8293
+ minimaxRegion: z$1.string().default("cn").description("MiniMax Code 登录区域:cn(国内站 account.minimax.cn)或 global(国际站 account.minimax.io)。").volatile(),
8294
+ minimaxDisplayName: z$1.string().default("MiniMax Code").description("模型选择器里 MiniMax Code 分组的名称。").volatile(),
8295
+ minimaxGlobalDisabledModels: z$1.array(z$1.string()).default([]).description("MiniMax Code 国际站已关闭的模型 ID 列表。").volatile(),
8296
+ minimaxCnDisabledModels: z$1.array(z$1.string()).default([]).description("MiniMax Code 国内站已关闭的模型 ID 列表。").volatile(),
8297
+ minimaxGlobalModelContextWindows: z$1.dict(z$1.number()).default({}).description("MiniMax Code 国际站按模型指定的上下文窗口(token 数)。").volatile(),
8298
+ minimaxCnModelContextWindows: z$1.dict(z$1.number()).default({}).description("MiniMax Code 国内站按模型指定的上下文窗口(token 数)。").volatile(),
8299
+ minimaxModelAliases: z$1.dict(z$1.string()).default({}).description("MiniMax Code 额外的模型别名映射:DSH 侧名称 → ACP 模型值。").volatile(),
5266
8300
  displayName: z$1.string().default("Qoder CN").description("模型选择器里主分组的名称。同时使用多个 Qoder 账号时可区分。").volatile(),
5267
8301
  maxSessions: z$1.number().step(1).min(1).max(64).default(8).description("同时保持的内层会话数上限,超出后按最久未使用关闭。每个会话是一个子进程。").volatile(),
5268
8302
  modelCacheTtlSeconds: z$1.number().step(1).min(10).max(86400).default(300).description("模型列表缓存时长(秒)。调小可更快看到账号侧变化。").volatile(),
@@ -5328,7 +8362,15 @@ function liveConfig(config) {
5328
8362
  codebuddyCnDisabledModels: () => stringList(field("codebuddyCnDisabledModels")),
5329
8363
  codebuddyGlobalModelContextWindows: () => numberMap(field("codebuddyGlobalModelContextWindows")),
5330
8364
  codebuddyCnModelContextWindows: () => numberMap(field("codebuddyCnModelContextWindows")),
5331
- codebuddyModelAliases: () => stringMap(field("codebuddyModelAliases"))
8365
+ codebuddyModelAliases: () => stringMap(field("codebuddyModelAliases")),
8366
+ minimaxEnabled: () => bool(field("minimaxEnabled"), true),
8367
+ minimaxRegion: () => field("minimaxRegion") === "global" ? "global" : "cn",
8368
+ minimaxDisplayName: () => nonEmpty(field("minimaxDisplayName"), "MiniMax Code"),
8369
+ minimaxGlobalDisabledModels: () => stringList(field("minimaxGlobalDisabledModels")),
8370
+ minimaxCnDisabledModels: () => stringList(field("minimaxCnDisabledModels")),
8371
+ minimaxGlobalModelContextWindows: () => numberMap(field("minimaxGlobalModelContextWindows")),
8372
+ minimaxCnModelContextWindows: () => numberMap(field("minimaxCnModelContextWindows")),
8373
+ minimaxModelAliases: () => stringMap(field("minimaxModelAliases"))
5332
8374
  };
5333
8375
  }
5334
8376
  /**
@@ -5370,7 +8412,15 @@ function resolveConfig(config) {
5370
8412
  codebuddyCnDisabledModels: live.codebuddyCnDisabledModels(),
5371
8413
  codebuddyGlobalModelContextWindows: live.codebuddyGlobalModelContextWindows(),
5372
8414
  codebuddyCnModelContextWindows: live.codebuddyCnModelContextWindows(),
5373
- codebuddyModelAliases: live.codebuddyModelAliases()
8415
+ codebuddyModelAliases: live.codebuddyModelAliases(),
8416
+ minimaxEnabled: live.minimaxEnabled(),
8417
+ minimaxRegion: live.minimaxRegion(),
8418
+ minimaxDisplayName: live.minimaxDisplayName(),
8419
+ minimaxGlobalDisabledModels: live.minimaxGlobalDisabledModels(),
8420
+ minimaxCnDisabledModels: live.minimaxCnDisabledModels(),
8421
+ minimaxGlobalModelContextWindows: live.minimaxGlobalModelContextWindows(),
8422
+ minimaxCnModelContextWindows: live.minimaxCnModelContextWindows(),
8423
+ minimaxModelAliases: live.minimaxModelAliases()
5374
8424
  };
5375
8425
  }
5376
8426
  function nonEmpty(value, fallback) {
@@ -5433,9 +8483,11 @@ const STRUCTURAL_FIELDS = /* @__PURE__ */ new Set([
5433
8483
  "cnEnabled",
5434
8484
  "intlEnabled",
5435
8485
  "codebuddyEnabled",
8486
+ "minimaxEnabled",
5436
8487
  "displayName",
5437
8488
  "intlDisplayName",
5438
- "codebuddyDisplayName"
8489
+ "codebuddyDisplayName",
8490
+ "minimaxDisplayName"
5439
8491
  ]);
5440
8492
  /** The configurable-provider directory rows for the enabled editions. */
5441
8493
  function directoryFor(live) {
@@ -5458,6 +8510,12 @@ function directoryFor(live) {
5458
8510
  settingsNs: NS,
5459
8511
  settingsPath: []
5460
8512
  });
8513
+ if (live.minimaxEnabled()) rows.push({
8514
+ provider: MINIMAX_PROVIDER,
8515
+ displayName: live.minimaxDisplayName(),
8516
+ settingsNs: NS,
8517
+ settingsPath: []
8518
+ });
5461
8519
  return rows;
5462
8520
  }
5463
8521
  /**
@@ -5548,7 +8606,23 @@ function apply(ctx, config) {
5548
8606
  region: live.codebuddyRegion,
5549
8607
  disabledModels: (region) => region === "cn" ? live.codebuddyCnDisabledModels() : live.codebuddyGlobalDisabledModels(),
5550
8608
  modelContextWindows: (region) => region === "cn" ? live.codebuddyCnModelContextWindows() : live.codebuddyGlobalModelContextWindows(),
5551
- modelAliases: live.codebuddyModelAliases
8609
+ modelAliases: live.codebuddyModelAliases,
8610
+ readImage: shared.readImage
8611
+ }),
8612
+ minimax: new MinimaxAdapter({
8613
+ maxSessions: live.maxSessions,
8614
+ modelCacheTtlMs: live.modelCacheTtlMs,
8615
+ catalogFetchTimeoutMs: live.catalogFetchTimeoutMs,
8616
+ toolResultTimeoutMs: live.toolResultTimeoutMs,
8617
+ abortGraceMs: live.abortGraceMs,
8618
+ defaultMaxTokens: live.defaultMaxTokens,
8619
+ defaultReasoningEffort: live.defaultReasoningEffort,
8620
+ displayName: live.minimaxDisplayName,
8621
+ region: live.minimaxRegion,
8622
+ disabledModels: (region) => region === "cn" ? live.minimaxCnDisabledModels() : live.minimaxGlobalDisabledModels(),
8623
+ modelContextWindows: (region) => region === "cn" ? live.minimaxCnModelContextWindows() : live.minimaxGlobalModelContextWindows(),
8624
+ modelAliases: live.minimaxModelAliases,
8625
+ readImage: shared.readImage
5552
8626
  })
5553
8627
  };
5554
8628
  ctx.inject(["attachments"], (scope) => {
@@ -5562,6 +8636,7 @@ function apply(ctx, config) {
5562
8636
  const enabled = (id) => {
5563
8637
  if (id === "cn") return live.cnEnabled();
5564
8638
  if (id === "global") return live.intlEnabled();
8639
+ if (id === "minimax") return live.minimaxEnabled();
5565
8640
  return live.codebuddyEnabled();
5566
8641
  };
5567
8642
  /**
@@ -5608,8 +8683,12 @@ function apply(ctx, config) {
5608
8683
  adapters.cn.close();
5609
8684
  adapters.global.close();
5610
8685
  adapters.codebuddy.close();
8686
+ adapters.minimax.close();
5611
8687
  }, "llm-qoder-cn.sessions");
5612
- ctx.effect(() => () => stopSetup(), "llm-qoder-cn.setup");
8688
+ ctx.effect(() => () => {
8689
+ stopSetup();
8690
+ stopMinimaxSetup();
8691
+ }, "llm-qoder-cn.setup");
5613
8692
  ctx.inject(["webServer"], (scope) => {
5614
8693
  const server = scope.webServer;
5615
8694
  if (server === void 0) return;
@@ -5624,4 +8703,4 @@ function apply(ctx, config) {
5624
8703
  });
5625
8704
  }
5626
8705
  //#endregion
5627
- export { API_PREFIX, BRANDS, CN_BRAND, CODEBUDDY_BRAND, CODEBUDDY_DEFAULT_CONTEXT_WINDOW, CODEBUDDY_DEFAULT_MAX_TOKENS, CODEBUDDY_PROVIDER, CodeBuddyAccountReader, CodeBuddyAdapter, CodeBuddyAuth, CodeBuddyCatalog, CodeBuddySession, CodeBuddySessionManager, Config, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_USAGE_CACHE_TTL_MS, DEFAULT_USAGE_TIMEOUT_MS, GLOBAL_BRAND, MODEL_ALIASES, NARROW_CHARS_PER_TOKEN, QODER_INTL_PROVIDER, QODER_MODELS, QODER_PROVIDER, QoderAdapter, QoderModelCatalog, QoderSession, QoderSessionManager, QoderUsage, SCRIPT_NAME, ToolResultPairing, WIDE_CHARS_PER_TOKEN, apply, brandProfile, buildRows, cliContextWindow, codeBuddyColdStream, codeBuddyEnvironment, countWideChars, estimateTextTokens, fetchCodeBuddyQuota, handleApi, inject, isBrandId, isSetupMode, isWideChar, liveConfig, loadCodeBuddySdk, loadSdk, name, parseCodeBuddyQuota, pickContextWindow, priceFactorOf, readLive, readLiveOptional, readSetupStatus, resolveCodeBuddyModelId, resolveConfig, resolveQoderModelId, setupScriptPath, startSetup, stopSetup, toCodeBuddyModel };
8706
+ export { API_PREFIX, BRANDS, CN_BRAND, CODEBUDDY_BRAND, CODEBUDDY_DEFAULT_CONTEXT_WINDOW, CODEBUDDY_DEFAULT_MAX_TOKENS, CODEBUDDY_PROVIDER, CodeBuddyAccountReader, CodeBuddyAdapter, CodeBuddyAuth, CodeBuddyCatalog, CodeBuddySession, CodeBuddySessionManager, Config, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_USAGE_CACHE_TTL_MS, DEFAULT_USAGE_TIMEOUT_MS, GLOBAL_BRAND, MINIMAX_DEFAULT_CONTEXT_WINDOW, MINIMAX_DEFAULT_MAX_TOKENS, MINIMAX_PROVIDER, MINIMAX_USAGE_CACHE_TTL_MS, MODEL_ALIASES, MinimaxAcp, MinimaxAdapter, MinimaxAuth, MinimaxCatalog, MinimaxCliSetup, MinimaxRegionBlockedError, MinimaxSession, MinimaxSessionManager, NARROW_CHARS_PER_TOKEN, QODER_INTL_PROVIDER, QODER_MODELS, QODER_PROVIDER, QoderAdapter, QoderModelCatalog, QoderSession, QoderSessionManager, QoderUsage, SCRIPT_NAME, ToolResultPairing, WIDE_CHARS_PER_TOKEN, apply, brandProfile, buildRows, cliContextWindow, codeBuddyColdStream, codeBuddyEnvironment, countWideChars, estimateTextTokens, fetchCodeBuddyQuota, handleApi, hostMcpToolName, inject, invalidateMinimaxRegionAccess, invalidateMinimaxUsage, isBrandId, isHostMcpTool, isSetupMode, isWideChar, liveConfig, loadCodeBuddySdk, loadSdk, minimaxAuthStatePath, minimaxCliCommand, minimaxColdStream, minimaxDataDir, minimaxHostBelongsToOtherRegion, minimaxModelsFromConfigOptions, minimaxRegionBlockMessage, minimaxRegionBlocked, minimaxRegionBlockedCached, minimaxUsage, minimaxUsageFromParts, name, parseCodeBuddyQuota, pickContextWindow, priceFactorOf, readLive, readLiveOptional, readMinimaxSetupStatus, readSetupStatus, resolveCodeBuddyModelId, resolveConfig, resolveMinimaxCli, resolveMinimaxModelId, resolveQoderModelId, setupScriptPath, startMinimaxSetup, startSetup, stopMinimaxSetup, stopSetup, toCodeBuddyModel };