dsh-agent-sdk-bridge 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -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`));
@@ -1338,7 +1377,7 @@ function meteredUsage(real, reasoning) {
1338
1377
  * The host tool runtime dispatches by the bare host name; the inner model
1339
1378
  * only ever sees the namespaced MCP form, so strip the prefix on the way out.
1340
1379
  */
1341
- function hostToolName(name) {
1380
+ function hostToolName$1(name) {
1342
1381
  return name.startsWith(MCP_TOOL_PREFIX$1) ? name.slice(MCP_TOOL_PREFIX$1.length) : name;
1343
1382
  }
1344
1383
  /** Deny native tools, allow this adapter's MCP tools. */
@@ -2168,7 +2207,7 @@ var QoderSession = class {
2168
2207
  this.openTool = {
2169
2208
  chunkIndex,
2170
2209
  callId,
2171
- name: hostToolName(block.name ?? ""),
2210
+ name: hostToolName$1(block.name ?? ""),
2172
2211
  arguments: initialArguments
2173
2212
  };
2174
2213
  this.countOutput(this.openTool.name);
@@ -2638,8 +2677,8 @@ var QoderUsage = class {
2638
2677
  }
2639
2678
  });
2640
2679
  try {
2641
- const usage = await withTimeout$1(q.getUsageInfo(), timeoutMs);
2642
- const account = await withTimeout$1(q.accountInfo(), timeoutMs).catch(() => void 0);
2680
+ const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
2681
+ const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
2643
2682
  return {
2644
2683
  at,
2645
2684
  ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
@@ -2670,9 +2709,9 @@ var QoderUsage = class {
2670
2709
  * @module dsh-llm-qoder/adapter
2671
2710
  */
2672
2711
  /** Shared empty values, so an unset list or map allocates nothing per read. */
2673
- const NO_MODELS$1 = [];
2712
+ const NO_MODELS$2 = [];
2674
2713
  const NO_WINDOWS = {};
2675
- const NO_ALIASES$1 = {};
2714
+ const NO_ALIASES$2 = {};
2676
2715
  /** The primary provider route (the CN account's own models). */
2677
2716
  const QODER_PROVIDER = "qoder-cn";
2678
2717
  /** The international edition's route; a second adapter instance serves it. */
@@ -2723,7 +2762,7 @@ function cliContextWindow(live, declared) {
2723
2762
  if (available !== void 0 && available.includes(declared)) return declared;
2724
2763
  return live.defaultContextWindow ?? largestWindow(available) ?? live.maxInputTokens;
2725
2764
  }
2726
- function modelInfo$1(provider, entry) {
2765
+ function modelInfo$2(provider, entry) {
2727
2766
  return {
2728
2767
  provider,
2729
2768
  id: entry.id,
@@ -2816,7 +2855,7 @@ var QoderAdapter = class extends LlmAdapter {
2816
2855
  return readLive(this.options.modelContextWindows, NO_WINDOWS);
2817
2856
  }
2818
2857
  get disabledModels() {
2819
- const source = readLive(this.options.disabledModels, NO_MODELS$1);
2858
+ const source = readLive(this.options.disabledModels, NO_MODELS$2);
2820
2859
  const cached = this.disabledCache;
2821
2860
  if (cached !== void 0 && cached.source === source) return cached.set;
2822
2861
  const set = new Set(source);
@@ -2827,7 +2866,7 @@ var QoderAdapter = class extends LlmAdapter {
2827
2866
  return set;
2828
2867
  }
2829
2868
  get modelAliases() {
2830
- return readLive(this.options.modelAliases, NO_ALIASES$1);
2869
+ return readLive(this.options.modelAliases, NO_ALIASES$2);
2831
2870
  }
2832
2871
  get defaultReasoningEffort() {
2833
2872
  return readLiveOptional(this.options.defaultReasoningEffort);
@@ -2910,7 +2949,7 @@ var QoderAdapter = class extends LlmAdapter {
2910
2949
  return this.modelContextWindows;
2911
2950
  }
2912
2951
  async listModels(provider) {
2913
- return (await this.catalog.models()).filter((entry) => this.isVisible(entry.id)).map((entry) => modelInfo$1(provider, entry));
2952
+ return (await this.catalog.models()).filter((entry) => this.isVisible(entry.id)).map((entry) => modelInfo$2(provider, entry));
2914
2953
  }
2915
2954
  async resolveModel(provider, model, _signal) {
2916
2955
  const target = resolveQoderModelId(model, this.modelAliases);
@@ -2937,7 +2976,7 @@ var QoderAdapter = class extends LlmAdapter {
2937
2976
  name: model,
2938
2977
  inputModalities: ["text"]
2939
2978
  } : {
2940
- ...modelInfo$1(provider, configured),
2979
+ ...modelInfo$2(provider, configured),
2941
2980
  id: model
2942
2981
  },
2943
2982
  context: { contextWindow: this.windowOverride(target) ?? 2e5 },
@@ -3286,6 +3325,26 @@ const LOGIN_TIMEOUT_MS = 3e5;
3286
3325
  const LOGOUT_TIMEOUT_MS = 2e4;
3287
3326
  const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
3288
3327
  /**
3328
+ * The same namespace after the CLI normalises the server name.
3329
+ *
3330
+ * CodeBuddy rewrites every non-alphanumeric character in an MCP server name to
3331
+ * `_`, so a server registered as `dsh-host` is exposed to the model as
3332
+ * `mcp__dsh_host__<tool>`. Matching only the registered spelling rejected the
3333
+ * host's own tools as "built-ins", which is exactly why the model fell back to
3334
+ * `Bash`. The Qoder CLI keeps the hyphen, so both spellings are accepted.
3335
+ */
3336
+ const MCP_TOOL_PREFIX_SANITIZED = `mcp__${MCP_SERVER_NAME.replace(/[^a-zA-Z0-9]/g, "_")}__`;
3337
+ /** Whether a CLI tool name belongs to this plugin's MCP server. */
3338
+ function isHostTool(toolName) {
3339
+ return toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED);
3340
+ }
3341
+ /** The host-side tool name, with the MCP namespace removed. */
3342
+ function hostToolName(toolName) {
3343
+ if (toolName.startsWith(MCP_TOOL_PREFIX)) return toolName.slice(MCP_TOOL_PREFIX.length);
3344
+ if (toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED)) return toolName.slice(MCP_TOOL_PREFIX_SANITIZED.length);
3345
+ return toolName;
3346
+ }
3347
+ /**
3289
3348
  * Whether the CLI answered as the anonymous fallback.
3290
3349
  *
3291
3350
  * With an invalid `CODEBUDDY_AUTH_TOKEN` the CLI still reports an account
@@ -3394,13 +3453,13 @@ async function withSession(region, run, timeoutMs, options = {}) {
3394
3453
  persistSession: false
3395
3454
  });
3396
3455
  try {
3397
- await withTimeout(session.connect(), timeoutMs);
3398
- return await withTimeout(run(session), timeoutMs);
3456
+ await withTimeout$1(session.connect(), timeoutMs);
3457
+ return await withTimeout$1(run(session), timeoutMs);
3399
3458
  } finally {
3400
3459
  session.close();
3401
3460
  }
3402
3461
  }
3403
- function withTimeout(promise, ms) {
3462
+ function withTimeout$1(promise, ms) {
3404
3463
  return new Promise((resolve, reject) => {
3405
3464
  const timer = setTimeout(() => {
3406
3465
  reject(/* @__PURE__ */ new Error(`CodeBuddy request timed out after ${ms}ms`));
@@ -3601,8 +3660,8 @@ async function readAccount(region, timeoutMs) {
3601
3660
  }
3602
3661
  });
3603
3662
  try {
3604
- await withTimeout(q.connect(), timeoutMs);
3605
- return await withTimeout(q.accountInfo(), timeoutMs);
3663
+ await withTimeout$1(q.connect(), timeoutMs);
3664
+ return await withTimeout$1(q.accountInfo(), timeoutMs);
3606
3665
  } finally {
3607
3666
  await q.return().catch(() => void 0);
3608
3667
  }
@@ -3696,7 +3755,7 @@ function formatLocalTime(date) {
3696
3755
  async function readBearerToken(region) {
3697
3756
  const cached = tokenFor(region);
3698
3757
  if (cached !== void 0) return cached;
3699
- const result = await withTimeout((await loadCodeBuddySdk()).unstable_v2_authenticate({
3758
+ const result = await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_authenticate({
3700
3759
  environment: codeBuddyEnvironment(region),
3701
3760
  timeout: 3e3,
3702
3761
  onAuthUrl: () => {}
@@ -3826,7 +3885,7 @@ var CodeBuddyAuth = class {
3826
3885
  async logout(region) {
3827
3886
  let failure;
3828
3887
  try {
3829
- await withTimeout((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
3888
+ await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
3830
3889
  } catch (error) {
3831
3890
  failure = error instanceof Error ? error.message : String(error);
3832
3891
  }
@@ -3847,7 +3906,7 @@ var CodeBuddyAuth = class {
3847
3906
  const { region } = status;
3848
3907
  try {
3849
3908
  const sdk = await loadCodeBuddySdk();
3850
- await withTimeout(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
3909
+ await withTimeout$1(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
3851
3910
  if (!this.current(run)) return;
3852
3911
  bearerTokens.delete(region);
3853
3912
  const result = await sdk.unstable_v2_authenticate({
@@ -3893,6 +3952,7 @@ var CodeBuddySession = class {
3893
3952
  mcp = null;
3894
3953
  pairing = new ToolResultPairing();
3895
3954
  registered = /* @__PURE__ */ new Map();
3955
+ toolSchemas = [];
3896
3956
  queue = null;
3897
3957
  disposed = false;
3898
3958
  abortPending = false;
@@ -3933,10 +3993,23 @@ var CodeBuddySession = class {
3933
3993
  this.systemPrompt = options.system;
3934
3994
  if (options.cwd !== void 0) this.cwd = options.cwd;
3935
3995
  }
3936
- /** Register any host tools whose schema this session's MCP server lacks. */
3996
+ /**
3997
+ * Remember the host tools and register them with this session's MCP server.
3998
+ *
3999
+ * Registration must happen before the CLI connects: the MCP SDK refuses a
4000
+ * tool added afterwards. The first turn calls this before the session — and
4001
+ * therefore its MCP server — exists, so the schemas are kept and replayed by
4002
+ * {@link ensureStarted}. Returning early there left the model with no host
4003
+ * tools at all, and it fell back to CodeBuddy's built-in `Bash`, which the
4004
+ * host could only answer with "unknown tool".
4005
+ */
3937
4006
  ensureTools(tools) {
4007
+ this.toolSchemas = tools;
4008
+ this.registerTools();
4009
+ }
4010
+ registerTools() {
3938
4011
  if (this.mcp === null) return;
3939
- for (const schema of tools) {
4012
+ for (const schema of this.toolSchemas) {
3940
4013
  const hash = JSON.stringify(schema.parameters ?? {});
3941
4014
  if (this.registered.get(schema.name) === hash) continue;
3942
4015
  const shape = jsonSchemaToShape(schema.parameters ?? {});
@@ -4040,12 +4113,14 @@ var CodeBuddySession = class {
4040
4113
  name: MCP_SERVER_NAME,
4041
4114
  tools: []
4042
4115
  });
4116
+ this.registerTools();
4043
4117
  const session = sdk.unstable_v2_createSession({
4044
4118
  environment: codeBuddyEnvironment(this.region),
4045
4119
  sessionId: randomUUID(),
4046
4120
  model: this.model,
4047
4121
  mcpServers: { [MCP_SERVER_NAME]: this.mcp },
4048
4122
  canUseTool: this.canUseTool,
4123
+ tools: [],
4049
4124
  ...cliEnv(this.region),
4050
4125
  settingSources: [],
4051
4126
  includePartialMessages: true,
@@ -4058,7 +4133,7 @@ var CodeBuddySession = class {
4058
4133
  return session;
4059
4134
  }
4060
4135
  canUseTool = (toolName, _input, options) => {
4061
- if (toolName.startsWith(MCP_TOOL_PREFIX)) {
4136
+ if (isHostTool(toolName)) {
4062
4137
  if (options.toolUseID !== void 0) this.pairing.announce(options.toolUseID);
4063
4138
  return Promise.resolve({
4064
4139
  behavior: "allow",
@@ -4105,6 +4180,7 @@ var CodeBuddySession = class {
4105
4180
  if (event.type === "content_block_start") {
4106
4181
  const block = event.content_block;
4107
4182
  if (block?.type === "tool_use") {
4183
+ if (!isHostTool(block.name ?? "")) return;
4108
4184
  const callId = `cb-${this.callNonce}-${++this.callCounter}`;
4109
4185
  if (typeof block.id === "string" && block.id.length > 0) this.pairing.mapHostCall(callId, block.id);
4110
4186
  const chunkIndex = this.blockIndex++;
@@ -4112,7 +4188,7 @@ var CodeBuddySession = class {
4112
4188
  this.openTool = {
4113
4189
  chunkIndex,
4114
4190
  callId,
4115
- name: (block.name ?? "").replace(MCP_TOOL_PREFIX, ""),
4191
+ name: hostToolName(block.name ?? ""),
4116
4192
  arguments: initial
4117
4193
  };
4118
4194
  this.countOutput(this.openTool.name);
@@ -4435,6 +4511,7 @@ async function codeBuddyColdStream(region, prompt, model, options) {
4435
4511
  sessionId: randomUUID(),
4436
4512
  ...model === void 0 ? {} : { model },
4437
4513
  ...cliEnv(region),
4514
+ tools: [],
4438
4515
  settingSources: [],
4439
4516
  persistSession: false
4440
4517
  });
@@ -4525,8 +4602,8 @@ async function codeBuddyColdStream(region, prompt, model, options) {
4525
4602
  */
4526
4603
  /** The CodeBuddy provider route. */
4527
4604
  const CODEBUDDY_PROVIDER = "codebuddy";
4528
- const NO_MODELS = [];
4529
- const NO_ALIASES = {};
4605
+ const NO_MODELS$1 = [];
4606
+ const NO_ALIASES$1 = {};
4530
4607
  /** Map a harness-side id onto a CodeBuddy model value. */
4531
4608
  function resolveCodeBuddyModelId(model, aliases = {}) {
4532
4609
  const configured = aliases[model] ?? aliases[model.toLowerCase()];
@@ -4534,7 +4611,7 @@ function resolveCodeBuddyModelId(model, aliases = {}) {
4534
4611
  const stripped = model.startsWith("codebuddy-") ? model.slice(10) : model;
4535
4612
  return stripped.length > 0 ? stripped : "default-model";
4536
4613
  }
4537
- function modelInfo(provider, model) {
4614
+ function modelInfo$1(provider, model) {
4538
4615
  return {
4539
4616
  provider,
4540
4617
  id: model.id,
@@ -4565,7 +4642,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4565
4642
  return readLive(this.options.region ?? (() => "global"), "global");
4566
4643
  }
4567
4644
  disabledFor(region) {
4568
- const source = this.options.disabledModels?.(region) ?? NO_MODELS;
4645
+ const source = this.options.disabledModels?.(region) ?? NO_MODELS$1;
4569
4646
  const key = source.join("\0");
4570
4647
  const cached = this.disabledCache.get(region);
4571
4648
  if (cached?.key === key) return cached.set;
@@ -4577,7 +4654,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4577
4654
  return set;
4578
4655
  }
4579
4656
  get aliases() {
4580
- return readLive(this.options.modelAliases, NO_ALIASES);
4657
+ return readLive(this.options.modelAliases, NO_ALIASES$1);
4581
4658
  }
4582
4659
  get displayName() {
4583
4660
  return readLive(this.options.displayName, "CodeBuddy");
@@ -4642,7 +4719,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4642
4719
  if (!this.isSignedIn(region)) return [];
4643
4720
  const models = await this.catalog.models(region);
4644
4721
  const disabled = this.disabledFor(region);
4645
- return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo(provider, model));
4722
+ return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo$1(provider, model));
4646
4723
  }
4647
4724
  async resolveModel(provider, model) {
4648
4725
  const target = resolveCodeBuddyModelId(model, this.aliases);
@@ -4736,60 +4813,112 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4736
4813
  }
4737
4814
  };
4738
4815
  //#endregion
4739
- //#region src/setup.ts
4816
+ //#region src/minimax-cli.ts
4740
4817
  /**
4741
- * Runs the bundled Windows helper that installs and signs into a Qoder CLI
4742
- * (one helper per edition: `qoderclicn` for CN, `qodercli` for international).
4743
- *
4744
- * The settings page cannot do this by itself: a browser has no way to start a
4745
- * local process, and the plugin's own process is the one that already talks to
4746
- * the CLI. So the page asks this module, and this module spawns
4747
- * {@link SCRIPT_NAME} — the same script a user can double-click — with one of
4748
- * two fixed flags, and buffers its output so the page can show progress while
4749
- * the browser sign-in is still open.
4818
+ * The MiniMax Code CLI (`mcode`): locating it and running its installer.
4750
4819
  *
4751
- * Nothing user-supplied reaches the command line: the mode is an allow-list of
4752
- * two keys mapped to two literal flags, and the script path comes from this
4753
- * package's own layout. The helper is idempotent, so a second press re-checks
4754
- * rather than reinstalling.
4820
+ * MiniMax ships `@minimax-ai/code` as a global npm package whose `mcode`
4821
+ * launcher is a Node shim. Its native SQLite dependency is installed by a
4822
+ * postinstall script, and npm 12 blocks install scripts unless they are named
4823
+ * with `--allow-scripts`; a plain `npm i -g` leaves a CLI that cannot start.
4824
+ * The installer below therefore passes the flags the package documents.
4755
4825
  *
4756
- * @module dsh-agent-sdk-bridge/setup
4826
+ * @module dsh-agent-sdk-bridge/minimax-cli
4757
4827
  */
4758
- /** File name of the CN helper, shipped under this package's `scripts/` directory. */
4759
- const SCRIPT_NAME = "setup-qoderclicn.bat";
4760
- /** The helper script for one edition. */
4761
- function scriptNameOf(brand) {
4762
- return brandProfile(brand).setupScript ?? "setup-qoderclicn.bat";
4828
+ /** The npm package and the version verified to work with native SQLite. */
4829
+ const PACKAGE = "@minimax-ai/code";
4830
+ const INSTALL_VERSION = "0.6.12";
4831
+ const INSTALL_FLAGS = [
4832
+ "--ignore-scripts=false",
4833
+ "--include=optional",
4834
+ "--allow-scripts=@minimax-ai/code,better-sqlite3",
4835
+ "--registry",
4836
+ "https://registry.npmjs.org/",
4837
+ "--foreground-scripts"
4838
+ ];
4839
+ function fromJsEntry(path) {
4840
+ return {
4841
+ command: process.execPath,
4842
+ args: [path],
4843
+ cliPath: path
4844
+ };
4763
4845
  }
4764
- /** The one command-line flag each mode maps to. Never a user-supplied string. */
4765
- const FLAGS = {
4766
- configure: "--gui",
4767
- login: "--login",
4768
- uninstall: "--uninstall"
4769
- };
4770
- /** Whether a value is one of the modes the page may request. */
4771
- function isSetupMode(value) {
4772
- return value === "configure" || value === "login" || value === "uninstall";
4846
+ function fromShim(shim) {
4847
+ if (shim.endsWith(".cmd") || shim.endsWith(".bat")) {
4848
+ try {
4849
+ const text = readFileSync(shim, "utf8");
4850
+ const match = /["']([^"']*node_modules[\\/]@minimax-ai[\\/]code[\\/]cli\.js)["']/.exec(text);
4851
+ if (match !== null && existsSync(match[1])) return fromJsEntry(match[1]);
4852
+ } catch {}
4853
+ const sibling = join(dirname(shim), "node_modules", "@minimax-ai", "code", "cli.js");
4854
+ if (existsSync(sibling)) return fromJsEntry(sibling);
4855
+ return {
4856
+ command: process.env.ComSpec ?? "cmd.exe",
4857
+ args: [
4858
+ "/d",
4859
+ "/c",
4860
+ shim
4861
+ ]
4862
+ };
4863
+ }
4864
+ if (shim.endsWith(".js") || shim.endsWith(".mjs")) return fromJsEntry(shim);
4865
+ try {
4866
+ const real = realpathSync(shim);
4867
+ if (real.endsWith(".js") || real.endsWith(".mjs")) return fromJsEntry(real);
4868
+ } catch {}
4869
+ return {
4870
+ command: shim,
4871
+ args: []
4872
+ };
4773
4873
  }
4774
- /** Cap on kept output, so a chatty `npm install` cannot grow without bound. */
4775
- const MAX_LINES = 400;
4776
- /** The latest run per edition: the two installers may run independently. */
4777
- const current = /* @__PURE__ */ new Map();
4778
4874
  /**
4779
- * Locate one edition's helper inside this package.
4780
- *
4781
- * The host half is bundled to `lib/index.js`, and tests import `src/*.ts`, so
4782
- * both layouts resolve to the same `scripts/` directory one level up.
4875
+ * Locate `mcode`.
4783
4876
  *
4784
- * @param brand - which edition's script to find.
4877
+ * `MCODE_CLI_PATH` wins (a cli.js path or an executable); otherwise the PATH
4878
+ * shims and the global npm prefixes are checked. The explicit cli.js lookup
4879
+ * matters on Windows, where spawning a `.cmd` for ACP would put cmd.exe between
4880
+ * the protocol streams.
4785
4881
  */
4786
- function setupScriptPath(brand = "cn") {
4787
- const here = path.dirname(fileURLToPath(import.meta.url));
4788
- const script = scriptNameOf(brand);
4789
- for (const candidate of [path.resolve(here, "..", "scripts", script), path.resolve(here, "scripts", script)]) if (existsSync(candidate)) return candidate;
4882
+ function resolveMinimaxCli() {
4883
+ const override = process.env.MCODE_CLI_PATH?.trim();
4884
+ if (override !== void 0 && override.length > 0 && existsSync(override)) return fromShim(override);
4885
+ const names = process.platform === "win32" ? [
4886
+ "mcode.cmd",
4887
+ "mcode.exe",
4888
+ "mcode"
4889
+ ] : ["mcode"];
4890
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
4891
+ if (directory.trim() === "") continue;
4892
+ for (const name of names) {
4893
+ const candidate = join(directory, name);
4894
+ if (existsSync(candidate)) return fromShim(candidate);
4895
+ }
4896
+ }
4897
+ const home = homedir();
4898
+ const candidates = process.platform === "win32" ? [
4899
+ join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "npm", "node_modules", PACKAGE, "cli.js"),
4900
+ join(process.env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "npm", "node_modules", PACKAGE, "cli.js"),
4901
+ join(process.env.ProgramFiles ?? "C:\\Program Files", "nodejs", "node_modules", PACKAGE, "cli.js")
4902
+ ] : [
4903
+ join(home, ".npm-global", "lib", "node_modules", PACKAGE, "cli.js"),
4904
+ join("/usr", "local", "lib", "node_modules", PACKAGE, "cli.js"),
4905
+ join("/usr", "lib", "node_modules", PACKAGE, "cli.js"),
4906
+ join(home, ".local", "lib", "node_modules", PACKAGE, "cli.js")
4907
+ ];
4908
+ for (const candidate of candidates) if (existsSync(candidate)) return fromJsEntry(candidate);
4790
4909
  }
4791
- /** Append decoded text to a run, splitting it into displayable lines. */
4792
- function absorb(run, chunk, done) {
4910
+ /** The spawn argument list for one CLI invocation. */
4911
+ function minimaxCliArgs(spec, args) {
4912
+ return [...spec.args, ...args];
4913
+ }
4914
+ /** Whether a value names an installer action. */
4915
+ function isMinimaxSetupMode(value) {
4916
+ return value === "install" || value === "uninstall";
4917
+ }
4918
+ /** Cap on kept output. */
4919
+ const MAX_LINES$1 = 400;
4920
+ let current$1;
4921
+ function absorb$1(run, chunk, done) {
4793
4922
  run.pending += run.decoder.decode(chunk, { stream: !done });
4794
4923
  const parts = run.pending.split(/\r\n|\r|\n/);
4795
4924
  run.pending = done ? "" : parts.pop() ?? "";
@@ -4798,43 +4927,48 @@ function absorb(run, chunk, done) {
4798
4927
  run.lines.push(part);
4799
4928
  }
4800
4929
  if (done && run.pending.trim() !== "") run.lines.push(run.pending.trim());
4801
- while (run.lines.length > MAX_LINES) {
4930
+ while (run.lines.length > MAX_LINES$1) {
4802
4931
  run.lines.shift();
4803
4932
  run.truncated = true;
4804
4933
  }
4805
4934
  }
4806
4935
  /**
4807
- * Start one edition's helper. Only one run per edition at a time; a finished
4808
- * one stays readable.
4936
+ * Start the npm installer or uninstaller.
4809
4937
  *
4810
- * @param brand - which edition to configure.
4811
- * @param mode - the fixed flag the page may ask for.
4812
- * @param onFinish - called once with the exit code.
4938
+ * The command is fixed: the mode is an allow-list and no user input reaches
4939
+ * argv. npm itself is run through cmd.exe on Windows because npm is a `.cmd`
4940
+ * shim and Node refuses to spawn it directly on recent versions.
4813
4941
  */
4814
- function startSetup(brand, mode, onFinish) {
4815
- const previous = current.get(brand);
4816
- if (previous !== void 0 && previous.finishedAt === void 0) return {
4942
+ function startMinimaxSetup(mode, onFinish) {
4943
+ if (current$1 !== void 0 && current$1.finishedAt === void 0) return {
4817
4944
  started: false,
4818
4945
  reason: "busy",
4819
- error: "已经有一次配置在跑了,请等它结束。"
4946
+ error: "已经有一次 MiniMax CLI 安装在跑了,请等它结束。"
4820
4947
  };
4821
- if (process.platform !== "win32") {
4822
- const command = brandProfile(brand).cliCommands[0];
4823
- return {
4824
- started: false,
4825
- reason: "unsupported",
4826
- error: `一键${mode === "uninstall" ? "卸载" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
4827
- };
4828
- }
4829
- const script = setupScriptPath(brand);
4830
- if (script === void 0) return {
4948
+ if (process.platform !== "win32" && mode === "install") return {
4831
4949
  started: false,
4832
- reason: "missing-script",
4833
- error: `插件包里没有 ${scriptNameOf(brand)},缺少 scripts/ 目录。`
4950
+ reason: "unsupported",
4951
+ error: "一键安装 MiniMax CLI 目前只支持 Windows;请在终端手动执行 npm install -g @minimax-ai/code。"
4834
4952
  };
4953
+ const npmArgs = mode === "install" ? [
4954
+ "install",
4955
+ "--global",
4956
+ `${PACKAGE}@${INSTALL_VERSION}`,
4957
+ ...INSTALL_FLAGS
4958
+ ] : [
4959
+ "uninstall",
4960
+ "--global",
4961
+ PACKAGE
4962
+ ];
4963
+ const command = process.platform === "win32" ? process.env.ComSpec ?? "cmd.exe" : "npm";
4964
+ const args = process.platform === "win32" ? [
4965
+ "/d",
4966
+ "/c",
4967
+ "npm",
4968
+ ...npmArgs
4969
+ ] : npmArgs;
4835
4970
  const run = {
4836
4971
  child: void 0,
4837
- brand,
4838
4972
  mode,
4839
4973
  startedAt: Date.now(),
4840
4974
  lines: [],
@@ -4842,12 +4976,7 @@ function startSetup(brand, mode, onFinish) {
4842
4976
  decoder: new TextDecoder("utf-8"),
4843
4977
  truncated: false
4844
4978
  };
4845
- const child = spawn(process.env.ComSpec ?? "cmd.exe", [
4846
- "/d",
4847
- "/c",
4848
- script,
4849
- FLAGS[mode]
4850
- ], {
4979
+ const child = spawn(command, args, {
4851
4980
  cwd: homedir(),
4852
4981
  windowsHide: true,
4853
4982
  stdio: [
@@ -4857,7 +4986,7 @@ function startSetup(brand, mode, onFinish) {
4857
4986
  ]
4858
4987
  });
4859
4988
  run.child = child;
4860
- current.set(brand, run);
4989
+ current$1 = run;
4861
4990
  const finish = (code) => {
4862
4991
  if (run.finishedAt !== void 0) return;
4863
4992
  run.finishedAt = Date.now();
@@ -4868,31 +4997,30 @@ function startSetup(brand, mode, onFinish) {
4868
4997
  run.lines.push(`收尾回调失败:${error instanceof Error ? error.message : String(error)}`);
4869
4998
  }
4870
4999
  };
4871
- child.stdout?.on("data", (chunk) => absorb(run, chunk, false));
4872
- child.stderr?.on("data", (chunk) => absorb(run, chunk, false));
5000
+ child.stdout?.on("data", (chunk) => absorb$1(run, chunk, false));
5001
+ child.stderr?.on("data", (chunk) => absorb$1(run, chunk, false));
4873
5002
  child.on("error", (error) => {
4874
- run.lines.push(`无法启动 ${scriptNameOf(brand)}:${error instanceof Error ? error.message : String(error)}`);
5003
+ run.lines.push(`无法启动 npm:${error instanceof Error ? error.message : String(error)}`);
4875
5004
  finish(null);
4876
5005
  });
4877
5006
  child.on("close", (code) => {
4878
- absorb(run, /* @__PURE__ */ new Uint8Array(), true);
5007
+ absorb$1(run, /* @__PURE__ */ new Uint8Array(), true);
4879
5008
  finish(code);
4880
5009
  });
4881
5010
  return { started: true };
4882
5011
  }
4883
- /**
4884
- * The latest run of one edition, with any not-yet-newlined tail included for
4885
- * live display.
4886
- *
4887
- * @param brand - which edition's run to report.
4888
- */
4889
- function readSetupStatus(brand = "cn") {
4890
- const run = current.get(brand);
4891
- if (run === void 0) return {
5012
+ /** The latest installer run, with any not-yet-newlined tail included. */
5013
+ function readMinimaxSetupStatus() {
5014
+ const spec = resolveMinimaxCli();
5015
+ const installed = spec !== void 0;
5016
+ if (current$1 === void 0) return {
4892
5017
  running: false,
4893
5018
  lines: [],
4894
- truncated: false
5019
+ truncated: false,
5020
+ installed,
5021
+ ...spec?.cliPath === void 0 ? {} : { cliPath: spec.cliPath }
4895
5022
  };
5023
+ const run = current$1;
4896
5024
  const lines = run.pending.trim() === "" ? run.lines : [...run.lines, run.pending.trim()];
4897
5025
  return {
4898
5026
  running: run.finishedAt === void 0,
@@ -4903,137 +5031,2806 @@ function readSetupStatus(brand = "cn") {
4903
5031
  code: run.code ?? null
4904
5032
  },
4905
5033
  lines,
4906
- truncated: run.truncated
5034
+ truncated: run.truncated,
5035
+ installed,
5036
+ ...spec?.cliPath === void 0 ? {} : { cliPath: spec.cliPath }
4907
5037
  };
4908
5038
  }
5039
+ /** Abandon a running installer. */
5040
+ function stopMinimaxSetup() {
5041
+ if (current$1 !== void 0 && current$1.finishedAt === void 0) current$1.child.kill();
5042
+ }
5043
+ /** A small object facade for callers that prefer a service shape. */
5044
+ var MinimaxCliSetup = class {
5045
+ start = startMinimaxSetup;
5046
+ status = readMinimaxSetupStatus;
5047
+ stop = stopMinimaxSetup;
5048
+ };
5049
+ //#endregion
5050
+ //#region src/minimax.ts
4909
5051
  /**
4910
- * Abandon the running helper, if any.
5052
+ * MiniMax Code over the Agent Client Protocol.
4911
5053
  *
4912
- * Called when the plugin is disposed. Killing `cmd.exe` does not reap the CLI it
4913
- * already launched, but the helper's own wait is bounded, so nothing hangs on
4914
- * the far end.
5054
+ * `mcode acp` is a stdio ACP server: the plugin starts one process per warm
5055
+ * host session, negotiates capabilities, creates one ACP session, and streams
5056
+ * `session/update` notifications back to the harness. Host tools are injected
5057
+ * as an HTTP MCP server (`mcpServers` in `session/new`), so a tool call the
5058
+ * model makes reaches this plugin and then the harness, exactly like the
5059
+ * CodeBuddy path.
5060
+ *
5061
+ * Two MiniMax behaviours shape this module:
5062
+ *
5063
+ * - ACP has no way to turn off the CLI's built-in tools. The model may call
5064
+ * `bash`/`write`/`read` directly, which would bypass the harness. The client
5065
+ * watches `tool_call` notifications and cancels the prompt before execution;
5066
+ * the turn is then retried with a correction. Host MCP tools are the only
5067
+ * calls allowed through.
5068
+ * - The CLI stores one auth state per region and selects it with
5069
+ * `MAVIS_REGION`; every process is pinned so the mainland and international
5070
+ * accounts can coexist.
5071
+ *
5072
+ * @module dsh-agent-sdk-bridge/minimax
4915
5073
  */
4916
- function stopSetup() {
4917
- for (const run of current.values()) if (run.finishedAt === void 0) run.child.kill();
5074
+ /** Default context capacity shown for a MiniMax model that declares none. */
5075
+ const MINIMAX_DEFAULT_CONTEXT_WINDOW = 512e3;
5076
+ /** Default output cap; the published MiniMax models allow 128k. */
5077
+ const MINIMAX_DEFAULT_MAX_TOKENS = 128e3;
5078
+ /** How long one model catalog stays fresh. */
5079
+ const MINIMAX_CACHE_TTL_MS = 3e5;
5080
+ /** Bound for one ACP control round trip. */
5081
+ const MINIMAX_FETCH_TIMEOUT_MS = 3e4;
5082
+ /** The MCP server name the model sees; its tools are `mcp__dsh-host__*`. */
5083
+ const MINIMAX_MCP_SERVER = "dsh-host";
5084
+ /** Context choices the hosted models publish. */
5085
+ const MINIMAX_CONTEXT_CHOICES = [MINIMAX_DEFAULT_CONTEXT_WINDOW, 1e6];
5086
+ /** How many native-tool corrections a turn may trigger before it fails. */
5087
+ const MAX_NATIVE_TOOL_RETRIES = 2;
5088
+ /** The per-user CLI state directory. */
5089
+ function minimaxDataDir() {
5090
+ const override = process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim();
5091
+ return override !== void 0 && override.length > 0 ? override : join(homedir(), ".minimax");
4918
5092
  }
4919
- //#endregion
4920
- //#region src/api.ts
4921
- /** Route prefix this plugin owns; the client resolves it relative to the page. */
4922
- const API_PREFIX = "/api/llm-qoder-cn";
4923
- /** Answer one request with JSON. */
4924
- function send(res, status, payload) {
4925
- const body = JSON.stringify(payload);
4926
- res.writeHead(status, {
4927
- "content-type": "application/json; charset=utf-8",
4928
- "cache-control": "no-store",
4929
- "content-length": Buffer.byteLength(body)
4930
- });
4931
- res.end(body);
5093
+ /** Path of one region's auth-state file. */
5094
+ function minimaxAuthStatePath(region) {
5095
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || "prod";
5096
+ return join(minimaxDataDir(), "auth", buildEnv, minimaxCliRegion(region), "mcode-public", "auth-state.json");
4932
5097
  }
4933
- /** Build model rows for a Qoder adapter. */
4934
- async function buildRows(adapter) {
4935
- return (await adapter.describeCatalog()).map((entry) => {
4936
- const override = adapter.contextWindowFor(entry.value);
4937
- const upstream = entry.defaultContextWindow ?? (entry.availableContextWindows !== void 0 && entry.availableContextWindows.length > 0 ? Math.max(...entry.availableContextWindows) : entry.maxInputTokens) ?? 2e5;
4938
- const choices = new Set(entry.availableContextWindows ?? []);
4939
- choices.add(upstream);
4940
- if (override !== void 0) choices.add(override);
4941
- const priceFactor = priceFactorOf(entry);
4942
- return {
4943
- id: entry.value,
4944
- name: entry.displayName.length > 0 ? entry.displayName : entry.value,
4945
- ...entry.description.length > 0 ? { description: entry.description } : {},
4946
- enabled: !adapter.isModelDisabled(entry.value),
4947
- vision: entry.isVl === true,
4948
- contextWindow: override ?? upstream,
4949
- contextWindows: [...choices].sort((a, b) => a - b),
4950
- defaultContextWindow: upstream,
4951
- ...override === void 0 ? {} : { override },
4952
- ...priceFactor === void 0 ? {} : { priceFactor },
4953
- reasoning: entry.isReasoning !== false
4954
- };
4955
- });
5098
+ /** Path of the credential file the CLI writes its OAuth token to. */
5099
+ function minimaxAuthRecordPath(region) {
5100
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || "prod";
5101
+ return join(minimaxDataDir(), "auth", buildEnv, minimaxCliRegion(region), "mcode-public", "auth.json");
4956
5102
  }
4957
- /** Build model rows for the CodeBuddy adapter, for one login region. */
4958
- async function buildCodeBuddyRows(adapter, region) {
4959
- return (await adapter.describeCatalog(region)).map((entry) => {
4960
- const override = adapter.contextWindowFor(entry.id, region);
4961
- const choices = new Set(entry.contextWindows);
4962
- choices.add(entry.defaultContextWindow);
4963
- if (override !== void 0) choices.add(override);
5103
+ /** The CLI command name, for error text. */
5104
+ function minimaxCliCommand() {
5105
+ return "mcode";
5106
+ }
5107
+ /** The host-side MCP namespace the CLI exposes for the injected server. */
5108
+ const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, "_")}__`];
5109
+ /** Whether a CLI tool name belongs to this plugin's MCP server. */
5110
+ function isHostMcpTool(name) {
5111
+ return HOST_TOOL_PREFIXES.some((prefix) => name.startsWith(prefix));
5112
+ }
5113
+ /** The host-side name of an MCP tool, without the namespace. */
5114
+ function hostMcpToolName(name) {
5115
+ for (const prefix of HOST_TOOL_PREFIXES) if (name.startsWith(prefix)) return name.slice(prefix.length);
5116
+ return name;
5117
+ }
5118
+ /** Thinking-effort values an ACP config option advertises, minus `default`. */
5119
+ function effortValues(options) {
5120
+ if (!Array.isArray(options)) return [];
5121
+ return options.map((entry) => typeof entry?.value === "string" ? entry.value : "").filter((value) => value.length > 0 && value !== "default");
5122
+ }
5123
+ /** Build one row from a model option entry and the efforts that model accepts. */
5124
+ function modelRow(entry, efforts) {
5125
+ if (typeof entry?.value !== "string" || entry.value.length === 0) return void 0;
5126
+ return {
5127
+ id: entry.value,
5128
+ name: typeof entry.name === "string" && entry.name.length > 0 ? entry.name : entry.value,
5129
+ ...typeof entry.description === "string" && entry.description.length > 0 ? { description: entry.description } : {},
5130
+ contextWindows: [...MINIMAX_CONTEXT_CHOICES],
5131
+ defaultContextWindow: MINIMAX_DEFAULT_CONTEXT_WINDOW,
5132
+ vision: true,
5133
+ reasoning: efforts.length > 0,
5134
+ reasoningEfforts: [...efforts]
5135
+ };
5136
+ }
5137
+ /** The model config option's values as rows. */
5138
+ function minimaxModelsFromConfigOptions(options) {
5139
+ if (!Array.isArray(options)) return [];
5140
+ const modelOption = options.find((option) => option?.category === "model" || option?.id === "model");
5141
+ const efforts = effortValues(options.find((option) => option?.id === "thinkingEffort" || option?.category === "thought_level")?.options);
5142
+ if (!Array.isArray(modelOption?.options)) return [];
5143
+ const seen = /* @__PURE__ */ new Set();
5144
+ const models = [];
5145
+ for (const entry of modelOption.options) {
5146
+ if (typeof entry?.value !== "string" || entry.value.length === 0 || seen.has(entry.value)) continue;
5147
+ seen.add(entry.value);
5148
+ const row = modelRow(entry, efforts);
5149
+ if (row !== void 0) models.push(row);
5150
+ }
5151
+ return models;
5152
+ }
5153
+ /**
5154
+ * Read one region's stored auth state, without spawning anything.
5155
+ *
5156
+ * The file records its own region; a copy left over from another build or a
5157
+ * CLI that rotates its layout must not be read as this region's login.
5158
+ */
5159
+ function readAuthState(region) {
5160
+ try {
5161
+ const parsed = JSON.parse(readFileSync(minimaxAuthStatePath(region), "utf8"));
5162
+ if (typeof parsed.region === "string" && parsed.region !== minimaxCliRegion(region)) return void 0;
4964
5163
  return {
4965
- id: entry.id,
4966
- name: entry.name,
4967
- ...entry.description === void 0 ? {} : { description: entry.description },
4968
- enabled: !adapter.isModelDisabled(entry.id, region),
4969
- vision: entry.vision,
4970
- contextWindow: override ?? entry.defaultContextWindow,
4971
- contextWindows: [...choices].sort((a, b) => a - b),
4972
- defaultContextWindow: entry.defaultContextWindow,
4973
- ...override === void 0 ? {} : { override },
4974
- ...entry.priceFactor === void 0 ? {} : { priceFactor: entry.priceFactor },
4975
- reasoning: (entry.reasoningEfforts?.length ?? 0) > 0
5164
+ ...typeof parsed.status === "string" ? { status: parsed.status } : {},
5165
+ ...typeof parsed.expiresAtMs === "number" ? { expiresAtMs: parsed.expiresAtMs } : {}
4976
5166
  };
4977
- });
4978
- }
4979
- /** Largest request body this route accepts. */
4980
- const MAX_BODY_BYTES = 2048;
4981
- /** Read and parse a small JSON request body. */
4982
- async function readJson(req) {
4983
- const chunks = [];
4984
- let size = 0;
4985
- for await (const part of req) {
4986
- const chunk = Buffer.isBuffer(part) ? part : Buffer.from(String(part));
4987
- size += chunk.length;
4988
- if (size > MAX_BODY_BYTES) throw new Error("请求体过大");
4989
- chunks.push(chunk);
5167
+ } catch {
5168
+ return;
4990
5169
  }
4991
- const text = Buffer.concat(chunks).toString("utf8").trim();
4992
- if (text === "") throw new Error("缺少请求体");
4993
- return JSON.parse(text);
4994
5170
  }
4995
- /** The brand a query-string or body selected, or undefined when it named none. */
4996
- function brandFrom(value) {
4997
- if (value === null || value === void 0 || value === "") return "cn";
4998
- return isBrandId(value) ? value : void 0;
5171
+ /** Whether the region has a stored login. */
5172
+ function minimaxSignedIn(region) {
5173
+ return readAuthState(region)?.status === "authenticated";
4999
5174
  }
5000
- /** A CodeBuddy region from a query or body, defaulting to the international one. */
5001
- function regionFrom(value) {
5002
- if (value === null || value === void 0 || value === "") return "global";
5003
- return isCodeBuddyRegion(value) ? value : void 0;
5175
+ /** Signed account gateway (the CLI's `agent` host). */
5176
+ const MINIMAX_ACCOUNT_HOSTS = {
5177
+ cn: "https://agent.minimaxi.com",
5178
+ global: "https://agent.minimax.io"
5179
+ };
5180
+ /** Host serving the coding-plan quota. */
5181
+ const MINIMAX_QUOTA_HOSTS = {
5182
+ cn: "https://www.minimaxi.com",
5183
+ global: "https://platform.minimax.io"
5184
+ };
5185
+ /** Salt the CLI signs account requests with. */
5186
+ const MINIMAX_ACCOUNT_SALT = "I*7Cf%WZ#S&%1RlZJ&C2";
5187
+ /** Bound for one account/quota read. */
5188
+ const MINIMAX_USAGE_TIMEOUT_MS = 15e3;
5189
+ /** How long one quota reading stays fresh. */
5190
+ const MINIMAX_USAGE_CACHE_TTL_MS = 6e4;
5191
+ /** Bound for one region-reachability probe. */
5192
+ const MINIMAX_REGION_PROBE_TIMEOUT_MS = 5e3;
5193
+ /** How long one reachability verdict stays fresh. */
5194
+ const MINIMAX_REGION_ACCESS_TTL_MS = 3e4;
5195
+ /** Domains the two sites serve their API and console from. */
5196
+ const MINIMAX_INTL_DOMAIN = "minimax.io";
5197
+ const MINIMAX_CN_DOMAIN = "minimaxi.com";
5198
+ function hostMatches(hostname, domain) {
5199
+ return hostname === domain || hostname.endsWith(`.${domain}`);
5004
5200
  }
5005
- /** Handle one request under {@link API_PREFIX}. */
5006
- async function handleApi(req, res, adapters) {
5007
- try {
5008
- const url = new URL(req.url ?? "/", "http://localhost");
5201
+ /**
5202
+ * Whether a URL points at the other site.
5203
+ *
5204
+ * MiniMax's edge answers a request from the wrong side of the border with a
5205
+ * 307 to the other site (`.io` -> `.minimaxi.com` and the reverse). The two
5206
+ * are different origins, so a redirect also drops the Authorization header;
5207
+ * that is why the CLI reports `401 token is required` instead of an
5208
+ * actionable error, and why a stale token is not the real cause.
5209
+ */
5210
+ function minimaxHostBelongsToOtherRegion(region, target) {
5211
+ let hostname;
5212
+ try {
5213
+ hostname = typeof target === "string" ? new URL(target).hostname : target.hostname;
5214
+ } catch {
5215
+ return false;
5216
+ }
5217
+ return region === "global" ? hostMatches(hostname, MINIMAX_CN_DOMAIN) : hostMatches(hostname, MINIMAX_INTL_DOMAIN);
5218
+ }
5219
+ /** The sentence the card and the chat surface show for a refused region. */
5220
+ function minimaxRegionBlockMessage(region) {
5221
+ return region === "global" ? "本机 IP 不在 MiniMax 国际站的服务区域,国际站已拒绝连接(请求被重定向到国内站)。请切换到国内站,或更换网络后重试。" : "本机 IP 不在 MiniMax 国内站的服务区域,国内站已拒绝连接(请求被重定向到国际站)。请切换到国际站,或更换网络后重试。";
5222
+ }
5223
+ /** A region whose hosts refused this machine's network. */
5224
+ var MinimaxRegionBlockedError = class extends Error {
5225
+ region;
5226
+ constructor(region) {
5227
+ super(minimaxRegionBlockMessage(region));
5228
+ this.region = region;
5229
+ this.name = "MinimaxRegionBlockedError";
5230
+ }
5231
+ };
5232
+ const regionAccessCache = /* @__PURE__ */ new Map();
5233
+ /**
5234
+ * Probes already on the wire.
5235
+ *
5236
+ * A region switch asks for the quota and the catalog at the same time, and
5237
+ * both need the same verdict; sharing the request keeps them from disagreeing
5238
+ * and spares the remote host a duplicate round trip.
5239
+ */
5240
+ const regionAccessInflight = /* @__PURE__ */ new Map();
5241
+ /** Forget a cached reachability verdict. */
5242
+ function invalidateMinimaxRegionAccess(region) {
5243
+ if (region === void 0) regionAccessCache.clear();
5244
+ else regionAccessCache.delete(region);
5245
+ }
5246
+ function rememberRegionAccess(region, blocked) {
5247
+ regionAccessCache.set(region, {
5248
+ at: Date.now(),
5249
+ blocked
5250
+ });
5251
+ }
5252
+ /** The last verdict, for synchronous rendering under the card. */
5253
+ function minimaxRegionBlockedCached(region) {
5254
+ const cached = regionAccessCache.get(region);
5255
+ return cached?.blocked === true && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS;
5256
+ }
5257
+ /**
5258
+ * Probe the region's account host for a cross-region redirect.
5259
+ *
5260
+ * Only a redirect to the other site's domain counts as a block. A timeout or
5261
+ * DNS failure leaves the previous verdict alone, so callers report the real
5262
+ * network error instead of blaming the IP.
5263
+ */
5264
+ async function minimaxRegionBlocked(region, options = {}) {
5265
+ const cached = regionAccessCache.get(region);
5266
+ if (options.fresh !== true && cached !== void 0 && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS) return cached.blocked;
5267
+ let pending = regionAccessInflight.get(region);
5268
+ if (pending === void 0) {
5269
+ pending = probeRegionAccess(region, options).finally(() => {
5270
+ regionAccessInflight.delete(region);
5271
+ });
5272
+ regionAccessInflight.set(region, pending);
5273
+ }
5274
+ return await pending;
5275
+ }
5276
+ async function probeRegionAccess(region, options) {
5277
+ const cached = regionAccessCache.get(region);
5278
+ const fetchImpl = options.fetchImpl ?? fetch;
5279
+ const timeout = AbortSignal.timeout(MINIMAX_REGION_PROBE_TIMEOUT_MS);
5280
+ const signal = options.signal === void 0 ? timeout : AbortSignal.any([options.signal, timeout]);
5281
+ try {
5282
+ const response = await fetchImpl(`${MINIMAX_ACCOUNT_HOSTS[region]}/`, {
5283
+ redirect: "manual",
5284
+ signal,
5285
+ headers: { Accept: "text/html,application/json" }
5286
+ });
5287
+ const location = response.headers.get("location");
5288
+ const blocked = response.status >= 300 && response.status < 400 && location !== null && minimaxHostBelongsToOtherRegion(region, location);
5289
+ rememberRegionAccess(region, blocked);
5290
+ return blocked;
5291
+ } catch {
5292
+ return cached?.blocked === true;
5293
+ }
5294
+ }
5295
+ /** Whether one response is the edge redirecting this machine to the other site. */
5296
+ function redirectTargetsOtherRegion(region, requestUrl, response) {
5297
+ if (response.status < 300 || response.status >= 400) return false;
5298
+ const location = response.headers.get("location");
5299
+ if (location === null) return false;
5300
+ try {
5301
+ return minimaxHostBelongsToOtherRegion(region, new URL(location, requestUrl));
5302
+ } catch {
5303
+ return false;
5304
+ }
5305
+ }
5306
+ function asRecord(value) {
5307
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5308
+ }
5309
+ function asNumber(value) {
5310
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
5311
+ if (typeof value === "string" && value.trim() !== "") {
5312
+ const parsed = Number(value);
5313
+ return Number.isFinite(parsed) ? parsed : void 0;
5314
+ }
5315
+ }
5316
+ function asString(value) {
5317
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5318
+ }
5319
+ /** Read the OAuth access token the CLI stored for one region. */
5320
+ function readStoredToken(region) {
5321
+ try {
5322
+ const parsed = JSON.parse(readFileSync(minimaxAuthRecordPath(region), "utf8"));
5323
+ for (const record of Object.values(parsed.records ?? {})) {
5324
+ const token = record?.accessToken;
5325
+ if (typeof token === "string" && token.trim().length > 0) return token.trim();
5326
+ }
5327
+ } catch {}
5328
+ }
5329
+ function minimaxMd5(value) {
5330
+ return createHash("md5").update(value).digest("hex");
5331
+ }
5332
+ /** Build one signed-gateway URL exactly as the CLI does. */
5333
+ function minimaxAccountUrl(region, path, nowMs, realUserId) {
5334
+ const url = new URL(path, MINIMAX_ACCOUNT_HOSTS[region]);
5335
+ const lang = region === "cn" ? "zh" : "en";
5336
+ url.search = new URLSearchParams({
5337
+ device_platform: "mcode",
5338
+ biz_id: "3",
5339
+ app_id: "3001",
5340
+ version_code: "22201",
5341
+ unix: String(nowMs),
5342
+ timezone_offset: String((/* @__PURE__ */ new Date()).getTimezoneOffset() * -60),
5343
+ sys_language: lang,
5344
+ lang,
5345
+ device_id: "0",
5346
+ os_name: process.platform,
5347
+ browser_name: "mcode",
5348
+ user_id: realUserId?.trim() || "0",
5349
+ client: "mcode"
5350
+ }).toString();
5351
+ return url;
5352
+ }
5353
+ /** One request to the signed gateway, with the CLI's signature headers. */
5354
+ async function minimaxAccountCall(region, path, call) {
5355
+ const now = Date.now();
5356
+ const url = minimaxAccountUrl(region, path, now, call.realUserId);
5357
+ const target = `${url.pathname}${url.search}`;
5358
+ const body = call.body === void 0 ? "" : JSON.stringify(call.body);
5359
+ const seconds = Math.floor(now / 1e3);
5360
+ const response = await call.fetchImpl(url, {
5361
+ method: call.method ?? "GET",
5362
+ redirect: "manual",
5363
+ headers: {
5364
+ Accept: "application/json",
5365
+ "Content-Type": "application/json",
5366
+ "User-Agent": "MiniMaxCode",
5367
+ Authorization: `Bearer ${call.token}`,
5368
+ yy: minimaxMd5(`${encodeURIComponent(target)}_${body}${minimaxMd5(String(now))}ooui`),
5369
+ "x-timestamp": String(seconds),
5370
+ "x-signature": minimaxMd5(`${seconds}${MINIMAX_ACCOUNT_SALT}${body}`)
5371
+ },
5372
+ ...body === "" ? {} : { body },
5373
+ ...call.signal === void 0 ? {} : { signal: call.signal }
5374
+ });
5375
+ if (redirectTargetsOtherRegion(region, url, response)) {
5376
+ rememberRegionAccess(region, true);
5377
+ throw new MinimaxRegionBlockedError(region);
5378
+ }
5379
+ if (response.status >= 300 && response.status < 400) throw new Error(`MiniMax 账号接口返回了意外的重定向(HTTP ${response.status})。`);
5380
+ if (!response.ok) {
5381
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) throw new MinimaxRegionBlockedError(region);
5382
+ throw new Error(response.status === 401 || response.status === 403 ? "MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。" : `MiniMax 账号接口返回 HTTP ${response.status}。`);
5383
+ }
5384
+ const payload = asRecord(await response.json());
5385
+ if (payload === void 0) throw new Error("MiniMax 账号接口返回了无法解析的响应。");
5386
+ const statusInfo = asRecord(payload.statusInfo);
5387
+ const statusCode = asNumber(statusInfo?.code);
5388
+ if (statusCode !== void 0 && statusCode !== 0) throw new Error(asString(statusInfo?.message) ?? `MiniMax 账号接口错误 ${statusCode}。`);
5389
+ const baseResp = asRecord(payload.base_resp);
5390
+ const baseCode = asNumber(baseResp?.status_code);
5391
+ if (baseCode !== void 0 && baseCode !== 0) throw new Error(asString(baseResp?.status_msg) ?? `MiniMax 账号接口错误 ${baseCode}。`);
5392
+ return payload;
5393
+ }
5394
+ /** One window's numbers, named the way the coding-plan endpoint reports them. */
5395
+ function quotaWindow(bucket, kind) {
5396
+ const prefix = kind === "interval" ? "current_interval" : "current_weekly";
5397
+ const unlimited = asNumber(bucket[`${prefix}_status`]) === 3;
5398
+ const percent = asNumber(bucket[`${prefix}_remaining_percent`]);
5399
+ const total = asNumber(bucket[`${prefix}_total_count`]);
5400
+ const used = asNumber(bucket[`${prefix}_usage_count`]);
5401
+ const remaining = percent ?? (total !== void 0 && total > 0 && used !== void 0 ? used / total * 100 : void 0);
5402
+ const resetAt = asNumber(bucket[kind === "interval" ? "end_time" : "weekly_end_time"]);
5403
+ if (remaining === void 0 && !unlimited && (resetAt === void 0 || resetAt <= 0)) return void 0;
5404
+ return {
5405
+ ...remaining === void 0 || unlimited ? {} : { remainingPercent: Math.round(Math.min(100, Math.max(0, remaining))) },
5406
+ ...resetAt !== void 0 && resetAt > 0 ? { resetAt } : {},
5407
+ unlimited,
5408
+ ...kind === "interval" && used !== void 0 ? { remainingCount: Math.max(0, used) } : {},
5409
+ ...kind === "interval" && total !== void 0 ? { totalCount: Math.max(0, total) } : {}
5410
+ };
5411
+ }
5412
+ /** Turn one `model_remains` bucket into its 5-hour and weekly rows. */
5413
+ function windowRows(id, label, bucket) {
5414
+ const rows = [];
5415
+ const interval = quotaWindow(bucket, "interval");
5416
+ if (interval !== void 0) rows.push({
5417
+ id: `${id}:5h`,
5418
+ label: `${label} · 5 小时`,
5419
+ ...interval
5420
+ });
5421
+ const weekly = quotaWindow(bucket, "weekly");
5422
+ if (weekly !== void 0) rows.push({
5423
+ id: `${id}:7d`,
5424
+ label: `${label} · 本周`,
5425
+ ...weekly
5426
+ });
5427
+ return rows;
5428
+ }
5429
+ /** Parse `/v1/api/openplatform/coding_plan/remains`. */
5430
+ function parseMinimaxRemains(payload) {
5431
+ if (payload === void 0) return [];
5432
+ const code = asNumber(asRecord(payload.base_resp)?.status_code);
5433
+ if (code !== void 0 && code !== 0) return [];
5434
+ const buckets = Array.isArray(payload.model_remains) ? payload.model_remains.map(asRecord).filter((bucket) => bucket !== void 0) : [];
5435
+ const rows = [];
5436
+ const general = buckets[0];
5437
+ if (general !== void 0) rows.push(...windowRows("general", "通用", general));
5438
+ const video = buckets.find((bucket) => {
5439
+ const name = asString(bucket.model_name) ?? "";
5440
+ return /video/i.test(name) && (asNumber(bucket.current_interval_total_count) ?? 0) > 0;
5441
+ });
5442
+ if (video !== void 0) rows.push(...windowRows("video", "视频", video));
5443
+ return rows;
5444
+ }
5445
+ /**
5446
+ * Build a snapshot from the three account documents.
5447
+ *
5448
+ * Split out from the network path so the mapping is testable without a live
5449
+ * account: the membership record is the source of the plan and credit
5450
+ * balance, `remains` only exists for token-plan subscribers.
5451
+ */
5452
+ function minimaxUsageFromParts(parts) {
5453
+ const userInfo = parts.userInfo ?? {};
5454
+ const membership = parts.membership ?? {};
5455
+ const personal = parts.workspaces?.find((workspace) => asNumber(workspace.workspace_type) === 0) ?? parts.workspaces?.[0];
5456
+ const name = asString(userInfo.name);
5457
+ const email = asString(userInfo.email);
5458
+ const avatar = asString(userInfo.avatar);
5459
+ const userId = asString(userInfo.userID);
5460
+ const account = name === void 0 && email === void 0 && avatar === void 0 && userId === void 0 ? void 0 : {
5461
+ ...name === void 0 ? {} : { name },
5462
+ ...email === void 0 ? {} : { email },
5463
+ ...avatar === void 0 ? {} : { avatar },
5464
+ ...userId === void 0 ? {} : { userId }
5465
+ };
5466
+ const summary = asRecord(membership.op_credit_summary) ?? asRecord(personal?.op_credit_summary);
5467
+ const remaining = asNumber(summary?.total_remaining_amount) ?? asNumber(personal?.opcredit_balance) ?? asNumber(membership.opcredit_balance);
5468
+ const purchased = asNumber(summary?.purchased_remaining_amount);
5469
+ const free = asNumber(summary?.free_remaining_amount);
5470
+ const credits = remaining === void 0 ? void 0 : {
5471
+ remaining,
5472
+ ...purchased === void 0 ? {} : { purchasedRemaining: purchased },
5473
+ ...free === void 0 ? {} : { freeRemaining: free }
5474
+ };
5475
+ const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true;
5476
+ const kind = hasTokenPlan ? "token-plan" : credits !== void 0 && credits.remaining > 0 ? "credits" : "free";
5477
+ const planName = asString(membership.plan_name) ?? asString(personal?.plan_name);
5478
+ const tier = asString(membership.token_plan_tier) ?? asString(personal?.token_plan_tier);
5479
+ const expiresRaw = asNumber(membership.token_plan_expires_at) ?? asNumber(personal?.token_plan_expires_at) ?? asNumber(membership.expires_at);
5480
+ const expiresAt = expiresRaw !== void 0 && expiresRaw > 0 ? expiresRaw : void 0;
5481
+ const subscriptionType = asString(membership.subscription_type);
5482
+ const windows = parseMinimaxRemains(parts.remains);
5483
+ return {
5484
+ at: parts.at ?? Date.now(),
5485
+ region: parts.region,
5486
+ signedIn: true,
5487
+ installed: parts.installed ?? true,
5488
+ ...account === void 0 ? {} : { account },
5489
+ plan: {
5490
+ kind,
5491
+ hasTokenPlan,
5492
+ ...planName === void 0 ? {} : { name: planName },
5493
+ ...tier === void 0 ? {} : { tier },
5494
+ ...expiresAt === void 0 ? {} : { expiresAt },
5495
+ ...subscriptionType === void 0 ? {} : { subscriptionType }
5496
+ },
5497
+ ...credits === void 0 ? {} : { credits },
5498
+ ...windows.length === 0 ? {} : { windows }
5499
+ };
5500
+ }
5501
+ /** Read the quota for a token-plan subscriber; a plain account has none. */
5502
+ async function readMinimaxRemains(region, token, groupId, fetchImpl, signal) {
5503
+ const url = new URL("/v1/api/openplatform/coding_plan/remains", MINIMAX_QUOTA_HOSTS[region]);
5504
+ const response = await fetchImpl(url, {
5505
+ redirect: "manual",
5506
+ headers: {
5507
+ Accept: "application/json",
5508
+ Authorization: `Bearer ${token}`,
5509
+ "X-Group-Id": groupId
5510
+ },
5511
+ signal
5512
+ });
5513
+ if (redirectTargetsOtherRegion(region, url, response)) {
5514
+ rememberRegionAccess(region, true);
5515
+ throw new MinimaxRegionBlockedError(region);
5516
+ }
5517
+ if (response.status >= 300 && response.status < 400) return void 0;
5518
+ if (!response.ok) {
5519
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) throw new MinimaxRegionBlockedError(region);
5520
+ if (response.status === 401 || response.status === 403) throw new Error("MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。");
5521
+ return;
5522
+ }
5523
+ return asRecord(await response.json());
5524
+ }
5525
+ const usageCache = /* @__PURE__ */ new Map();
5526
+ const usageInflight = /* @__PURE__ */ new Map();
5527
+ /** Drop a cached quota reading, so the next request re-reads it. */
5528
+ function invalidateMinimaxUsage(region) {
5529
+ if (region === void 0) {
5530
+ usageCache.clear();
5531
+ return;
5532
+ }
5533
+ usageCache.delete(region);
5534
+ }
5535
+ /**
5536
+ * Read one region's account, plan and quota.
5537
+ *
5538
+ * A failed account call keeps the login state and reports the reason in
5539
+ * `error`; the settings card shows the account it already knows with that
5540
+ * message instead of silently claiming nothing is configured.
5541
+ */
5542
+ async function minimaxUsage(region, options = {}) {
5543
+ const installed = resolveMinimaxCli() !== void 0;
5544
+ const token = options.token ?? readStoredToken(region);
5545
+ if (!(token !== void 0 || minimaxSignedIn(region))) return {
5546
+ at: Date.now(),
5547
+ region,
5548
+ signedIn: false,
5549
+ installed
5550
+ };
5551
+ if (await minimaxRegionBlocked(region, {
5552
+ fresh: options.fresh,
5553
+ fetchImpl: options.fetchImpl,
5554
+ signal: options.signal
5555
+ })) return {
5556
+ at: Date.now(),
5557
+ region,
5558
+ signedIn: true,
5559
+ installed,
5560
+ regionBlocked: true,
5561
+ error: minimaxRegionBlockMessage(region)
5562
+ };
5563
+ if (token === void 0) return {
5564
+ at: Date.now(),
5565
+ region,
5566
+ signedIn: true,
5567
+ installed,
5568
+ error: "未找到 MiniMax 登录凭据,请重新登录。"
5569
+ };
5570
+ if (options.token === void 0 && options.fresh !== true) {
5571
+ const cached = usageCache.get(region);
5572
+ if (cached !== void 0 && Date.now() - cached.at < 6e4) return cached.snapshot;
5573
+ }
5574
+ let pending = usageInflight.get(region);
5575
+ if (pending === void 0) {
5576
+ pending = readUsage(region, token, installed, options).finally(() => {
5577
+ usageInflight.delete(region);
5578
+ });
5579
+ usageInflight.set(region, pending);
5580
+ }
5581
+ const snapshot = await pending;
5582
+ if (snapshot.error === void 0 && options.token === void 0) usageCache.set(region, {
5583
+ at: snapshot.at,
5584
+ snapshot
5585
+ });
5586
+ return snapshot;
5587
+ }
5588
+ async function readUsage(region, token, installed, options) {
5589
+ const timeout = AbortSignal.timeout(MINIMAX_USAGE_TIMEOUT_MS);
5590
+ const signal = options.signal === void 0 ? timeout : AbortSignal.any([options.signal, timeout]);
5591
+ const fetchImpl = options.fetchImpl ?? fetch;
5592
+ try {
5593
+ const info = await minimaxAccountCall(region, "/v1/api/user/info", {
5594
+ token,
5595
+ fetchImpl,
5596
+ signal
5597
+ });
5598
+ const userInfo = asRecord(asRecord(info.data)?.userInfo) ?? asRecord(info.userInfo) ?? {};
5599
+ const realUserId = asString(userInfo.realUserID) ?? asString(userInfo.real_user_id);
5600
+ const extra = await minimaxAccountCall(region, "/matrix/api/v1/user/get_user_extra_info", {
5601
+ method: "POST",
5602
+ body: {},
5603
+ realUserId,
5604
+ token,
5605
+ fetchImpl,
5606
+ signal
5607
+ });
5608
+ 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);
5609
+ const personal = workspaces.find((workspace) => asNumber(workspace.workspace_type) === 0) ?? workspaces[0];
5610
+ const workspaceId = asNumber(personal?.workspace_id);
5611
+ const membership = workspaceId === void 0 ? {} : await minimaxAccountCall(region, "/matrix/api/v1/commerce/get_membership_info", {
5612
+ method: "POST",
5613
+ body: { workspace_id: workspaceId },
5614
+ realUserId,
5615
+ token,
5616
+ fetchImpl,
5617
+ signal
5618
+ });
5619
+ const groupId = asString(membership.op_group_id) ?? asString(personal?.op_group_id);
5620
+ return minimaxUsageFromParts({
5621
+ region,
5622
+ installed,
5623
+ userInfo,
5624
+ workspaces,
5625
+ membership,
5626
+ remains: (membership.has_token_plan === true || personal?.has_token_plan === true) && groupId !== void 0 ? await readMinimaxRemains(region, token, groupId, fetchImpl, signal) : void 0
5627
+ });
5628
+ } catch (error) {
5629
+ const blocked = error instanceof MinimaxRegionBlockedError;
5630
+ return {
5631
+ at: Date.now(),
5632
+ region,
5633
+ signedIn: true,
5634
+ installed,
5635
+ ...blocked ? { regionBlocked: true } : {},
5636
+ error: blocked ? minimaxRegionBlockMessage(region) : error instanceof Error ? error.message : String(error)
5637
+ };
5638
+ }
5639
+ }
5640
+ /** Trim CLI output to a short, token-free sentence. */
5641
+ function outputTail(lines) {
5642
+ return lines.slice(-4).map((line) => line.replace(/mmo(at|rt)_[A-Za-z0-9_-]+/g, "mmo***")).join(" ").slice(0, 400);
5643
+ }
5644
+ /**
5645
+ * Browser login/logout, one run per region.
5646
+ *
5647
+ * The CLI owns the OAuth device flow and the credential file. The plugin only
5648
+ * starts the process, surfaces the authorization URL while it waits, and then
5649
+ * re-reads the auth-state file to decide whether the region is signed in.
5650
+ */
5651
+ var MinimaxAuth = class {
5652
+ runs = /* @__PURE__ */ new Map();
5653
+ status(region) {
5654
+ const run = this.runs.get(region);
5655
+ if (run !== void 0) return run.status;
5656
+ const state = readAuthState(region);
5657
+ return {
5658
+ running: false,
5659
+ region,
5660
+ signedIn: state?.status === "authenticated",
5661
+ ...state?.expiresAtMs === void 0 ? {} : { expiresAt: state.expiresAtMs }
5662
+ };
5663
+ }
5664
+ /** Start the CLI's browser login. */
5665
+ start(region, onFinish) {
5666
+ const existing = this.runs.get(region);
5667
+ if (existing !== void 0 && existing.status.running) return {
5668
+ started: false,
5669
+ error: "该区域正在登录,请先在浏览器中完成授权。"
5670
+ };
5671
+ const spec = resolveMinimaxCli();
5672
+ if (spec === void 0) return {
5673
+ started: false,
5674
+ error: "未安装 MiniMax Code CLI(mcode),请先安装后再登录。"
5675
+ };
5676
+ const status = {
5677
+ running: true,
5678
+ region,
5679
+ signedIn: false,
5680
+ startedAt: Date.now()
5681
+ };
5682
+ const run = {
5683
+ status,
5684
+ child: void 0,
5685
+ lines: [],
5686
+ finish: (_code) => {}
5687
+ };
5688
+ const env = {
5689
+ ...process.env,
5690
+ MAVIS_REGION: minimaxCliRegion(region)
5691
+ };
5692
+ delete env.MAVIS_AGENT;
5693
+ delete env.MAVIS_SESSION;
5694
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
5695
+ "login",
5696
+ "--region",
5697
+ region === "cn" ? "cn" : "global"
5698
+ ]), {
5699
+ cwd: homedir(),
5700
+ env,
5701
+ windowsHide: true,
5702
+ stdio: [
5703
+ "ignore",
5704
+ "pipe",
5705
+ "pipe"
5706
+ ]
5707
+ });
5708
+ run.child = child;
5709
+ this.runs.set(region, run);
5710
+ const absorb = (chunk) => {
5711
+ const text = String(chunk);
5712
+ for (const line of text.split(/\r?\n/)) {
5713
+ const trimmed = line.trim();
5714
+ if (trimmed === "") continue;
5715
+ run.lines.push(trimmed);
5716
+ const match = /^(?:Open:\s*)?(https?:\/\/\S+)/.exec(trimmed);
5717
+ if (match !== null) status.url = match[1];
5718
+ }
5719
+ while (run.lines.length > 40) run.lines.shift();
5720
+ };
5721
+ child.stdout?.on("data", absorb);
5722
+ child.stderr?.on("data", absorb);
5723
+ const finish = (code) => {
5724
+ if (!status.running) return;
5725
+ status.running = false;
5726
+ status.finishedAt = Date.now();
5727
+ const state = readAuthState(region);
5728
+ status.signedIn = state?.status === "authenticated";
5729
+ if (state?.expiresAtMs !== void 0) status.expiresAt = state.expiresAtMs;
5730
+ if (code !== 0) status.error = outputTail(run.lines) || "登录未完成";
5731
+ else if (!status.signedIn) status.error = outputTail(run.lines) || "登录未完成";
5732
+ try {
5733
+ onFinish?.(status.signedIn);
5734
+ } catch {}
5735
+ };
5736
+ run.finish = finish;
5737
+ child.on("error", (error) => {
5738
+ status.error = `无法启动 mcode:${error.message}`;
5739
+ finish(null);
5740
+ });
5741
+ child.on("close", (code) => {
5742
+ finish(code);
5743
+ });
5744
+ return { started: true };
5745
+ }
5746
+ /** Sign one region out; the other region is untouched. */
5747
+ async logout(region) {
5748
+ const spec = resolveMinimaxCli();
5749
+ if (spec === void 0) return {
5750
+ running: false,
5751
+ region,
5752
+ signedIn: false,
5753
+ error: "未安装 MiniMax Code CLI(mcode)。"
5754
+ };
5755
+ const env = {
5756
+ ...process.env,
5757
+ MAVIS_REGION: minimaxCliRegion(region)
5758
+ };
5759
+ delete env.MAVIS_AGENT;
5760
+ delete env.MAVIS_SESSION;
5761
+ const result = await new Promise((resolve) => {
5762
+ const lines = [];
5763
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
5764
+ "logout",
5765
+ "--region",
5766
+ region === "cn" ? "cn" : "global"
5767
+ ]), {
5768
+ cwd: homedir(),
5769
+ env,
5770
+ windowsHide: true,
5771
+ stdio: [
5772
+ "ignore",
5773
+ "pipe",
5774
+ "pipe"
5775
+ ]
5776
+ });
5777
+ const absorb = (chunk) => {
5778
+ for (const line of String(chunk).split(/\r?\n/)) if (line.trim() !== "") lines.push(line.trim());
5779
+ while (lines.length > 40) lines.shift();
5780
+ };
5781
+ child.stdout?.on("data", absorb);
5782
+ child.stderr?.on("data", absorb);
5783
+ const timer = setTimeout(() => {
5784
+ child.kill();
5785
+ resolve({
5786
+ code: null,
5787
+ lines
5788
+ });
5789
+ }, 2e4);
5790
+ child.on("error", () => {
5791
+ clearTimeout(timer);
5792
+ resolve({
5793
+ code: null,
5794
+ lines
5795
+ });
5796
+ });
5797
+ child.on("close", (code) => {
5798
+ clearTimeout(timer);
5799
+ resolve({
5800
+ code,
5801
+ lines
5802
+ });
5803
+ });
5804
+ });
5805
+ this.runs.delete(region);
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
+ ...result.code !== 0 ? { error: outputTail(result.lines) || "退出登录未完成" } : {}
5813
+ };
5814
+ }
5815
+ /** Cancel any login process (plugin disposal). */
5816
+ stop() {
5817
+ for (const run of this.runs.values()) if (run.status.running) run.child.kill();
5818
+ }
5819
+ };
5820
+ /** A single-consumer async event queue. */
5821
+ var EventQueue = class {
5822
+ items = [];
5823
+ waiter = null;
5824
+ closed = false;
5825
+ push(event) {
5826
+ if (this.closed) return;
5827
+ if (this.waiter !== null) {
5828
+ const settle = this.waiter;
5829
+ this.waiter = null;
5830
+ settle(event);
5831
+ return;
5832
+ }
5833
+ this.items.push(event);
5834
+ }
5835
+ close() {
5836
+ if (this.closed) return;
5837
+ this.closed = true;
5838
+ if (this.waiter !== null) {
5839
+ const settle = this.waiter;
5840
+ this.waiter = null;
5841
+ settle(void 0);
5842
+ }
5843
+ }
5844
+ get isClosed() {
5845
+ return this.closed;
5846
+ }
5847
+ next() {
5848
+ const item = this.items.shift();
5849
+ if (item !== void 0) return Promise.resolve(item);
5850
+ if (this.closed) return Promise.resolve(void 0);
5851
+ return new Promise((resolve) => {
5852
+ this.waiter = resolve;
5853
+ });
5854
+ }
5855
+ };
5856
+ /** Render a harness tool result for the MCP caller. */
5857
+ function renderToolResult(content) {
5858
+ const text = (value) => {
5859
+ if (typeof value === "string") return value;
5860
+ if (value === null || value === void 0) return "";
5861
+ try {
5862
+ return JSON.stringify(value);
5863
+ } catch {
5864
+ return String(value);
5865
+ }
5866
+ };
5867
+ if (Array.isArray(content)) {
5868
+ const parts = [];
5869
+ for (const block of content) {
5870
+ if (typeof block === "string") {
5871
+ parts.push(block);
5872
+ continue;
5873
+ }
5874
+ if (block !== null && typeof block === "object" && block.type === "text") {
5875
+ parts.push(text(block.text));
5876
+ continue;
5877
+ }
5878
+ parts.push(text(block));
5879
+ }
5880
+ const joined = parts.join("\n").trim();
5881
+ return { content: [{
5882
+ type: "text",
5883
+ text: joined === "" ? "(宿主工具没有返回内容)" : joined
5884
+ }] };
5885
+ }
5886
+ const joined = text(content).trim();
5887
+ return { content: [{
5888
+ type: "text",
5889
+ text: joined === "" ? "(宿主工具没有返回内容)" : joined
5890
+ }] };
5891
+ }
5892
+ /**
5893
+ * One `mcode acp` process and its ACP session.
5894
+ *
5895
+ * The class only speaks protocol: model/effort config, prompts, cancellation,
5896
+ * and the translation of `session/update` into {@link SessionEvent}s. Turn
5897
+ * policy (tool calls, retries, harness chunks) lives in {@link MinimaxSession}.
5898
+ */
5899
+ var MinimaxAcp = class {
5900
+ child = null;
5901
+ conn = null;
5902
+ sessionId;
5903
+ configOptions = [];
5904
+ systemFile;
5905
+ tempDir;
5906
+ closing = false;
5907
+ stderr = [];
5908
+ options;
5909
+ constructor(options) {
5910
+ this.options = options;
5911
+ }
5912
+ /** The model/effort options the CLI currently offers. */
5913
+ get optionsList() {
5914
+ return this.configOptions;
5915
+ }
5916
+ /** The selected model config value. */
5917
+ get currentModel() {
5918
+ const option = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
5919
+ return typeof option?.currentValue === "string" ? option.currentValue : void 0;
5920
+ }
5921
+ /** Start the process and create one ACP session. */
5922
+ async start() {
5923
+ const spec = resolveMinimaxCli();
5924
+ if (spec === void 0) throw new Error("未安装 MiniMax Code CLI(mcode)。请在设置页安装,或运行 npm install -g @minimax-ai/code。");
5925
+ const timeout = this.options.timeoutMs ?? 3e4;
5926
+ const directory = mkdtempSync(join(tmpdir(), "dsh-minimax-acp-"));
5927
+ const systemFile = join(directory, "system.md");
5928
+ writeFileSync(systemFile, this.options.systemPrompt, "utf8");
5929
+ this.systemFile = systemFile;
5930
+ this.tempDir = directory;
5931
+ const env = {
5932
+ ...process.env,
5933
+ MAVIS_REGION: minimaxCliRegion(this.options.region),
5934
+ ...this.options.disableTools === true ? { MAVIS_LOCAL_RUNTIME_DISABLE_TOOLS: "1" } : {}
5935
+ };
5936
+ delete env.MAVIS_AGENT;
5937
+ delete env.MAVIS_SESSION;
5938
+ const child = spawn(spec.command, minimaxCliArgs(spec, [
5939
+ "acp",
5940
+ "--system-prompt-file",
5941
+ systemFile
5942
+ ]), {
5943
+ cwd: this.options.cwd,
5944
+ env,
5945
+ windowsHide: true,
5946
+ stdio: [
5947
+ "pipe",
5948
+ "pipe",
5949
+ "pipe"
5950
+ ]
5951
+ });
5952
+ this.child = child;
5953
+ child.stderr?.on("data", (chunk) => {
5954
+ for (const line of String(chunk).split(/\r?\n/)) if (line.trim() !== "") this.stderr.push(line.trim());
5955
+ while (this.stderr.length > 30) this.stderr.shift();
5956
+ });
5957
+ child.on("exit", (code, signal) => {
5958
+ if (this.closing) return;
5959
+ const detail = outputTail(this.stderr) || `mcode acp 退出(code=${String(code)}, signal=${String(signal)})`;
5960
+ this.options.onExit?.(new Error(detail));
5961
+ });
5962
+ if (child.stdin === null || child.stdout === null) throw new Error("mcode acp 没有可用的 stdio。");
5963
+ const client = {
5964
+ sessionUpdate: (params) => {
5965
+ if (params.sessionId !== void 0 && this.sessionId !== void 0 && params.sessionId !== this.sessionId) return;
5966
+ const update = params.update;
5967
+ if (update === null || typeof update !== "object") return;
5968
+ switch (update.sessionUpdate) {
5969
+ case "agent_message_chunk": {
5970
+ const text = typeof update.content?.text === "string" ? update.content.text : "";
5971
+ if (text.length > 0) this.options.onUpdate?.({
5972
+ kind: "text",
5973
+ text
5974
+ });
5975
+ return;
5976
+ }
5977
+ case "agent_thought_chunk": {
5978
+ const text = typeof update.content?.text === "string" ? update.content.text : "";
5979
+ if (text.length > 0) this.options.onUpdate?.({
5980
+ kind: "reasoning",
5981
+ text
5982
+ });
5983
+ return;
5984
+ }
5985
+ case "usage_update": {
5986
+ const used = typeof update.used === "number" ? update.used : 0;
5987
+ const size = typeof update.size === "number" ? update.size : 0;
5988
+ if (size > 0) this.options.onUpdate?.({
5989
+ kind: "usage",
5990
+ used,
5991
+ size
5992
+ });
5993
+ return;
5994
+ }
5995
+ case "tool_call":
5996
+ case "tool_call_update": {
5997
+ const name = typeof update.title === "string" && update.title.length > 0 ? update.title : typeof update.name === "string" ? update.name : "";
5998
+ if (name.length === 0) return;
5999
+ if (!isHostMcpTool(name)) {
6000
+ if (update.sessionUpdate === "tool_call" || update.status === "in_progress") this.options.onUpdate?.({
6001
+ kind: "native-tool",
6002
+ name
6003
+ });
6004
+ return;
6005
+ }
6006
+ return;
6007
+ }
6008
+ default: return;
6009
+ }
6010
+ },
6011
+ requestPermission: async (params) => {
6012
+ const name = typeof params?.toolCall?.title === "string" && params.toolCall.title.length > 0 ? params.toolCall.title : typeof params?.toolCall?.name === "string" ? params.toolCall.name : "";
6013
+ const options = Array.isArray(params?.options) ? params.options : [];
6014
+ if (isHostMcpTool(name)) {
6015
+ const allow = options.find((entry) => entry?.kind === "allow_once") ?? options.find((entry) => entry?.kind === "allow_always") ?? options[0];
6016
+ if (allow !== void 0) return { outcome: {
6017
+ outcome: "selected",
6018
+ optionId: allow.optionId
6019
+ } };
6020
+ return { outcome: { outcome: "cancelled" } };
6021
+ }
6022
+ this.options.onPermissionDenied?.(name);
6023
+ const deny = options.find((entry) => entry?.kind === "reject_once") ?? options.find((entry) => entry?.kind === "reject_always");
6024
+ return deny === void 0 ? { outcome: { outcome: "cancelled" } } : { outcome: {
6025
+ outcome: "selected",
6026
+ optionId: deny.optionId
6027
+ } };
6028
+ }
6029
+ };
6030
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
6031
+ const conn = new ClientSideConnection(() => client, stream);
6032
+ this.conn = conn;
6033
+ await withTimeout(conn.initialize({
6034
+ protocolVersion: PROTOCOL_VERSION,
6035
+ clientCapabilities: {
6036
+ fs: {
6037
+ readTextFile: false,
6038
+ writeTextFile: false
6039
+ },
6040
+ terminal: false
6041
+ },
6042
+ clientInfo: {
6043
+ name: "dsh-agent-sdk-bridge",
6044
+ version: "1.1.0"
6045
+ }
6046
+ }), timeout, "mcode acp initialize");
6047
+ const mcpServers = this.options.mcpUrl === void 0 ? [] : [{
6048
+ type: "http",
6049
+ name: MINIMAX_MCP_SERVER,
6050
+ url: this.options.mcpUrl,
6051
+ headers: [{
6052
+ name: "Authorization",
6053
+ value: `Bearer ${this.options.mcpToken ?? ""}`
6054
+ }]
6055
+ }];
6056
+ const session = await withTimeout(conn.newSession({
6057
+ cwd: this.options.cwd,
6058
+ mcpServers
6059
+ }), timeout, "mcode acp session/new");
6060
+ this.sessionId = session.sessionId;
6061
+ this.configOptions = Array.isArray(session.configOptions) ? [...session.configOptions] : [];
6062
+ }
6063
+ /** Run one prompt; resolves when the agent's turn ends. */
6064
+ async prompt(text) {
6065
+ if (this.conn === null || this.sessionId === void 0) throw new Error("ACP 会话尚未启动。");
6066
+ const response = await this.conn.prompt({
6067
+ sessionId: this.sessionId,
6068
+ prompt: [{
6069
+ type: "text",
6070
+ text
6071
+ }]
6072
+ });
6073
+ return { stopReason: String(response.stopReason) };
6074
+ }
6075
+ /** Ask the agent to stop the active turn. */
6076
+ async cancel() {
6077
+ if (this.conn === null || this.sessionId === void 0) return;
6078
+ try {
6079
+ await this.conn.cancel({ sessionId: this.sessionId });
6080
+ } catch {}
6081
+ }
6082
+ /** Set a session config option and remember the updated list. */
6083
+ async setConfig(id, value) {
6084
+ if (this.conn === null || this.sessionId === void 0) return;
6085
+ const option = this.configOptions.find((entry) => entry?.id === id);
6086
+ if (option === void 0) return;
6087
+ if (option.currentValue === value) return;
6088
+ if (!(Array.isArray(option.options) ? option.options.some((entry) => entry?.value === value) : true)) return;
6089
+ const response = await this.conn.setSessionConfigOption({
6090
+ sessionId: this.sessionId,
6091
+ configId: id,
6092
+ value
6093
+ });
6094
+ if (Array.isArray(response.configOptions)) this.configOptions = [...response.configOptions];
6095
+ }
6096
+ /**
6097
+ * List the models the CLI actually accepts, with each model's own efforts.
6098
+ *
6099
+ * The advertised option list can contain values the agent rejects (0.6.12
6100
+ * lists a `M3.1-Flash` non-thinking value and answers `Invalid model
6101
+ * reasoning` when it is selected). Selecting each value once is the only
6102
+ * reliable filter, and it also reveals that non-thinking models drop the
6103
+ * `thinkingEffort` option entirely, so reasoning has to be reported per
6104
+ * model rather than once for the catalog.
6105
+ */
6106
+ async probeModels() {
6107
+ const modelOption = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
6108
+ if (!Array.isArray(modelOption?.options)) return [];
6109
+ const initial = typeof modelOption.currentValue === "string" ? modelOption.currentValue : void 0;
6110
+ const seen = /* @__PURE__ */ new Set();
6111
+ const models = [];
6112
+ for (const entry of modelOption.options) {
6113
+ if (typeof entry?.value !== "string" || entry.value.length === 0 || seen.has(entry.value)) continue;
6114
+ seen.add(entry.value);
6115
+ try {
6116
+ await this.setConfig(String(modelOption.id), entry.value);
6117
+ } catch {
6118
+ continue;
6119
+ }
6120
+ const row = modelRow(entry, effortValues(this.configOptions.find((option) => option?.id === "thinkingEffort" || option?.category === "thought_level")?.options));
6121
+ if (row !== void 0) models.push(row);
6122
+ }
6123
+ if (initial !== void 0 && this.currentModel !== initial) try {
6124
+ await this.setConfig(String(modelOption.id), initial);
6125
+ } catch {}
6126
+ return models;
6127
+ }
6128
+ /** Select the model (and, when supported, the thinking effort). */
6129
+ async selectModel(model, effort) {
6130
+ const modelOption = this.configOptions.find((entry) => entry?.category === "model" || entry?.id === "model");
6131
+ if (modelOption !== void 0) {
6132
+ if ((Array.isArray(modelOption.options) ? modelOption.options.map((entry) => entry?.value) : []).includes(model)) await this.setConfig(String(modelOption.id), model);
6133
+ }
6134
+ if (effort !== void 0 && effort.length > 0 && effort !== "default") {
6135
+ const effortOption = this.configOptions.find((entry) => entry?.id === "thinkingEffort" || entry?.category === "thought_level");
6136
+ if (effortOption !== void 0) try {
6137
+ await this.setConfig(String(effortOption.id), effort);
6138
+ } catch {}
6139
+ }
6140
+ }
6141
+ /** Exit the session and reap the process. */
6142
+ async close() {
6143
+ if (this.closing) return;
6144
+ this.closing = true;
6145
+ const conn = this.conn;
6146
+ const sessionId = this.sessionId;
6147
+ this.conn = null;
6148
+ this.sessionId = void 0;
6149
+ if (conn !== null && sessionId !== void 0) await withTimeout(conn.closeSession({ sessionId }), 3e3, "mcode acp session/close").catch(() => void 0);
6150
+ this.child?.kill();
6151
+ this.child = null;
6152
+ if (this.tempDir !== void 0) {
6153
+ try {
6154
+ rmSync(this.tempDir, {
6155
+ recursive: true,
6156
+ force: true
6157
+ });
6158
+ } catch {}
6159
+ this.tempDir = void 0;
6160
+ }
6161
+ this.systemFile = void 0;
6162
+ }
6163
+ };
6164
+ /** A one-shot ACP process used by the catalog and title side channels. */
6165
+ async function withAcp(region, timeoutMs, run, options = {}) {
6166
+ const cwd = mkdtempSync(join(tmpdir(), "dsh-minimax-side-"));
6167
+ const acp = new MinimaxAcp({
6168
+ region,
6169
+ cwd,
6170
+ systemPrompt: options.systemPrompt ?? "You are a helper. Do not use tools.",
6171
+ disableTools: options.disableTools ?? true,
6172
+ timeoutMs
6173
+ });
6174
+ try {
6175
+ await acp.start();
6176
+ return await run(acp);
6177
+ } finally {
6178
+ await acp.close();
6179
+ try {
6180
+ rmSync(cwd, {
6181
+ recursive: true,
6182
+ force: true
6183
+ });
6184
+ } catch {}
6185
+ }
6186
+ }
6187
+ /** Read the model list for one region (cached). */
6188
+ var MinimaxCatalog = class {
6189
+ region;
6190
+ ttlMs;
6191
+ timeoutMs;
6192
+ snapshots = /* @__PURE__ */ new Map();
6193
+ inflight = /* @__PURE__ */ new Map();
6194
+ failures = /* @__PURE__ */ new Map();
6195
+ constructor(region, ttlMs = MINIMAX_CACHE_TTL_MS, timeoutMs = MINIMAX_FETCH_TIMEOUT_MS) {
6196
+ this.region = region;
6197
+ this.ttlMs = ttlMs;
6198
+ this.timeoutMs = timeoutMs;
6199
+ }
6200
+ /** Models for one region; a failed refresh keeps the last good list. */
6201
+ async models(requested) {
6202
+ const region = requested ?? readLive(this.region, "cn");
6203
+ if (await minimaxRegionBlocked(region)) {
6204
+ this.invalidate(region);
6205
+ return [];
6206
+ }
6207
+ const ttl = readLive(this.ttlMs, MINIMAX_CACHE_TTL_MS);
6208
+ const cached = this.snapshots.get(region);
6209
+ if (cached !== void 0 && Date.now() - cached.at < ttl) return cached.models;
6210
+ let pending = this.inflight.get(region);
6211
+ if (pending === void 0) {
6212
+ pending = this.fetch(region).finally(() => {
6213
+ this.inflight.delete(region);
6214
+ });
6215
+ this.inflight.set(region, pending);
6216
+ }
6217
+ try {
6218
+ const models = await pending;
6219
+ this.snapshots.set(region, {
6220
+ at: Date.now(),
6221
+ models
6222
+ });
6223
+ this.failures.delete(region);
6224
+ return models;
6225
+ } catch (error) {
6226
+ this.failures.set(region, error instanceof Error ? error.message : String(error));
6227
+ return cached?.models ?? [];
6228
+ }
6229
+ }
6230
+ /** Why the last refresh failed, or undefined when it succeeded. */
6231
+ error(requested) {
6232
+ return this.failures.get(requested ?? readLive(this.region, "cn"));
6233
+ }
6234
+ invalidate(region) {
6235
+ if (region === void 0) {
6236
+ this.snapshots.clear();
6237
+ this.failures.clear();
6238
+ return;
6239
+ }
6240
+ this.snapshots.delete(region);
6241
+ this.failures.delete(region);
6242
+ }
6243
+ async fetch(region) {
6244
+ if (!minimaxSignedIn(region)) throw new Error(`${region === "cn" ? "MiniMax 国内站" : "MiniMax 国际站"}尚未登录,请先在设置页登录。`);
6245
+ if (await minimaxRegionBlocked(region)) throw new MinimaxRegionBlockedError(region);
6246
+ return await withAcp(region, readLive(this.timeoutMs, MINIMAX_FETCH_TIMEOUT_MS), async (acp) => acp.probeModels(), {
6247
+ systemPrompt: "You are a helper used only to list models. Do not call any tool.",
6248
+ disableTools: true
6249
+ });
6250
+ }
6251
+ };
6252
+ /** One shared HTTP MCP server for every warm MiniMax session. */
6253
+ var MinimaxMcpServer = class {
6254
+ server;
6255
+ port = 0;
6256
+ bridges = /* @__PURE__ */ new Map();
6257
+ /** The base URL, or undefined before {@link start}. */
6258
+ get baseUrl() {
6259
+ return this.server === void 0 ? void 0 : `http://127.0.0.1:${this.port}`;
6260
+ }
6261
+ /** Bind to an ephemeral loopback port. */
6262
+ async start() {
6263
+ if (this.server !== void 0) return;
6264
+ const server = createServer((req, res) => {
6265
+ this.handle(req, res);
6266
+ });
6267
+ await new Promise((resolve, reject) => {
6268
+ server.once("error", reject);
6269
+ server.listen(0, "127.0.0.1", () => resolve());
6270
+ });
6271
+ const address = server.address();
6272
+ if (address === null || typeof address === "string") {
6273
+ server.close();
6274
+ throw new Error("无法为 MiniMax 宿主工具分配本地端口。");
6275
+ }
6276
+ this.port = address.port;
6277
+ this.server = server;
6278
+ }
6279
+ /** Add one session's bridge under a random token. */
6280
+ register(bridge) {
6281
+ if (this.server === void 0) throw new Error("MiniMax MCP server 尚未启动。");
6282
+ const token = randomBytes(24).toString("hex");
6283
+ this.bridges.set(token, bridge);
6284
+ return {
6285
+ url: `${this.baseUrl}/mcp/${token}`,
6286
+ token
6287
+ };
6288
+ }
6289
+ unregister(token) {
6290
+ this.bridges.delete(token);
6291
+ }
6292
+ /** Close the server and release every session. */
6293
+ close() {
6294
+ this.bridges.clear();
6295
+ this.server?.close();
6296
+ this.server = void 0;
6297
+ }
6298
+ async handle(req, res) {
6299
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
6300
+ const match = /^\/mcp\/([a-f0-9]+)$/.exec(url.pathname);
6301
+ const bridge = match === null ? void 0 : this.bridges.get(match[1]);
6302
+ if (bridge === void 0) {
6303
+ res.writeHead(404, { "content-type": "application/json" }).end("{\"error\":\"unknown MCP session\"}");
6304
+ return;
6305
+ }
6306
+ if (req.method === "GET") {
6307
+ res.writeHead(405).end();
6308
+ return;
6309
+ }
6310
+ if (req.method === "DELETE") {
6311
+ res.writeHead(200).end();
6312
+ return;
6313
+ }
6314
+ if (req.method !== "POST") {
6315
+ res.writeHead(405).end();
6316
+ return;
6317
+ }
6318
+ if (req.headers.authorization !== `Bearer ${match?.[1] ?? ""}`) {
6319
+ res.writeHead(403).end();
6320
+ return;
6321
+ }
6322
+ let raw = "";
6323
+ for await (const chunk of req) {
6324
+ raw += chunk;
6325
+ if (raw.length > 8388608) {
6326
+ res.writeHead(413).end();
6327
+ return;
6328
+ }
6329
+ }
6330
+ let message;
6331
+ try {
6332
+ message = JSON.parse(raw);
6333
+ } catch {
6334
+ res.writeHead(400).end();
6335
+ return;
6336
+ }
6337
+ const id = message?.id;
6338
+ const reply = (payload) => {
6339
+ const body = JSON.stringify(payload);
6340
+ res.writeHead(200, {
6341
+ "content-type": "application/json",
6342
+ "mcp-session-id": match?.[1] ?? "dsh-host"
6343
+ }).end(body);
6344
+ };
6345
+ if (message?.method === void 0) {
6346
+ res.writeHead(202).end();
6347
+ return;
6348
+ }
6349
+ if (id === void 0) {
6350
+ res.writeHead(202).end();
6351
+ return;
6352
+ }
6353
+ try {
6354
+ switch (message.method) {
6355
+ case "initialize":
6356
+ reply({
6357
+ jsonrpc: "2.0",
6358
+ id,
6359
+ result: {
6360
+ protocolVersion: message.params?.protocolVersion ?? "2025-06-18",
6361
+ capabilities: { tools: {} },
6362
+ serverInfo: {
6363
+ name: MINIMAX_MCP_SERVER,
6364
+ version: "1.0.0"
6365
+ }
6366
+ }
6367
+ });
6368
+ return;
6369
+ case "ping":
6370
+ reply({
6371
+ jsonrpc: "2.0",
6372
+ id,
6373
+ result: {}
6374
+ });
6375
+ return;
6376
+ case "tools/list":
6377
+ reply({
6378
+ jsonrpc: "2.0",
6379
+ id,
6380
+ result: { tools: bridge.tools() }
6381
+ });
6382
+ return;
6383
+ case "tools/call": {
6384
+ const name = typeof message.params?.name === "string" ? message.params.name : "";
6385
+ const args = message.params?.arguments !== null && typeof message.params?.arguments === "object" ? message.params.arguments : {};
6386
+ reply({
6387
+ jsonrpc: "2.0",
6388
+ id,
6389
+ result: await bridge.call(name, args)
6390
+ });
6391
+ return;
6392
+ }
6393
+ default:
6394
+ reply({
6395
+ jsonrpc: "2.0",
6396
+ id,
6397
+ error: {
6398
+ code: -32601,
6399
+ message: `Unknown method ${String(message.method)}`
6400
+ }
6401
+ });
6402
+ return;
6403
+ }
6404
+ } catch (error) {
6405
+ reply({
6406
+ jsonrpc: "2.0",
6407
+ id,
6408
+ result: {
6409
+ content: [{
6410
+ type: "text",
6411
+ text: error instanceof Error ? error.message : String(error)
6412
+ }],
6413
+ isError: true
6414
+ }
6415
+ });
6416
+ }
6417
+ }
6418
+ };
6419
+ /** One session's view of the MCP server. */
6420
+ var MinimaxMcpBridge = class {
6421
+ callHost;
6422
+ schemas = [];
6423
+ constructor(callHost) {
6424
+ this.callHost = callHost;
6425
+ }
6426
+ setTools(tools) {
6427
+ this.schemas = tools;
6428
+ }
6429
+ tools() {
6430
+ return this.schemas.map((schema) => ({
6431
+ name: schema.name,
6432
+ description: schema.description.length > 0 ? schema.description : schema.name,
6433
+ inputSchema: schema.parameters !== null && typeof schema.parameters === "object" ? schema.parameters : {
6434
+ type: "object",
6435
+ properties: {}
6436
+ }
6437
+ }));
6438
+ }
6439
+ async call(name, args) {
6440
+ if (!this.schemas.some((schema) => schema.name === name)) return {
6441
+ content: [{
6442
+ type: "text",
6443
+ text: `未知工具:${name}`
6444
+ }],
6445
+ isError: true
6446
+ };
6447
+ return await this.callHost(name, args);
6448
+ }
6449
+ };
6450
+ /**
6451
+ * Round one token count up to a whole number.
6452
+ *
6453
+ * The harness validates every usage bucket as `number().int().nonnegative()`.
6454
+ * The text estimator prices by script and therefore returns fractions; a
6455
+ * fractional reading is accepted when it streams but makes the durable usage
6456
+ * projection fail, and the conversation then refuses to load at all (the
6457
+ * "failed to project session" error). Counts must leave this module whole.
6458
+ */
6459
+ function wholeTokens(value) {
6460
+ return Math.max(1, Math.ceil(value));
6461
+ }
6462
+ /** Build a turn's usage from its character counts and the reported context. */
6463
+ function minimaxTurnUsage(counts) {
6464
+ const inputTokens = wholeTokens(counts.contextUsed ?? estimateTextTokens(counts.inputChars, 0));
6465
+ const outputTokens = wholeTokens(estimateTextTokens(counts.outputChars + counts.reasoningChars, 0));
6466
+ const reasoningTokens = counts.reasoningChars === 0 ? void 0 : Math.min(outputTokens, wholeTokens(estimateTextTokens(counts.reasoningChars, 0)));
6467
+ return {
6468
+ inputTokens,
6469
+ outputTokens,
6470
+ ...reasoningTokens === void 0 ? {} : { reasoningTokens },
6471
+ cacheReadTokens: 0,
6472
+ cacheWriteTokens: 0,
6473
+ totalTokens: inputTokens + outputTokens
6474
+ };
6475
+ }
6476
+ /** A prompt that asks the model to retry without native tools. */
6477
+ const NATIVE_TOOL_CORRECTION = [
6478
+ "SYSTEM NOTICE (not from the user):",
6479
+ "The built-in tools (bash, read, write, edit, glob, grep, web_fetch, task, and every other native tool)",
6480
+ "are disabled in this deployment. Any call to them is cancelled before execution.",
6481
+ "The only valid tools are the host MCP tools whose names begin with mcp__dsh-host__.",
6482
+ "Re-answer the user's last request using only those host tools. Do not mention this notice."
6483
+ ].join("\n");
6484
+ /** The tool policy appended to the host system prompt. */
6485
+ const HOST_TOOL_POLICY = [
6486
+ "## Host tool protocol",
6487
+ "You are the model backend of DeepSeek Harness.",
6488
+ "The ONLY tools you may call are the host MCP tools exposed by the `dsh-host` MCP server;",
6489
+ "their names begin with `mcp__dsh-host__`. The built-in tools (bash, read, write, edit, glob,",
6490
+ "grep, web_fetch, task, and every other native tool) are disabled in this deployment: calling",
6491
+ "one aborts the turn before execution. Never mention this rule to the user."
6492
+ ].join("\n");
6493
+ /**
6494
+ * One warm MiniMax conversation for a harness session id.
6495
+ *
6496
+ * The ACP agent owns the history. A turn ends either when the prompt finishes
6497
+ * or when a host tool call is handed to the harness; in the latter case the
6498
+ * ACP prompt stays open until the harness returns the result on its next
6499
+ * request, exactly like the CodeBuddy bridge.
6500
+ */
6501
+ var MinimaxSession = class {
6502
+ sessionId;
6503
+ mcpServer;
6504
+ acp = null;
6505
+ events = new EventQueue();
6506
+ bridge;
6507
+ pending = /* @__PURE__ */ new Map();
6508
+ toolResultTimeoutMs;
6509
+ abortGraceMs;
6510
+ callNonce = randomUUID().slice(0, 8);
6511
+ toolCounter = 0;
6512
+ promptInFlight = false;
6513
+ activeTurn = false;
6514
+ disposed = false;
6515
+ region = "cn";
6516
+ model = "";
6517
+ effort;
6518
+ systemPrompt = "";
6519
+ workspace;
6520
+ /** The harness workspace; absent means the session owns a temp directory. */
6521
+ requestedCwd;
6522
+ ownsWorkspace = false;
6523
+ mcpToken;
6524
+ toolSchemas = [];
6525
+ nativeViolation = false;
6526
+ cancelSent = false;
6527
+ correctionCount = 0;
6528
+ observedContextWindow;
6529
+ /** Was the last turn closed with tool-calls, leaving the ACP prompt open? */
6530
+ awaitingToolResults = false;
6531
+ /** Host messages already fed to the ACP session, for continuation planning. */
6532
+ fedMessages;
6533
+ /** Host system prompt last applied; informational for the adapter. */
6534
+ fedSystem;
6535
+ constructor(sessionId, initialModel, mcpServer, runtime = {}) {
6536
+ this.sessionId = sessionId;
6537
+ this.mcpServer = mcpServer;
6538
+ this.model = initialModel;
6539
+ this.toolResultTimeoutMs = readLive(runtime.toolResultTimeoutMs, 12e4);
6540
+ this.abortGraceMs = readLive(runtime.abortGraceMs, 5e3);
6541
+ this.bridge = new MinimaxMcpBridge((name, args) => this.handleToolCall(name, args));
6542
+ }
6543
+ /** Model context window observed from a real turn, when one was reported. */
6544
+ get contextWindow() {
6545
+ return this.observedContextWindow;
6546
+ }
6547
+ /**
6548
+ * Whether the ACP session still owns an unfinished turn.
6549
+ *
6550
+ * A turn closed with `tool-calls` keeps its prompt open while the host runs
6551
+ * the tools, so this stays true between the two host requests. A brand-new
6552
+ * user message in that state cannot be injected; the adapter rebuilds the
6553
+ * session and feeds the whole history instead.
6554
+ */
6555
+ get busy() {
6556
+ return this.promptInFlight || this.activeTurn;
6557
+ }
6558
+ /**
6559
+ * Point the session at a region, model and system prompt.
6560
+ *
6561
+ * @returns true when the warm ACP process was dropped, which means the
6562
+ * conversation state must be rebuilt from the durable history.
6563
+ */
6564
+ configure(region, model, options = {}) {
6565
+ const nextSystem = options.system ?? "";
6566
+ const nextCwd = options.cwd;
6567
+ let reset = false;
6568
+ if (this.acp !== null && (nextSystem !== this.systemPrompt || region !== this.region || nextCwd !== this.requestedCwd)) {
6569
+ this.dropAcp();
6570
+ this.fedMessages = void 0;
6571
+ reset = true;
6572
+ }
6573
+ this.region = region;
6574
+ this.model = model;
6575
+ this.effort = options.effort;
6576
+ this.systemPrompt = nextSystem;
6577
+ this.requestedCwd = nextCwd;
6578
+ return reset;
6579
+ }
6580
+ /** Register the host tools this session's MCP server advertises. */
6581
+ ensureTools(tools) {
6582
+ this.toolSchemas = tools;
6583
+ this.bridge.setTools(tools);
6584
+ }
6585
+ /** Hand the host's tool results to parked handlers. */
6586
+ deliverToolResults(tail) {
6587
+ let freshUserTurn = false;
6588
+ for (const message of tail) {
6589
+ if (message.role === "user") {
6590
+ freshUserTurn = true;
6591
+ continue;
6592
+ }
6593
+ if (message.role !== "tool") continue;
6594
+ const callId = message.toolCallId === void 0 ? "" : String(message.toolCallId);
6595
+ const pending = this.pending.get(callId);
6596
+ if (pending === void 0) continue;
6597
+ clearTimeout(pending.timer);
6598
+ this.pending.delete(callId);
6599
+ pending.resolve({
6600
+ ...renderToolResult(message.content),
6601
+ ...message.isError === true ? { isError: true } : {}
6602
+ });
6603
+ }
6604
+ if (freshUserTurn && this.pending.size > 0) {
6605
+ for (const [callId, pending] of this.pending) {
6606
+ clearTimeout(pending.timer);
6607
+ pending.reject(/* @__PURE__ */ new Error("宿主开始了新的用户轮次,未返回的工具结果已取消。"));
6608
+ this.pending.delete(callId);
6609
+ }
6610
+ if (this.promptInFlight) this.acp?.cancel();
6611
+ this.awaitingToolResults = false;
6612
+ }
6613
+ }
6614
+ /** Run one harness turn. `feed` is new user text, or null for a continuation. */
6615
+ async *stream(options, feed) {
6616
+ if (this.disposed) throw new Error(`MiniMax session ${this.sessionId} was disposed`);
6617
+ if (this.activeTurn) throw new Error(`MiniMax session ${this.sessionId} already has a turn in flight`);
6618
+ this.activeTurn = true;
6619
+ const signal = options.signal;
6620
+ const turn = {
6621
+ blockIndex: 0,
6622
+ inputChars: feed?.length ?? 0,
6623
+ outputChars: 0,
6624
+ reasoningChars: 0
6625
+ };
6626
+ let abortRequested = false;
6627
+ let abortTimer;
6628
+ let onAbortListener;
6629
+ try {
6630
+ await this.ensureStarted();
6631
+ if (!this.promptInFlight) {
6632
+ await this.startPrompt(feed ?? "");
6633
+ this.awaitingToolResults = false;
6634
+ } else if (feed !== null && feed.length > 0 && !this.awaitingToolResults) throw new Error("MiniMax 会话正忙:上一轮尚未结束。");
6635
+ const onAbort = () => {
6636
+ abortRequested = true;
6637
+ this.acp?.cancel();
6638
+ abortTimer = setTimeout(() => {
6639
+ this.dropAcp();
6640
+ }, this.abortGraceMs);
6641
+ };
6642
+ onAbortListener = onAbort;
6643
+ signal?.addEventListener("abort", onAbort, { once: true });
6644
+ while (true) {
6645
+ if (signal?.aborted === true) {
6646
+ if (!abortRequested) onAbort();
6647
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话被宿主中止。"));
6648
+ this.promptInFlight = false;
6649
+ this.awaitingToolResults = false;
6650
+ yield* this.finish(turn, {
6651
+ kind: "aborted",
6652
+ failure: {
6653
+ message: "MiniMax turn aborted by host",
6654
+ code: "ABORTED"
6655
+ }
6656
+ });
6657
+ return;
6658
+ }
6659
+ const event = await raceAbort(this.events.next(), signal);
6660
+ if (event === void 0) {
6661
+ if (abortRequested) continue;
6662
+ yield* this.finish(turn, {
6663
+ kind: "error",
6664
+ failure: {
6665
+ message: "MiniMax ACP stream closed",
6666
+ code: "STREAM_CLOSED"
6667
+ }
6668
+ });
6669
+ return;
6670
+ }
6671
+ switch (event.kind) {
6672
+ case "text":
6673
+ turn.outputChars += event.text.length;
6674
+ if (turn.textBlock === void 0) {
6675
+ turn.textBlock = {
6676
+ index: turn.blockIndex++,
6677
+ text: ""
6678
+ };
6679
+ yield {
6680
+ type: "block-start",
6681
+ index: turn.textBlock.index,
6682
+ blockType: "text"
6683
+ };
6684
+ }
6685
+ turn.textBlock.text += event.text;
6686
+ yield {
6687
+ type: "text-delta",
6688
+ index: turn.textBlock.index,
6689
+ text: event.text
6690
+ };
6691
+ continue;
6692
+ case "reasoning":
6693
+ turn.reasoningChars += event.text.length;
6694
+ if (turn.reasoningBlock === void 0) {
6695
+ turn.reasoningBlock = {
6696
+ index: turn.blockIndex++,
6697
+ text: ""
6698
+ };
6699
+ yield {
6700
+ type: "block-start",
6701
+ index: turn.reasoningBlock.index,
6702
+ blockType: "reasoning"
6703
+ };
6704
+ }
6705
+ turn.reasoningBlock.text += event.text;
6706
+ yield {
6707
+ type: "reasoning-delta",
6708
+ index: turn.reasoningBlock.index,
6709
+ text: event.text
6710
+ };
6711
+ continue;
6712
+ case "usage":
6713
+ if (event.size > 0) this.observedContextWindow = event.size;
6714
+ if (event.used > 0) turn.contextUsed = event.used;
6715
+ continue;
6716
+ case "host-tool": {
6717
+ if (turn.textBlock !== void 0) {
6718
+ yield {
6719
+ type: "block-end",
6720
+ index: turn.textBlock.index,
6721
+ block: {
6722
+ type: "text",
6723
+ text: turn.textBlock.text
6724
+ }
6725
+ };
6726
+ turn.textBlock = void 0;
6727
+ }
6728
+ if (turn.reasoningBlock !== void 0) {
6729
+ yield {
6730
+ type: "block-end",
6731
+ index: turn.reasoningBlock.index,
6732
+ block: {
6733
+ type: "reasoning",
6734
+ text: turn.reasoningBlock.text
6735
+ }
6736
+ };
6737
+ turn.reasoningBlock = void 0;
6738
+ }
6739
+ const index = turn.blockIndex++;
6740
+ yield {
6741
+ type: "block-start",
6742
+ index,
6743
+ blockType: "tool-call"
6744
+ };
6745
+ const args = JSON.stringify(event.args);
6746
+ yield {
6747
+ type: "tool-call-delta",
6748
+ index,
6749
+ id: ToolCallId(event.callId),
6750
+ name: event.name,
6751
+ argumentsDelta: args
6752
+ };
6753
+ yield {
6754
+ type: "block-end",
6755
+ index,
6756
+ block: {
6757
+ type: "tool-call",
6758
+ id: ToolCallId(event.callId),
6759
+ name: event.name,
6760
+ arguments: args
6761
+ }
6762
+ };
6763
+ this.awaitingToolResults = true;
6764
+ yield* this.finish(turn, { kind: "tool-calls" });
6765
+ return;
6766
+ }
6767
+ case "native-tool":
6768
+ if (!this.cancelSent) {
6769
+ this.cancelSent = true;
6770
+ this.nativeViolation = true;
6771
+ await this.acp?.cancel();
6772
+ }
6773
+ continue;
6774
+ case "prompt-done":
6775
+ this.promptInFlight = false;
6776
+ this.cancelSent = false;
6777
+ if (abortRequested) {
6778
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话被宿主中止。"));
6779
+ yield* this.finish(turn, {
6780
+ kind: "aborted",
6781
+ failure: {
6782
+ message: "MiniMax turn aborted by host",
6783
+ code: "ABORTED"
6784
+ }
6785
+ });
6786
+ return;
6787
+ }
6788
+ if (this.nativeViolation) {
6789
+ this.nativeViolation = false;
6790
+ this.correctionCount += 1;
6791
+ if (this.correctionCount <= MAX_NATIVE_TOOL_RETRIES) {
6792
+ await new Promise((resolve) => setTimeout(resolve, 350));
6793
+ try {
6794
+ await this.startPrompt(NATIVE_TOOL_CORRECTION);
6795
+ this.awaitingToolResults = false;
6796
+ continue;
6797
+ } catch (error) {
6798
+ yield* this.finish(turn, {
6799
+ kind: "error",
6800
+ failure: {
6801
+ message: `MiniMax 内置工具不可用,重试失败:${error instanceof Error ? error.message : String(error)}`,
6802
+ code: "BACKEND_TURN_ERROR"
6803
+ }
6804
+ });
6805
+ return;
6806
+ }
6807
+ }
6808
+ yield* this.finish(turn, {
6809
+ kind: "error",
6810
+ failure: {
6811
+ message: "MiniMax 连续尝试调用内置工具。本插件只允许宿主 MCP 工具,已取消本轮。",
6812
+ code: "BACKEND_TURN_ERROR"
6813
+ }
6814
+ });
6815
+ return;
6816
+ }
6817
+ if (event.stopReason === "end_turn" || event.stopReason === "max_tokens") {
6818
+ yield* this.finish(turn, event.stopReason === "max_tokens" ? { kind: "max-tokens" } : { kind: "stop" });
6819
+ return;
6820
+ }
6821
+ if (event.stopReason === "cancelled") {
6822
+ yield* this.finish(turn, {
6823
+ kind: "aborted",
6824
+ failure: {
6825
+ message: "MiniMax turn cancelled",
6826
+ code: "ABORTED"
6827
+ }
6828
+ });
6829
+ return;
6830
+ }
6831
+ yield* this.finish(turn, { kind: "stop" });
6832
+ return;
6833
+ case "prompt-error":
6834
+ this.promptInFlight = false;
6835
+ this.cancelSent = false;
6836
+ yield* this.finish(turn, {
6837
+ kind: "error",
6838
+ failure: {
6839
+ message: event.error.message,
6840
+ code: "BACKEND_TURN_ERROR"
6841
+ }
6842
+ });
6843
+ return;
6844
+ case "closed":
6845
+ this.promptInFlight = false;
6846
+ yield* this.finish(turn, {
6847
+ kind: "error",
6848
+ failure: {
6849
+ message: event.error.message,
6850
+ code: "BACKEND_TURN_ERROR"
6851
+ }
6852
+ });
6853
+ return;
6854
+ }
6855
+ }
6856
+ } finally {
6857
+ if (onAbortListener !== void 0) signal?.removeEventListener("abort", onAbortListener);
6858
+ if (abortTimer !== void 0) clearTimeout(abortTimer);
6859
+ this.activeTurn = false;
6860
+ }
6861
+ }
6862
+ /** Tear the ACP process down; parked handlers settle with a cancellation. */
6863
+ close() {
6864
+ if (this.disposed) return;
6865
+ this.disposed = true;
6866
+ rejectPending(this.pending, /* @__PURE__ */ new Error("MiniMax 会话已关闭。"));
6867
+ this.events.close();
6868
+ const workspace = this.workspace;
6869
+ const owned = this.ownsWorkspace;
6870
+ this.workspace = void 0;
6871
+ this.ownsWorkspace = false;
6872
+ this.dropAcp().finally(() => {
6873
+ if (workspace === void 0 || !owned) return;
6874
+ try {
6875
+ rmSync(workspace, {
6876
+ recursive: true,
6877
+ force: true
6878
+ });
6879
+ } catch {}
6880
+ });
6881
+ }
6882
+ async ensureStarted() {
6883
+ if (this.acp !== null) return;
6884
+ await this.mcpServer.start();
6885
+ if (this.workspace === void 0) {
6886
+ if (this.requestedCwd !== void 0) {
6887
+ this.workspace = this.requestedCwd;
6888
+ this.ownsWorkspace = false;
6889
+ } else {
6890
+ this.workspace = mkdtempSync(join(tmpdir(), "dsh-minimax-session-"));
6891
+ this.ownsWorkspace = true;
6892
+ }
6893
+ }
6894
+ this.bridge.setTools(this.toolSchemas);
6895
+ const registered = this.mcpServer.register(this.bridge);
6896
+ this.mcpToken = registered.token;
6897
+ const system = `${this.systemPrompt.trim()}\n\n${HOST_TOOL_POLICY}\n`;
6898
+ const acp = new MinimaxAcp({
6899
+ region: this.region,
6900
+ cwd: this.workspace,
6901
+ systemPrompt: system,
6902
+ mcpUrl: registered.url,
6903
+ mcpToken: registered.token,
6904
+ onUpdate: (update) => {
6905
+ this.events.push(update);
6906
+ },
6907
+ onExit: (error) => {
6908
+ this.events.push({
6909
+ kind: "closed",
6910
+ error
6911
+ });
6912
+ }
6913
+ });
6914
+ try {
6915
+ await acp.start();
6916
+ await acp.selectModel(this.model, this.effort);
6917
+ this.acp = acp;
6918
+ } catch (error) {
6919
+ await acp.close();
6920
+ this.mcpServer.unregister(registered.token);
6921
+ this.mcpToken = void 0;
6922
+ throw error;
6923
+ }
6924
+ }
6925
+ async startPrompt(text) {
6926
+ const acp = this.acp;
6927
+ if (acp === null) throw new Error("MiniMax ACP 尚未启动。");
6928
+ this.promptInFlight = true;
6929
+ this.cancelSent = false;
6930
+ this.launchPrompt(acp, text, 0);
6931
+ }
6932
+ /**
6933
+ * Start one ACP prompt and publish its outcome.
6934
+ *
6935
+ * Cancelling a turn makes the next `session/prompt` fail with "Session
6936
+ * already has an active Turn" for a short while even though the cancelled
6937
+ * prompt has already resolved. That race is routine here: the native-tool
6938
+ * correction is sent immediately after such a cancel, so it is retried with
6939
+ * a short backoff instead of being reported as a failed turn.
6940
+ */
6941
+ async launchPrompt(acp, text, attempt) {
6942
+ try {
6943
+ const response = await acp.prompt(text);
6944
+ this.events.push({
6945
+ kind: "prompt-done",
6946
+ stopReason: response.stopReason
6947
+ });
6948
+ } catch (error) {
6949
+ const message = error instanceof Error ? error.message : String(error);
6950
+ if (/401 token is required/i.test(message)) {
6951
+ minimaxRegionBlocked(this.region, { fresh: true });
6952
+ const hint = minimaxRegionBlockedCached(this.region) ? minimaxRegionBlockMessage(this.region) : this.region === "global" ? "MiniMax 国际站拒绝了本机连接(401 token is required)。通常是本机网络 IP 不在国际站服务区域;请检查网络后重试,或切换到国内站。" : "MiniMax 国内站拒绝了本机连接(401 token is required)。请检查网络或重新登录后重试。";
6953
+ this.events.push({
6954
+ kind: "prompt-error",
6955
+ error: new Error(hint)
6956
+ });
6957
+ return;
6958
+ }
6959
+ if (/active Turn|already has an active/i.test(message) && attempt < 4 && !this.disposed && this.acp === acp) {
6960
+ await new Promise((resolve) => setTimeout(resolve, 200 * 2 ** attempt));
6961
+ if (!this.disposed && this.acp === acp) {
6962
+ await this.launchPrompt(acp, text, attempt + 1);
6963
+ return;
6964
+ }
6965
+ }
6966
+ this.events.push({
6967
+ kind: "prompt-error",
6968
+ error: error instanceof Error ? error : new Error(message)
6969
+ });
6970
+ }
6971
+ }
6972
+ async dropAcp() {
6973
+ const acp = this.acp;
6974
+ this.acp = null;
6975
+ this.promptInFlight = false;
6976
+ this.awaitingToolResults = false;
6977
+ if (acp !== null) await acp.close();
6978
+ if (this.mcpToken !== void 0) {
6979
+ this.mcpServer.unregister(this.mcpToken);
6980
+ this.mcpToken = void 0;
6981
+ }
6982
+ }
6983
+ async handleToolCall(name, args) {
6984
+ if (this.disposed) return {
6985
+ content: [{
6986
+ type: "text",
6987
+ text: "MiniMax 会话已关闭。"
6988
+ }],
6989
+ isError: true
6990
+ };
6991
+ const callId = `mm-${this.callNonce}-${++this.toolCounter}`;
6992
+ const result = new Promise((resolve, reject) => {
6993
+ const timer = setTimeout(() => {
6994
+ this.pending.delete(callId);
6995
+ reject(/* @__PURE__ */ new Error(`宿主工具 ${name} 在 ${Math.round(this.toolResultTimeoutMs / 1e3)} 秒内没有返回结果。`));
6996
+ }, this.toolResultTimeoutMs);
6997
+ this.pending.set(callId, {
6998
+ resolve,
6999
+ reject,
7000
+ timer
7001
+ });
7002
+ });
7003
+ this.events.push({
7004
+ kind: "host-tool",
7005
+ callId,
7006
+ name,
7007
+ args
7008
+ });
7009
+ try {
7010
+ return await result;
7011
+ } catch (error) {
7012
+ return {
7013
+ content: [{
7014
+ type: "text",
7015
+ text: error instanceof Error ? error.message : String(error)
7016
+ }],
7017
+ isError: true
7018
+ };
7019
+ }
7020
+ }
7021
+ async *finish(turn, reason) {
7022
+ if (turn.textBlock !== void 0) yield {
7023
+ type: "block-end",
7024
+ index: turn.textBlock.index,
7025
+ block: {
7026
+ type: "text",
7027
+ text: turn.textBlock.text
7028
+ }
7029
+ };
7030
+ if (turn.reasoningBlock !== void 0) yield {
7031
+ type: "block-end",
7032
+ index: turn.reasoningBlock.index,
7033
+ block: {
7034
+ type: "reasoning",
7035
+ text: turn.reasoningBlock.text
7036
+ }
7037
+ };
7038
+ yield {
7039
+ type: "usage",
7040
+ usage: minimaxTurnUsage({
7041
+ ...turn.contextUsed === void 0 ? {} : { contextUsed: turn.contextUsed },
7042
+ inputChars: turn.inputChars,
7043
+ outputChars: turn.outputChars,
7044
+ reasoningChars: turn.reasoningChars
7045
+ })
7046
+ };
7047
+ yield {
7048
+ type: "finish",
7049
+ reason
7050
+ };
7051
+ if (reason.kind !== "tool-calls" && !this.disposed) this.correctionCount = 0;
7052
+ }
7053
+ };
7054
+ /** Reject every parked handler with the same reason. */
7055
+ function rejectPending(pending, error) {
7056
+ for (const [callId, entry] of pending) {
7057
+ clearTimeout(entry.timer);
7058
+ entry.reject(error);
7059
+ pending.delete(callId);
7060
+ }
7061
+ }
7062
+ /** Wait for a promise, or give up after `ms`. */
7063
+ function withTimeout(promise, ms, label) {
7064
+ return new Promise((resolve, reject) => {
7065
+ const timer = setTimeout(() => {
7066
+ reject(/* @__PURE__ */ new Error(`${label} timed out after ${ms}ms`));
7067
+ }, ms);
7068
+ promise.then((value) => {
7069
+ clearTimeout(timer);
7070
+ resolve(value);
7071
+ }, (error) => {
7072
+ clearTimeout(timer);
7073
+ reject(error);
7074
+ });
7075
+ });
7076
+ }
7077
+ /** Await a queue read, giving up when the harness aborts the turn. */
7078
+ function raceAbort(promise, signal) {
7079
+ if (signal === void 0) return promise;
7080
+ if (signal.aborted) return Promise.resolve(void 0);
7081
+ return new Promise((resolve, reject) => {
7082
+ const onAbort = () => {
7083
+ signal.removeEventListener("abort", onAbort);
7084
+ resolve(void 0);
7085
+ };
7086
+ signal.addEventListener("abort", onAbort, { once: true });
7087
+ promise.then((value) => {
7088
+ signal.removeEventListener("abort", onAbort);
7089
+ resolve(value);
7090
+ }, (error) => {
7091
+ signal.removeEventListener("abort", onAbort);
7092
+ reject(error);
7093
+ });
7094
+ });
7095
+ }
7096
+ /** Warm session pool, keyed by harness session id. */
7097
+ var MinimaxSessionManager = class {
7098
+ maxSessions;
7099
+ mcpServer;
7100
+ runtime;
7101
+ sessions = /* @__PURE__ */ new Map();
7102
+ constructor(maxSessions, mcpServer, runtime = {}) {
7103
+ this.maxSessions = maxSessions;
7104
+ this.mcpServer = mcpServer;
7105
+ this.runtime = runtime;
7106
+ }
7107
+ forSession(sessionId, region, model) {
7108
+ const existing = this.sessions.get(sessionId);
7109
+ if (existing !== void 0) {
7110
+ if (existing.region !== region) {
7111
+ existing.session.close();
7112
+ this.sessions.delete(sessionId);
7113
+ } else {
7114
+ this.sessions.delete(sessionId);
7115
+ this.sessions.set(sessionId, existing);
7116
+ return existing.session;
7117
+ }
7118
+ }
7119
+ const session = new MinimaxSession(sessionId, model, this.mcpServer, this.runtime);
7120
+ this.sessions.set(sessionId, {
7121
+ session,
7122
+ region
7123
+ });
7124
+ const cap = readLive(this.maxSessions, 8);
7125
+ while (this.sessions.size > cap) {
7126
+ const oldest = this.sessions.keys().next();
7127
+ if (oldest.done === true) break;
7128
+ const victim = this.sessions.get(oldest.value);
7129
+ this.sessions.delete(oldest.value);
7130
+ victim?.session.close();
7131
+ }
7132
+ return session;
7133
+ }
7134
+ dispose(sessionId) {
7135
+ const entry = this.sessions.get(sessionId);
7136
+ if (entry === void 0) return;
7137
+ this.sessions.delete(sessionId);
7138
+ entry.session.close();
7139
+ }
7140
+ closeAll() {
7141
+ for (const entry of this.sessions.values()) entry.session.close();
7142
+ this.sessions.clear();
7143
+ }
7144
+ };
7145
+ /** A one-shot turn, used for titles and compaction summaries. */
7146
+ async function minimaxColdStream(region, prompt, model, options) {
7147
+ const chunks = [];
7148
+ let text = "";
7149
+ const cwd = mkdtempSync(join(tmpdir(), "dsh-minimax-cold-"));
7150
+ const acp = new MinimaxAcp({
7151
+ region,
7152
+ cwd,
7153
+ systemPrompt: "You are a concise helper used only for titles and summaries. Do not call any tool.",
7154
+ disableTools: true,
7155
+ onUpdate: (update) => {
7156
+ if (update.kind === "text") text += update.text;
7157
+ }
7158
+ });
7159
+ const signal = options.signal;
7160
+ const onAbort = () => {
7161
+ acp.cancel();
7162
+ };
7163
+ signal?.addEventListener("abort", onAbort, { once: true });
7164
+ try {
7165
+ await acp.start();
7166
+ if (model !== void 0) await acp.selectModel(model);
7167
+ const response = await acp.prompt(prompt);
7168
+ if (signal?.aborted === true || response.stopReason === "cancelled") {
7169
+ chunks.push({
7170
+ type: "finish",
7171
+ reason: {
7172
+ kind: "aborted",
7173
+ failure: {
7174
+ message: "aborted by host",
7175
+ code: "ABORTED"
7176
+ }
7177
+ }
7178
+ });
7179
+ return chunks;
7180
+ }
7181
+ if (text.trim().length === 0) {
7182
+ chunks.push({
7183
+ type: "finish",
7184
+ reason: {
7185
+ kind: "error",
7186
+ failure: {
7187
+ message: "MiniMax side-channel returned no content",
7188
+ code: EMPTY_RESPONSE_CODE
7189
+ }
7190
+ }
7191
+ });
7192
+ return chunks;
7193
+ }
7194
+ chunks.push({
7195
+ type: "block-start",
7196
+ index: 0,
7197
+ blockType: "text"
7198
+ });
7199
+ for (let index = 0; index < text.length; index += 192) chunks.push({
7200
+ type: "text-delta",
7201
+ index: 0,
7202
+ text: text.slice(index, index + 192)
7203
+ });
7204
+ chunks.push({
7205
+ type: "block-end",
7206
+ index: 0,
7207
+ block: {
7208
+ type: "text",
7209
+ text
7210
+ }
7211
+ });
7212
+ chunks.push({
7213
+ type: "usage",
7214
+ usage: minimaxTurnUsage({
7215
+ inputChars: prompt.length,
7216
+ outputChars: text.length,
7217
+ reasoningChars: 0
7218
+ })
7219
+ });
7220
+ chunks.push({
7221
+ type: "finish",
7222
+ reason: { kind: "stop" }
7223
+ });
7224
+ return chunks;
7225
+ } finally {
7226
+ signal?.removeEventListener("abort", onAbort);
7227
+ await acp.close();
7228
+ try {
7229
+ rmSync(cwd, {
7230
+ recursive: true,
7231
+ force: true
7232
+ });
7233
+ } catch {}
7234
+ }
7235
+ }
7236
+ //#endregion
7237
+ //#region src/minimax-adapter.ts
7238
+ /**
7239
+ * `MinimaxAdapter`: route the harness LLM seam onto a MiniMax Code account.
7240
+ *
7241
+ * The ACP agent owns the conversation; this adapter decides what new text to
7242
+ * send, which model/effort to select, and how the ACP tool calls map onto the
7243
+ * harness's tool seam. One provider serves both login regions; the region is a
7244
+ * live config choice and every ACP process is pinned to it.
7245
+ *
7246
+ * @module dsh-agent-sdk-bridge/minimax-adapter
7247
+ */
7248
+ /** The MiniMax Code provider route. */
7249
+ const MINIMAX_PROVIDER = "minimax-acp";
7250
+ const NO_MODELS = [];
7251
+ const NO_ALIASES = {};
7252
+ /** Map a harness-side id onto an ACP model value. */
7253
+ function resolveMinimaxModelId(model, aliases = {}) {
7254
+ const configured = aliases[model] ?? aliases[model.toLowerCase()];
7255
+ if (configured !== void 0 && configured.length > 0) return configured;
7256
+ return model.startsWith("minimax-") ? model.slice(8) : model;
7257
+ }
7258
+ function modelInfo(provider, model) {
7259
+ return {
7260
+ provider,
7261
+ id: model.id,
7262
+ name: model.name,
7263
+ ...model.description === void 0 ? {} : { description: model.description },
7264
+ inputModalities: model.vision ? ["text", "image"] : ["text"]
7265
+ };
7266
+ }
7267
+ /** The MiniMax Code-backed adapter. */
7268
+ var MinimaxAdapter = class extends LlmAdapter {
7269
+ options;
7270
+ sessions;
7271
+ catalog;
7272
+ auth = new MinimaxAuth();
7273
+ mcpServer = new MinimaxMcpServer();
7274
+ disabledCache = /* @__PURE__ */ new Map();
7275
+ constructor(options = {}) {
7276
+ super();
7277
+ this.options = options;
7278
+ this.sessions = new MinimaxSessionManager(options.maxSessions ?? 8, this.mcpServer, {
7279
+ toolResultTimeoutMs: options.toolResultTimeoutMs,
7280
+ abortGraceMs: options.abortGraceMs
7281
+ });
7282
+ this.catalog = new MinimaxCatalog(options.region ?? (() => "cn"), options.modelCacheTtlMs ?? 3e5, options.catalogFetchTimeoutMs ?? 3e4);
7283
+ }
7284
+ get region() {
7285
+ return readLive(this.options.region ?? (() => "cn"), "cn");
7286
+ }
7287
+ disabledFor(region) {
7288
+ const source = this.options.disabledModels?.(region) ?? NO_MODELS;
7289
+ const key = source.join("\0");
7290
+ const cached = this.disabledCache.get(region);
7291
+ if (cached?.key === key) return cached.set;
7292
+ const set = new Set(source);
7293
+ this.disabledCache.set(region, {
7294
+ key,
7295
+ set
7296
+ });
7297
+ return set;
7298
+ }
7299
+ get aliases() {
7300
+ return readLive(this.options.modelAliases, NO_ALIASES);
7301
+ }
7302
+ get displayName() {
7303
+ return readLive(this.options.displayName, "MiniMax Code");
7304
+ }
7305
+ providerInfo(provider) {
7306
+ return {
7307
+ id: provider,
7308
+ name: this.displayName
7309
+ };
7310
+ }
7311
+ /** The live catalog, unfiltered (the page must show switched-off models). */
7312
+ async describeCatalog(region = this.region) {
7313
+ if (!this.isSignedIn(region)) return [];
7314
+ if (await minimaxRegionBlocked(region)) return [];
7315
+ return this.catalog.models(region);
7316
+ }
7317
+ /** Whether the region's endpoints are refusing this machine's network. */
7318
+ regionBlocked(region = this.region) {
7319
+ return minimaxRegionBlockedCached(region);
7320
+ }
7321
+ /** Whether the selected (or given) region has a stored login. */
7322
+ isSignedIn(region = this.region) {
7323
+ return this.auth.status(region).signedIn || minimaxSignedIn(region);
7324
+ }
7325
+ /** Why the last catalog read failed, for the page's guidance. */
7326
+ catalogError(region = this.region) {
7327
+ if (resolveMinimaxCli() === void 0) return "未安装 MiniMax Code CLI(mcode)。请先安装后再登录。";
7328
+ if (minimaxRegionBlockedCached(region)) return minimaxRegionBlockMessage(region);
7329
+ if (!this.isSignedIn(region)) return "请先登录 MiniMax Code,登录后才会读取并显示模型目录。";
7330
+ return this.catalog.error(region);
7331
+ }
7332
+ /**
7333
+ * Drop the cached catalog and the region verdict behind it.
7334
+ *
7335
+ * The page calls this with `fresh=1` on a region switch, which is exactly
7336
+ * when the network may have changed; keeping a 30-second "blocked" verdict
7337
+ * would hide the catalog the switch was meant to reveal.
7338
+ */
7339
+ invalidateCatalog(region) {
7340
+ this.catalog.invalidate(region);
7341
+ invalidateMinimaxRegionAccess(region);
7342
+ }
7343
+ /** Login status, installer state and (when signed in) the account's quota. */
7344
+ async usageInfo(fresh = false, region) {
7345
+ const target = region ?? this.region;
7346
+ const installed = resolveMinimaxCli() !== void 0;
7347
+ const status = this.auth.status(target);
7348
+ if (!(status.signedIn || minimaxSignedIn(target))) return {
7349
+ at: Date.now(),
7350
+ region: target,
7351
+ signedIn: false,
7352
+ installed,
7353
+ ...installed ? {} : { error: "未安装 MiniMax Code CLI(mcode)。" },
7354
+ ...status.error === void 0 ? {} : { error: status.error }
7355
+ };
7356
+ const snapshot = await minimaxUsage(target, { fresh });
7357
+ return {
7358
+ ...snapshot,
7359
+ signedIn: true,
7360
+ installed,
7361
+ ...snapshot.error !== void 0 || status.error === void 0 ? {} : { error: status.error }
7362
+ };
7363
+ }
7364
+ /** Drop cached quota readings and the region verdict (login, logout, CLI). */
7365
+ invalidateUsage(region) {
7366
+ invalidateMinimaxUsage(region);
7367
+ invalidateMinimaxRegionAccess(region);
7368
+ }
7369
+ /** Login progress for one region; the page polls this. */
7370
+ authStatus(region) {
7371
+ return this.auth.status(region);
7372
+ }
7373
+ startLogin(region) {
7374
+ return this.auth.start(region, (ok) => {
7375
+ if (!ok) return;
7376
+ this.sessions.closeAll();
7377
+ this.invalidateCatalog(region);
7378
+ this.invalidateUsage(region);
7379
+ invalidateMinimaxRegionAccess(region);
7380
+ });
7381
+ }
7382
+ async logout(region) {
7383
+ const result = await this.auth.logout(region);
7384
+ this.sessions.closeAll();
7385
+ this.invalidateCatalog(region);
7386
+ this.invalidateUsage(region);
7387
+ invalidateMinimaxRegionAccess(region);
7388
+ return result;
7389
+ }
7390
+ isModelDisabled(id, region = this.region) {
7391
+ return this.disabledFor(region).has(id);
7392
+ }
7393
+ contextWindowFor(id, region = this.region) {
7394
+ return this.options.modelContextWindows?.(region)[id];
7395
+ }
7396
+ async listModels(provider) {
7397
+ const region = this.region;
7398
+ if (!this.isSignedIn(region)) return [];
7399
+ if (await minimaxRegionBlocked(region)) return [];
7400
+ const models = await this.catalog.models(region);
7401
+ const disabled = this.disabledFor(region);
7402
+ return models.filter((model) => !disabled.has(model.id)).map((model) => modelInfo(provider, model));
7403
+ }
7404
+ async resolveModel(provider, model) {
7405
+ const region = this.region;
7406
+ const target = resolveMinimaxModelId(model, this.aliases);
7407
+ const live = (await this.catalog.models(region)).find((entry) => entry.id === target);
7408
+ if (live !== void 0) {
7409
+ const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, live.reasoning);
7410
+ return {
7411
+ provider,
7412
+ id: model,
7413
+ name: live.name,
7414
+ ...live.description === void 0 ? {} : { description: live.description },
7415
+ inputModalities: live.vision ? ["text", "image"] : ["text"],
7416
+ context: { contextWindow: this.contextWindowFor(target, region) ?? live.defaultContextWindow },
7417
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
7418
+ ...reasoning === void 0 ? {} : { reasoning }
7419
+ };
7420
+ }
7421
+ const reasoning = reasoningInfo(void 0, readLiveOptional(this.options.defaultReasoningEffort), true);
7422
+ return {
7423
+ provider,
7424
+ id: model,
7425
+ name: model,
7426
+ inputModalities: ["text"],
7427
+ context: { contextWindow: this.contextWindowFor(target, region) ?? 512e3 },
7428
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
7429
+ ...reasoning === void 0 ? {} : { reasoning }
7430
+ };
7431
+ }
7432
+ async prepareCall(provider, model, signal) {
7433
+ return {
7434
+ model: await this.resolveModel(provider, model),
7435
+ stream: (options) => this.dispatch(options)
7436
+ };
7437
+ }
7438
+ async *stream(options) {
7439
+ yield* this.dispatch(options);
7440
+ }
7441
+ async *dispatch(options) {
7442
+ const region = this.region;
7443
+ if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "MiniMax 国内站" : "MiniMax 国际站"}尚未登录,请先在设置 → MiniMax Code 中登录。`);
7444
+ if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
7445
+ const model = resolveMinimaxModelId(options.model, this.aliases);
7446
+ if (options.sessionId === void 0 || options.purpose !== void 0) {
7447
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages)) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
7448
+ for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
7449
+ return;
7450
+ }
7451
+ const sessionId = String(options.sessionId);
7452
+ const effort = options.reasoningEffort ?? readLiveOptional(this.options.defaultReasoningEffort);
7453
+ let session = this.sessions.forSession(sessionId, region, model);
7454
+ if (session.fedMessages === void 0) {
7455
+ yield* this.firstTurn(session, options, region, model, effort);
7456
+ return;
7457
+ }
7458
+ const tail = options.messages.slice(session.fedMessages.length);
7459
+ session.deliverToolResults(tail);
7460
+ const plan = planContinuation(session.fedMessages, options.messages);
7461
+ if (plan.rebuild) {
7462
+ this.sessions.dispose(sessionId);
7463
+ session = this.sessions.forSession(sessionId, region, model);
7464
+ yield* this.firstTurn(session, options, region, model, effort);
7465
+ return;
7466
+ }
7467
+ if (plan.feed !== null && session.busy) {
7468
+ this.sessions.dispose(sessionId);
7469
+ session = this.sessions.forSession(sessionId, region, model);
7470
+ yield* this.firstTurn(session, options, region, model, effort);
7471
+ return;
7472
+ }
7473
+ if (session.configure(region, model, {
7474
+ effort,
7475
+ system: options.system,
7476
+ cwd: this.cwdOf(options)
7477
+ }) || plan.feed === null && !session.busy) {
7478
+ this.sessions.dispose(sessionId);
7479
+ session = this.sessions.forSession(sessionId, region, model);
7480
+ yield* this.firstTurn(session, options, region, model, effort);
7481
+ return;
7482
+ }
7483
+ session.ensureTools(options.tools ?? []);
7484
+ session.fedMessages = options.messages;
7485
+ session.fedSystem = options.system;
7486
+ const feed = plan.feed === null ? null : feedToText(plan.feed);
7487
+ yield* session.stream(options, feed);
7488
+ }
7489
+ async *firstTurn(session, options, region, model, effort) {
7490
+ session.configure(region, model, {
7491
+ effort,
7492
+ system: options.system,
7493
+ cwd: this.cwdOf(options)
7494
+ });
7495
+ session.ensureTools(options.tools ?? []);
7496
+ session.fedMessages = options.messages;
7497
+ session.fedSystem = options.system;
7498
+ const feed = feedToText(renderInitialFeed(void 0, options.messages));
7499
+ yield* session.stream(options, feed);
7500
+ }
7501
+ cwdOf(options) {
7502
+ return options.cwd;
7503
+ }
7504
+ close() {
7505
+ this.sessions.closeAll();
7506
+ this.mcpServer.close();
7507
+ this.auth.stop();
7508
+ }
7509
+ };
7510
+ //#endregion
7511
+ //#region src/setup.ts
7512
+ /**
7513
+ * Runs the bundled Windows helper that installs and signs into a Qoder CLI
7514
+ * (one helper per edition: `qoderclicn` for CN, `qodercli` for international).
7515
+ *
7516
+ * The settings page cannot do this by itself: a browser has no way to start a
7517
+ * local process, and the plugin's own process is the one that already talks to
7518
+ * the CLI. So the page asks this module, and this module spawns
7519
+ * {@link SCRIPT_NAME} — the same script a user can double-click — with one of
7520
+ * two fixed flags, and buffers its output so the page can show progress while
7521
+ * the browser sign-in is still open.
7522
+ *
7523
+ * Nothing user-supplied reaches the command line: the mode is an allow-list of
7524
+ * two keys mapped to two literal flags, and the script path comes from this
7525
+ * package's own layout. The helper is idempotent, so a second press re-checks
7526
+ * rather than reinstalling.
7527
+ *
7528
+ * @module dsh-agent-sdk-bridge/setup
7529
+ */
7530
+ /** File name of the CN helper, shipped under this package's `scripts/` directory. */
7531
+ const SCRIPT_NAME = "setup-qoderclicn.bat";
7532
+ /** The helper script for one edition. */
7533
+ function scriptNameOf(brand) {
7534
+ return brandProfile(brand).setupScript ?? "setup-qoderclicn.bat";
7535
+ }
7536
+ /** The one command-line flag each mode maps to. Never a user-supplied string. */
7537
+ const FLAGS = {
7538
+ configure: "--gui",
7539
+ login: "--login",
7540
+ uninstall: "--uninstall"
7541
+ };
7542
+ /** Whether a value is one of the modes the page may request. */
7543
+ function isSetupMode(value) {
7544
+ return value === "configure" || value === "login" || value === "uninstall";
7545
+ }
7546
+ /** Cap on kept output, so a chatty `npm install` cannot grow without bound. */
7547
+ const MAX_LINES = 400;
7548
+ /** The latest run per edition: the two installers may run independently. */
7549
+ const current = /* @__PURE__ */ new Map();
7550
+ /**
7551
+ * Locate one edition's helper inside this package.
7552
+ *
7553
+ * The host half is bundled to `lib/index.js`, and tests import `src/*.ts`, so
7554
+ * both layouts resolve to the same `scripts/` directory one level up.
7555
+ *
7556
+ * @param brand - which edition's script to find.
7557
+ */
7558
+ function setupScriptPath(brand = "cn") {
7559
+ const here = path.dirname(fileURLToPath(import.meta.url));
7560
+ const script = scriptNameOf(brand);
7561
+ for (const candidate of [path.resolve(here, "..", "scripts", script), path.resolve(here, "scripts", script)]) if (existsSync(candidate)) return candidate;
7562
+ }
7563
+ /** Append decoded text to a run, splitting it into displayable lines. */
7564
+ function absorb(run, chunk, done) {
7565
+ run.pending += run.decoder.decode(chunk, { stream: !done });
7566
+ const parts = run.pending.split(/\r\n|\r|\n/);
7567
+ run.pending = done ? "" : parts.pop() ?? "";
7568
+ for (const part of parts) {
7569
+ if (part.trim() === "") continue;
7570
+ run.lines.push(part);
7571
+ }
7572
+ if (done && run.pending.trim() !== "") run.lines.push(run.pending.trim());
7573
+ while (run.lines.length > MAX_LINES) {
7574
+ run.lines.shift();
7575
+ run.truncated = true;
7576
+ }
7577
+ }
7578
+ /**
7579
+ * Start one edition's helper. Only one run per edition at a time; a finished
7580
+ * one stays readable.
7581
+ *
7582
+ * @param brand - which edition to configure.
7583
+ * @param mode - the fixed flag the page may ask for.
7584
+ * @param onFinish - called once with the exit code.
7585
+ */
7586
+ function startSetup(brand, mode, onFinish) {
7587
+ const previous = current.get(brand);
7588
+ if (previous !== void 0 && previous.finishedAt === void 0) return {
7589
+ started: false,
7590
+ reason: "busy",
7591
+ error: "已经有一次配置在跑了,请等它结束。"
7592
+ };
7593
+ if (process.platform !== "win32") {
7594
+ const command = brandProfile(brand).cliCommands[0];
7595
+ return {
7596
+ started: false,
7597
+ reason: "unsupported",
7598
+ error: `一键${mode === "uninstall" ? "卸载" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
7599
+ };
7600
+ }
7601
+ const script = setupScriptPath(brand);
7602
+ if (script === void 0) return {
7603
+ started: false,
7604
+ reason: "missing-script",
7605
+ error: `插件包里没有 ${scriptNameOf(brand)},缺少 scripts/ 目录。`
7606
+ };
7607
+ const run = {
7608
+ child: void 0,
7609
+ brand,
7610
+ mode,
7611
+ startedAt: Date.now(),
7612
+ lines: [],
7613
+ pending: "",
7614
+ decoder: new TextDecoder("utf-8"),
7615
+ truncated: false
7616
+ };
7617
+ const child = spawn(process.env.ComSpec ?? "cmd.exe", [
7618
+ "/d",
7619
+ "/c",
7620
+ script,
7621
+ FLAGS[mode]
7622
+ ], {
7623
+ cwd: homedir(),
7624
+ windowsHide: true,
7625
+ stdio: [
7626
+ "ignore",
7627
+ "pipe",
7628
+ "pipe"
7629
+ ]
7630
+ });
7631
+ run.child = child;
7632
+ current.set(brand, run);
7633
+ const finish = (code) => {
7634
+ if (run.finishedAt !== void 0) return;
7635
+ run.finishedAt = Date.now();
7636
+ run.code = code;
7637
+ try {
7638
+ onFinish?.(code);
7639
+ } catch (error) {
7640
+ run.lines.push(`收尾回调失败:${error instanceof Error ? error.message : String(error)}`);
7641
+ }
7642
+ };
7643
+ child.stdout?.on("data", (chunk) => absorb(run, chunk, false));
7644
+ child.stderr?.on("data", (chunk) => absorb(run, chunk, false));
7645
+ child.on("error", (error) => {
7646
+ run.lines.push(`无法启动 ${scriptNameOf(brand)}:${error instanceof Error ? error.message : String(error)}`);
7647
+ finish(null);
7648
+ });
7649
+ child.on("close", (code) => {
7650
+ absorb(run, /* @__PURE__ */ new Uint8Array(), true);
7651
+ finish(code);
7652
+ });
7653
+ return { started: true };
7654
+ }
7655
+ /**
7656
+ * The latest run of one edition, with any not-yet-newlined tail included for
7657
+ * live display.
7658
+ *
7659
+ * @param brand - which edition's run to report.
7660
+ */
7661
+ function readSetupStatus(brand = "cn") {
7662
+ const run = current.get(brand);
7663
+ if (run === void 0) return {
7664
+ running: false,
7665
+ lines: [],
7666
+ truncated: false
7667
+ };
7668
+ const lines = run.pending.trim() === "" ? run.lines : [...run.lines, run.pending.trim()];
7669
+ return {
7670
+ running: run.finishedAt === void 0,
7671
+ mode: run.mode,
7672
+ startedAt: run.startedAt,
7673
+ ...run.finishedAt === void 0 ? {} : {
7674
+ finishedAt: run.finishedAt,
7675
+ code: run.code ?? null
7676
+ },
7677
+ lines,
7678
+ truncated: run.truncated
7679
+ };
7680
+ }
7681
+ /**
7682
+ * Abandon the running helper, if any.
7683
+ *
7684
+ * Called when the plugin is disposed. Killing `cmd.exe` does not reap the CLI it
7685
+ * already launched, but the helper's own wait is bounded, so nothing hangs on
7686
+ * the far end.
7687
+ */
7688
+ function stopSetup() {
7689
+ for (const run of current.values()) if (run.finishedAt === void 0) run.child.kill();
7690
+ }
7691
+ //#endregion
7692
+ //#region src/api.ts
7693
+ /** Route prefix this plugin owns; the client resolves it relative to the page. */
7694
+ const API_PREFIX = "/api/llm-qoder-cn";
7695
+ /** Answer one request with JSON. */
7696
+ function send(res, status, payload) {
7697
+ const body = JSON.stringify(payload);
7698
+ res.writeHead(status, {
7699
+ "content-type": "application/json; charset=utf-8",
7700
+ "cache-control": "no-store",
7701
+ "content-length": Buffer.byteLength(body)
7702
+ });
7703
+ res.end(body);
7704
+ }
7705
+ /** Build model rows for a Qoder adapter. */
7706
+ async function buildRows(adapter) {
7707
+ return (await adapter.describeCatalog()).map((entry) => {
7708
+ const override = adapter.contextWindowFor(entry.value);
7709
+ const upstream = entry.defaultContextWindow ?? (entry.availableContextWindows !== void 0 && entry.availableContextWindows.length > 0 ? Math.max(...entry.availableContextWindows) : entry.maxInputTokens) ?? 2e5;
7710
+ const choices = new Set(entry.availableContextWindows ?? []);
7711
+ choices.add(upstream);
7712
+ if (override !== void 0) choices.add(override);
7713
+ const priceFactor = priceFactorOf(entry);
7714
+ return {
7715
+ id: entry.value,
7716
+ name: entry.displayName.length > 0 ? entry.displayName : entry.value,
7717
+ ...entry.description.length > 0 ? { description: entry.description } : {},
7718
+ enabled: !adapter.isModelDisabled(entry.value),
7719
+ vision: entry.isVl === true,
7720
+ contextWindow: override ?? upstream,
7721
+ contextWindows: [...choices].sort((a, b) => a - b),
7722
+ defaultContextWindow: upstream,
7723
+ ...override === void 0 ? {} : { override },
7724
+ ...priceFactor === void 0 ? {} : { priceFactor },
7725
+ reasoning: entry.isReasoning !== false
7726
+ };
7727
+ });
7728
+ }
7729
+ /** Build model rows for the CodeBuddy adapter, for one login region. */
7730
+ async function buildCodeBuddyRows(adapter, region) {
7731
+ return (await adapter.describeCatalog(region)).map((entry) => {
7732
+ const override = adapter.contextWindowFor(entry.id, region);
7733
+ const choices = new Set(entry.contextWindows);
7734
+ choices.add(entry.defaultContextWindow);
7735
+ if (override !== void 0) choices.add(override);
7736
+ return {
7737
+ id: entry.id,
7738
+ name: entry.name,
7739
+ ...entry.description === void 0 ? {} : { description: entry.description },
7740
+ enabled: !adapter.isModelDisabled(entry.id, region),
7741
+ vision: entry.vision,
7742
+ contextWindow: override ?? entry.defaultContextWindow,
7743
+ contextWindows: [...choices].sort((a, b) => a - b),
7744
+ defaultContextWindow: entry.defaultContextWindow,
7745
+ ...override === void 0 ? {} : { override },
7746
+ ...entry.priceFactor === void 0 ? {} : { priceFactor: entry.priceFactor },
7747
+ reasoning: (entry.reasoningEfforts?.length ?? 0) > 0
7748
+ };
7749
+ });
7750
+ }
7751
+ /** Build model rows for the MiniMax adapter, for one login region. */
7752
+ async function buildMinimaxRows(adapter, region) {
7753
+ return (await adapter.describeCatalog(region)).map((entry) => {
7754
+ const override = adapter.contextWindowFor(entry.id, region);
7755
+ const choices = new Set(entry.contextWindows);
7756
+ choices.add(entry.defaultContextWindow);
7757
+ if (override !== void 0) choices.add(override);
7758
+ return {
7759
+ id: entry.id,
7760
+ name: entry.name,
7761
+ ...entry.description === void 0 ? {} : { description: entry.description },
7762
+ enabled: !adapter.isModelDisabled(entry.id, region),
7763
+ vision: entry.vision,
7764
+ contextWindow: override ?? entry.defaultContextWindow,
7765
+ contextWindows: [...choices].sort((a, b) => a - b),
7766
+ defaultContextWindow: entry.defaultContextWindow,
7767
+ ...override === void 0 ? {} : { override },
7768
+ reasoning: entry.reasoning
7769
+ };
7770
+ });
7771
+ }
7772
+ /** Largest request body this route accepts. */
7773
+ const MAX_BODY_BYTES = 2048;
7774
+ /** Read and parse a small JSON request body. */
7775
+ async function readJson(req) {
7776
+ const chunks = [];
7777
+ let size = 0;
7778
+ for await (const part of req) {
7779
+ const chunk = Buffer.isBuffer(part) ? part : Buffer.from(String(part));
7780
+ size += chunk.length;
7781
+ if (size > MAX_BODY_BYTES) throw new Error("请求体过大");
7782
+ chunks.push(chunk);
7783
+ }
7784
+ const text = Buffer.concat(chunks).toString("utf8").trim();
7785
+ if (text === "") throw new Error("缺少请求体");
7786
+ return JSON.parse(text);
7787
+ }
7788
+ /** The brand a query-string or body selected, or undefined when it named none. */
7789
+ function brandFrom(value) {
7790
+ if (value === null || value === void 0 || value === "") return "cn";
7791
+ return isBrandId(value) ? value : void 0;
7792
+ }
7793
+ /** A CodeBuddy region from a query or body, defaulting to the international one. */
7794
+ function regionFrom(value) {
7795
+ if (value === null || value === void 0 || value === "") return "global";
7796
+ return isCodeBuddyRegion(value) ? value : void 0;
7797
+ }
7798
+ /** Handle one request under {@link API_PREFIX}. */
7799
+ async function handleApi(req, res, adapters) {
7800
+ try {
7801
+ const url = new URL(req.url ?? "/", "http://localhost");
5009
7802
  const path = url.pathname.slice(17) || "/";
5010
7803
  const method = req.method ?? "GET";
5011
7804
  const queryBrand = brandFrom(url.searchParams.get("brand"));
5012
7805
  if (queryBrand === void 0) {
5013
- send(res, 400, { error: "brand 只接受 cn、global 或 codebuddy" });
7806
+ send(res, 400, { error: "brand 只接受 cn、global、codebuddy 或 minimax" });
5014
7807
  return;
5015
7808
  }
5016
7809
  const adapter = adapters[queryBrand];
5017
7810
  const codebuddy = queryBrand === "codebuddy" ? adapter : void 0;
7811
+ const minimax = queryBrand === "minimax" ? adapter : void 0;
7812
+ const regional = codebuddy !== void 0 || minimax !== void 0;
5018
7813
  if (path === "/models" && method === "GET") {
5019
7814
  const requestedRegion = url.searchParams.get("region");
5020
7815
  const region = requestedRegion === null || requestedRegion === "" ? void 0 : regionFrom(requestedRegion);
5021
- if (codebuddy !== void 0 && region === void 0 && requestedRegion !== null && requestedRegion !== "") {
7816
+ if (regional && region === void 0 && requestedRegion !== null && requestedRegion !== "") {
5022
7817
  send(res, 400, { error: "region 只接受 global 或 cn" });
5023
7818
  return;
5024
7819
  }
5025
7820
  if (url.searchParams.get("fresh") === "1") {
5026
7821
  if (codebuddy !== void 0) codebuddy.invalidateCatalog(region);
7822
+ else if (minimax !== void 0) minimax.invalidateCatalog(region);
5027
7823
  else adapter.invalidateCatalog();
5028
7824
  }
5029
- const signedIn = codebuddy?.isSignedIn(region);
5030
- const rows = codebuddy !== void 0 ? signedIn === false ? [] : await buildCodeBuddyRows(codebuddy, region) : await buildRows(adapter);
5031
- const notice = rows.length === 0 ? codebuddy === void 0 ? adapter.catalogError() : codebuddy.catalogError(region) : void 0;
7825
+ const signedIn = codebuddy?.isSignedIn(region) ?? minimax?.isSignedIn(region);
7826
+ const rows = codebuddy !== void 0 ? signedIn === false ? [] : await buildCodeBuddyRows(codebuddy, region) : minimax !== void 0 ? signedIn === false ? [] : await buildMinimaxRows(minimax, region) : await buildRows(adapter);
7827
+ const notice = rows.length === 0 ? codebuddy !== void 0 ? codebuddy.catalogError(region) : minimax !== void 0 ? minimax.catalogError(region) : adapter.catalogError() : void 0;
5032
7828
  send(res, 200, {
5033
7829
  brand: queryBrand,
5034
7830
  models: rows,
5035
7831
  ...region === void 0 ? {} : { region },
5036
7832
  ...signedIn === void 0 ? {} : { signedIn },
7833
+ ...minimax === void 0 ? {} : { regionBlocked: minimax.regionBlocked(region) },
5037
7834
  ...notice === void 0 ? {} : { notice }
5038
7835
  });
5039
7836
  return;
@@ -5041,21 +7838,22 @@ async function handleApi(req, res, adapters) {
5041
7838
  if (path === "/usage" && method === "GET") {
5042
7839
  const requested = url.searchParams.get("region");
5043
7840
  const region = requested === null || requested === "" ? void 0 : regionFrom(requested);
5044
- if (codebuddy !== void 0 && region === void 0 && requested !== null && requested !== "") {
7841
+ if (regional && region === void 0 && requested !== null && requested !== "") {
5045
7842
  send(res, 400, { error: "region 只接受 global 或 cn" });
5046
7843
  return;
5047
7844
  }
7845
+ const fresh = url.searchParams.get("fresh") === "1";
5048
7846
  send(res, 200, {
5049
7847
  brand: queryBrand,
5050
- ...codebuddy !== void 0 ? await codebuddy.usageInfo(url.searchParams.get("fresh") === "1", region) : await adapter.usageInfo(url.searchParams.get("fresh") === "1"),
5051
- ...codebuddy === void 0 ? {} : { signedIn: codebuddy.isSignedIn(region) }
7848
+ ...codebuddy !== void 0 ? await codebuddy.usageInfo(fresh, region) : minimax !== void 0 ? await minimax.usageInfo(fresh, region) : await adapter.usageInfo(fresh),
7849
+ ...codebuddy === void 0 && minimax === void 0 ? {} : { signedIn: (codebuddy ?? minimax).isSignedIn(region) }
5052
7850
  });
5053
7851
  return;
5054
7852
  }
5055
7853
  if (path === "/auth") {
5056
7854
  if (method === "GET") {
5057
- if (codebuddy === void 0) {
5058
- send(res, 404, { error: "该 provider 没有 CodeBuddy 登录流程" });
7855
+ if (codebuddy === void 0 && minimax === void 0) {
7856
+ send(res, 404, { error: "该 provider 没有浏览器登录流程" });
5059
7857
  return;
5060
7858
  }
5061
7859
  const region = regionFrom(url.searchParams.get("region"));
@@ -5063,9 +7861,12 @@ async function handleApi(req, res, adapters) {
5063
7861
  send(res, 400, { error: "region 只接受 global 或 cn" });
5064
7862
  return;
5065
7863
  }
5066
- send(res, 200, {
7864
+ send(res, 200, codebuddy !== void 0 ? {
5067
7865
  brand: "codebuddy",
5068
7866
  ...codebuddy.authStatus(region)
7867
+ } : {
7868
+ brand: "minimax",
7869
+ ...minimax.authStatus(region)
5069
7870
  });
5070
7871
  return;
5071
7872
  }
@@ -5077,20 +7878,37 @@ async function handleApi(req, res, adapters) {
5077
7878
  send(res, 400, { error: `请求体无法解析:${error instanceof Error ? error.message : String(error)}` });
5078
7879
  return;
5079
7880
  }
5080
- if (brandFrom(body.brand) !== "codebuddy") {
5081
- send(res, 400, { error: "该 provider 没有 CodeBuddy 登录流程" });
7881
+ const postBrand = brandFrom(body.brand);
7882
+ if (postBrand !== "codebuddy" && postBrand !== "minimax") {
7883
+ send(res, 400, { error: "该 provider 没有浏览器登录流程" });
5082
7884
  return;
5083
7885
  }
5084
- const cb = adapters.codebuddy;
5085
7886
  const region = regionFrom(body.region);
5086
7887
  if (region === void 0) {
5087
7888
  send(res, 400, { error: "region 只接受 global 或 cn" });
5088
7889
  return;
5089
7890
  }
5090
- if (body.action === "logout") {
5091
- const result = await cb.logout(region);
5092
- if (!result.ok) {
5093
- send(res, 500, { error: result.error });
7891
+ if (body.action !== "login" && body.action !== "logout") {
7892
+ send(res, 400, { error: "action 只接受 login 或 logout" });
7893
+ return;
7894
+ }
7895
+ if (postBrand === "codebuddy") {
7896
+ const cb = adapters.codebuddy;
7897
+ if (body.action === "logout") {
7898
+ const result = await cb.logout(region);
7899
+ if (!result.ok) {
7900
+ send(res, 500, { error: result.error });
7901
+ return;
7902
+ }
7903
+ send(res, 200, {
7904
+ brand: "codebuddy",
7905
+ ...cb.authStatus(region)
7906
+ });
7907
+ return;
7908
+ }
7909
+ const started = cb.startLogin(region);
7910
+ if (started.started === false) {
7911
+ send(res, 409, { error: started.error });
5094
7912
  return;
5095
7913
  }
5096
7914
  send(res, 200, {
@@ -5099,29 +7917,36 @@ async function handleApi(req, res, adapters) {
5099
7917
  });
5100
7918
  return;
5101
7919
  }
5102
- if (body.action !== "login") {
5103
- send(res, 400, { error: "action 只接受 login 或 logout" });
7920
+ const mm = adapters.minimax;
7921
+ if (body.action === "logout") {
7922
+ send(res, 200, {
7923
+ brand: "minimax",
7924
+ ...await mm.logout(region)
7925
+ });
5104
7926
  return;
5105
7927
  }
5106
- const started = cb.startLogin(region);
7928
+ const started = mm.startLogin(region);
5107
7929
  if (started.started === false) {
5108
7930
  send(res, 409, { error: started.error });
5109
7931
  return;
5110
7932
  }
5111
7933
  send(res, 200, {
5112
- brand: "codebuddy",
5113
- ...cb.authStatus(region)
7934
+ brand: "minimax",
7935
+ ...mm.authStatus(region)
5114
7936
  });
5115
7937
  return;
5116
7938
  }
5117
7939
  }
5118
7940
  if (path === "/setup") {
5119
- if (codebuddy !== void 0) {
5120
- send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
5121
- return;
5122
- }
5123
- const qoder = adapter;
5124
7941
  if (method === "GET") {
7942
+ if (codebuddy !== void 0) {
7943
+ send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
7944
+ return;
7945
+ }
7946
+ if (minimax !== void 0) {
7947
+ send(res, 200, readMinimaxSetupStatus());
7948
+ return;
7949
+ }
5125
7950
  send(res, 200, readSetupStatus(queryBrand));
5126
7951
  return;
5127
7952
  }
@@ -5134,14 +7959,37 @@ async function handleApi(req, res, adapters) {
5134
7959
  return;
5135
7960
  }
5136
7961
  const postBrand = brandFrom(parsed.brand);
5137
- if (postBrand === void 0 || postBrand === "codebuddy") {
5138
- send(res, 400, { error: "该 brand 没有 CLI 安装脚本" });
7962
+ if (postBrand === void 0) {
7963
+ send(res, 400, { error: "brand 只接受 cn、global、codebuddy 或 minimax" });
7964
+ return;
7965
+ }
7966
+ if (postBrand === "codebuddy") {
7967
+ send(res, 400, { error: "CodeBuddy 不需要安装 CLI,请在页面中登录" });
7968
+ return;
7969
+ }
7970
+ if (postBrand === "minimax") {
7971
+ if (!isMinimaxSetupMode(parsed.mode)) {
7972
+ send(res, 400, { error: "mode 只接受 install 或 uninstall" });
7973
+ return;
7974
+ }
7975
+ const mm = adapters.minimax;
7976
+ const result = startMinimaxSetup(parsed.mode, (code) => {
7977
+ if (code !== 0) return;
7978
+ mm.invalidateCatalog();
7979
+ mm.invalidateUsage();
7980
+ });
7981
+ if (!result.started) {
7982
+ send(res, result.reason === "busy" ? 409 : 501, { error: result.error });
7983
+ return;
7984
+ }
7985
+ send(res, 200, readMinimaxSetupStatus());
5139
7986
  return;
5140
7987
  }
5141
7988
  if (!isSetupMode(parsed.mode)) {
5142
7989
  send(res, 400, { error: "mode 只接受 configure、login 或 uninstall" });
5143
7990
  return;
5144
7991
  }
7992
+ const qoder = adapters[postBrand];
5145
7993
  const result = startSetup(postBrand, parsed.mode, (code) => {
5146
7994
  if (code === 0) {
5147
7995
  qoder.invalidateCatalog();
@@ -5155,6 +8003,8 @@ async function handleApi(req, res, adapters) {
5155
8003
  send(res, 200, readSetupStatus(postBrand));
5156
8004
  return;
5157
8005
  }
8006
+ send(res, 405, { error: "不支持的写入路径" });
8007
+ return;
5158
8008
  }
5159
8009
  send(res, method === "GET" ? 404 : 405, { error: method === "GET" ? "not found" : "不支持的写入路径" });
5160
8010
  } catch (error) {
@@ -5225,6 +8075,14 @@ const Config$1 = z$1.object({
5225
8075
  codebuddyGlobalModelContextWindows: z$1.dict(z$1.number()).default({}).description("CodeBuddy 国际版按模型指定的上下文窗口(token 数)。").volatile(),
5226
8076
  codebuddyCnModelContextWindows: z$1.dict(z$1.number()).default({}).description("CodeBuddy 国内版按模型指定的上下文窗口(token 数)。").volatile(),
5227
8077
  codebuddyModelAliases: z$1.dict(z$1.string()).default({}).description("CodeBuddy 额外的模型别名映射:DSH 侧名称 → CodeBuddy 模型 ID。").volatile(),
8078
+ minimaxEnabled: z$1.boolean().default(true).description("启用 MiniMax Code(ACP)。关闭后该设置页、模型列表与 provider 路由都会移除;登录态与模型选择会保留。").volatile(),
8079
+ minimaxRegion: z$1.string().default("cn").description("MiniMax Code 登录区域:cn(国内站 account.minimax.cn)或 global(国际站 account.minimax.io)。").volatile(),
8080
+ minimaxDisplayName: z$1.string().default("MiniMax Code").description("模型选择器里 MiniMax Code 分组的名称。").volatile(),
8081
+ minimaxGlobalDisabledModels: z$1.array(z$1.string()).default([]).description("MiniMax Code 国际站已关闭的模型 ID 列表。").volatile(),
8082
+ minimaxCnDisabledModels: z$1.array(z$1.string()).default([]).description("MiniMax Code 国内站已关闭的模型 ID 列表。").volatile(),
8083
+ minimaxGlobalModelContextWindows: z$1.dict(z$1.number()).default({}).description("MiniMax Code 国际站按模型指定的上下文窗口(token 数)。").volatile(),
8084
+ minimaxCnModelContextWindows: z$1.dict(z$1.number()).default({}).description("MiniMax Code 国内站按模型指定的上下文窗口(token 数)。").volatile(),
8085
+ minimaxModelAliases: z$1.dict(z$1.string()).default({}).description("MiniMax Code 额外的模型别名映射:DSH 侧名称 → ACP 模型值。").volatile(),
5228
8086
  displayName: z$1.string().default("Qoder CN").description("模型选择器里主分组的名称。同时使用多个 Qoder 账号时可区分。").volatile(),
5229
8087
  maxSessions: z$1.number().step(1).min(1).max(64).default(8).description("同时保持的内层会话数上限,超出后按最久未使用关闭。每个会话是一个子进程。").volatile(),
5230
8088
  modelCacheTtlSeconds: z$1.number().step(1).min(10).max(86400).default(300).description("模型列表缓存时长(秒)。调小可更快看到账号侧变化。").volatile(),
@@ -5290,7 +8148,15 @@ function liveConfig(config) {
5290
8148
  codebuddyCnDisabledModels: () => stringList(field("codebuddyCnDisabledModels")),
5291
8149
  codebuddyGlobalModelContextWindows: () => numberMap(field("codebuddyGlobalModelContextWindows")),
5292
8150
  codebuddyCnModelContextWindows: () => numberMap(field("codebuddyCnModelContextWindows")),
5293
- codebuddyModelAliases: () => stringMap(field("codebuddyModelAliases"))
8151
+ codebuddyModelAliases: () => stringMap(field("codebuddyModelAliases")),
8152
+ minimaxEnabled: () => bool(field("minimaxEnabled"), true),
8153
+ minimaxRegion: () => field("minimaxRegion") === "global" ? "global" : "cn",
8154
+ minimaxDisplayName: () => nonEmpty(field("minimaxDisplayName"), "MiniMax Code"),
8155
+ minimaxGlobalDisabledModels: () => stringList(field("minimaxGlobalDisabledModels")),
8156
+ minimaxCnDisabledModels: () => stringList(field("minimaxCnDisabledModels")),
8157
+ minimaxGlobalModelContextWindows: () => numberMap(field("minimaxGlobalModelContextWindows")),
8158
+ minimaxCnModelContextWindows: () => numberMap(field("minimaxCnModelContextWindows")),
8159
+ minimaxModelAliases: () => stringMap(field("minimaxModelAliases"))
5294
8160
  };
5295
8161
  }
5296
8162
  /**
@@ -5332,7 +8198,15 @@ function resolveConfig(config) {
5332
8198
  codebuddyCnDisabledModels: live.codebuddyCnDisabledModels(),
5333
8199
  codebuddyGlobalModelContextWindows: live.codebuddyGlobalModelContextWindows(),
5334
8200
  codebuddyCnModelContextWindows: live.codebuddyCnModelContextWindows(),
5335
- codebuddyModelAliases: live.codebuddyModelAliases()
8201
+ codebuddyModelAliases: live.codebuddyModelAliases(),
8202
+ minimaxEnabled: live.minimaxEnabled(),
8203
+ minimaxRegion: live.minimaxRegion(),
8204
+ minimaxDisplayName: live.minimaxDisplayName(),
8205
+ minimaxGlobalDisabledModels: live.minimaxGlobalDisabledModels(),
8206
+ minimaxCnDisabledModels: live.minimaxCnDisabledModels(),
8207
+ minimaxGlobalModelContextWindows: live.minimaxGlobalModelContextWindows(),
8208
+ minimaxCnModelContextWindows: live.minimaxCnModelContextWindows(),
8209
+ minimaxModelAliases: live.minimaxModelAliases()
5336
8210
  };
5337
8211
  }
5338
8212
  function nonEmpty(value, fallback) {
@@ -5395,9 +8269,11 @@ const STRUCTURAL_FIELDS = /* @__PURE__ */ new Set([
5395
8269
  "cnEnabled",
5396
8270
  "intlEnabled",
5397
8271
  "codebuddyEnabled",
8272
+ "minimaxEnabled",
5398
8273
  "displayName",
5399
8274
  "intlDisplayName",
5400
- "codebuddyDisplayName"
8275
+ "codebuddyDisplayName",
8276
+ "minimaxDisplayName"
5401
8277
  ]);
5402
8278
  /** The configurable-provider directory rows for the enabled editions. */
5403
8279
  function directoryFor(live) {
@@ -5420,6 +8296,12 @@ function directoryFor(live) {
5420
8296
  settingsNs: NS,
5421
8297
  settingsPath: []
5422
8298
  });
8299
+ if (live.minimaxEnabled()) rows.push({
8300
+ provider: MINIMAX_PROVIDER,
8301
+ displayName: live.minimaxDisplayName(),
8302
+ settingsNs: NS,
8303
+ settingsPath: []
8304
+ });
5423
8305
  return rows;
5424
8306
  }
5425
8307
  /**
@@ -5511,6 +8393,20 @@ function apply(ctx, config) {
5511
8393
  disabledModels: (region) => region === "cn" ? live.codebuddyCnDisabledModels() : live.codebuddyGlobalDisabledModels(),
5512
8394
  modelContextWindows: (region) => region === "cn" ? live.codebuddyCnModelContextWindows() : live.codebuddyGlobalModelContextWindows(),
5513
8395
  modelAliases: live.codebuddyModelAliases
8396
+ }),
8397
+ minimax: new MinimaxAdapter({
8398
+ maxSessions: live.maxSessions,
8399
+ modelCacheTtlMs: live.modelCacheTtlMs,
8400
+ catalogFetchTimeoutMs: live.catalogFetchTimeoutMs,
8401
+ toolResultTimeoutMs: live.toolResultTimeoutMs,
8402
+ abortGraceMs: live.abortGraceMs,
8403
+ defaultMaxTokens: live.defaultMaxTokens,
8404
+ defaultReasoningEffort: live.defaultReasoningEffort,
8405
+ displayName: live.minimaxDisplayName,
8406
+ region: live.minimaxRegion,
8407
+ disabledModels: (region) => region === "cn" ? live.minimaxCnDisabledModels() : live.minimaxGlobalDisabledModels(),
8408
+ modelContextWindows: (region) => region === "cn" ? live.minimaxCnModelContextWindows() : live.minimaxGlobalModelContextWindows(),
8409
+ modelAliases: live.minimaxModelAliases
5514
8410
  })
5515
8411
  };
5516
8412
  ctx.inject(["attachments"], (scope) => {
@@ -5524,6 +8420,7 @@ function apply(ctx, config) {
5524
8420
  const enabled = (id) => {
5525
8421
  if (id === "cn") return live.cnEnabled();
5526
8422
  if (id === "global") return live.intlEnabled();
8423
+ if (id === "minimax") return live.minimaxEnabled();
5527
8424
  return live.codebuddyEnabled();
5528
8425
  };
5529
8426
  /**
@@ -5570,8 +8467,12 @@ function apply(ctx, config) {
5570
8467
  adapters.cn.close();
5571
8468
  adapters.global.close();
5572
8469
  adapters.codebuddy.close();
8470
+ adapters.minimax.close();
5573
8471
  }, "llm-qoder-cn.sessions");
5574
- ctx.effect(() => () => stopSetup(), "llm-qoder-cn.setup");
8472
+ ctx.effect(() => () => {
8473
+ stopSetup();
8474
+ stopMinimaxSetup();
8475
+ }, "llm-qoder-cn.setup");
5575
8476
  ctx.inject(["webServer"], (scope) => {
5576
8477
  const server = scope.webServer;
5577
8478
  if (server === void 0) return;
@@ -5586,4 +8487,4 @@ function apply(ctx, config) {
5586
8487
  });
5587
8488
  }
5588
8489
  //#endregion
5589
- 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 };
8490
+ 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 };