dsh-agent-sdk-bridge 1.2.3 → 1.3.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/src/minimax.ts CHANGED
@@ -1,2458 +1,2463 @@
1
- /**
2
- * MiniMax Code over the Agent Client Protocol.
3
- *
4
- * `mcode acp` is a stdio ACP server: the plugin starts one process per warm
5
- * host session, negotiates capabilities, creates one ACP session, and streams
6
- * `session/update` notifications back to the harness. Host tools are injected
7
- * as an HTTP MCP server (`mcpServers` in `session/new`), so a tool call the
8
- * model makes reaches this plugin and then the harness, exactly like the
9
- * CodeBuddy path.
10
- *
11
- * Two MiniMax behaviours shape this module:
12
- *
13
- * - ACP has no way to turn off the CLI's built-in tools. The model may call
14
- * `bash`/`write`/`read` directly, which would bypass the harness. The client
15
- * watches `tool_call` notifications and cancels the prompt before execution;
16
- * the turn is then retried with a correction. Host MCP tools are the only
17
- * calls allowed through.
18
- * - The CLI stores one auth state per region and selects it with
19
- * `MAVIS_REGION`; every process is pinned so the mainland and international
20
- * accounts can coexist.
21
- *
22
- * @module dsh-agent-sdk-bridge/minimax
23
- */
24
-
25
- import { spawn, type ChildProcess } from 'node:child_process'
26
- import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
27
- import { createHash, randomBytes, randomUUID } from 'node:crypto'
28
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
29
- import { homedir, tmpdir } from 'node:os'
30
- import { join } from 'node:path'
31
- import { Readable, Writable } from 'node:stream'
32
- import {
33
- ClientSideConnection, ndJsonStream, PROTOCOL_VERSION,
34
- } from '@agentclientprotocol/sdk'
35
- import { EMPTY_RESPONSE_CODE, ToolCallId } from '@deepseek-ai/dsh-llm'
36
- import type {
37
- FinishReason, GenerateOptions, RequestMessage, StreamChunk, TokenUsage,
38
- } from '@deepseek-ai/dsh-llm'
39
- import type { MinimaxRegion } from './brand.ts'
40
- import { minimaxCliRegion } from './brand.ts'
41
- import type { Live } from './live.ts'
42
- import { readLive } from './live.ts'
43
- import { resolveMinimaxCli, minimaxCliArgs } from './minimax-cli.ts'
44
- import { estimateTextTokens } from './tokens.ts'
45
-
46
- /** Default context capacity shown for a MiniMax model that declares none. */
47
- export const MINIMAX_DEFAULT_CONTEXT_WINDOW = 512_000
48
- /** Default output cap; the published MiniMax models allow 128k. */
49
- export const MINIMAX_DEFAULT_MAX_TOKENS = 128_000
50
- /** How long one model catalog stays fresh. */
51
- export const MINIMAX_CACHE_TTL_MS = 300_000
52
- /** Bound for one ACP control round trip. */
53
- export const MINIMAX_FETCH_TIMEOUT_MS = 30_000
54
- /** The MCP server name the model sees; its tools are `mcp__dsh-host__*`. */
55
- export const MINIMAX_MCP_SERVER = 'dsh-host'
56
- /** Context choices the hosted models publish. */
57
- const MINIMAX_CONTEXT_CHOICES = [MINIMAX_DEFAULT_CONTEXT_WINDOW, 1_000_000]
58
- /** How many native-tool corrections a turn may trigger before it fails. */
59
- const MAX_NATIVE_TOOL_RETRIES = 2
60
-
61
- /** One model as the settings page and the adapter see it. */
62
- export interface MinimaxModel {
63
- id: string
64
- name: string
65
- description?: string
66
- contextWindows: number[]
67
- defaultContextWindow: number
68
- vision: boolean
69
- reasoning: boolean
70
- reasoningEfforts: string[]
71
- defaultEffort?: string
72
- }
73
-
74
- /** One tool call's result, in the shape the MCP bridge returns. */
75
- export interface MinimaxMcpToolResult {
76
- content: { type: 'text', text: string }[]
77
- isError?: boolean
78
- }
79
-
80
- /**
81
- * One ACP prompt content block.
82
- *
83
- * ACP defines image blocks as base64 `data` plus a `mimeType`; text blocks are
84
- * the historical shape and remain the only kind a text-only feed produces.
85
- */
86
- export type MinimaxPromptBlock =
87
- | { type: 'text', text: string }
88
- | { type: 'image', data: string, mimeType: string }
89
-
90
- /** Login progress and state for one region. */
91
- export interface MinimaxAuthStatus {
92
- running: boolean
93
- region: MinimaxRegion
94
- signedIn: boolean
95
- startedAt?: number
96
- finishedAt?: number
97
- /** Authorization URL, once the CLI prints one. */
98
- url?: string
99
- /** Expiry of the stored access token, when reported. */
100
- expiresAt?: number
101
- error?: string
102
- }
103
-
104
- /** One rolling quota window reported by the coding-plan endpoint. */
105
- export interface MinimaxQuotaWindow {
106
- id: string
107
- label: string
108
- /** Percent still available; absent when the CLI reports no percentage. */
109
- remainingPercent?: number
110
- /** When this window resets. */
111
- resetAt?: number
112
- /** The plan does not count this window (status 3). */
113
- unlimited: boolean
114
- /** Remaining units, when the endpoint reports a count instead of a ratio. */
115
- remainingCount?: number
116
- totalCount?: number
117
- }
118
-
119
- /** Which quota model the account is on. */
120
- export interface MinimaxPlanInfo {
121
- kind: 'token-plan' | 'credits' | 'free'
122
- hasTokenPlan: boolean
123
- /** Plan name the account itself reports, when it has one. */
124
- name?: string
125
- tier?: string
126
- expiresAt?: number
127
- subscriptionType?: string
128
- }
129
-
130
- /** Credit balance from the membership record. */
131
- export interface MinimaxCreditInfo {
132
- remaining: number
133
- purchasedRemaining?: number
134
- freeRemaining?: number
135
- }
136
-
137
- /** Display identity of the signed-in MiniMax account. */
138
- export interface MinimaxAccountInfo {
139
- name?: string
140
- email?: string
141
- avatar?: string
142
- userId?: string
143
- }
144
-
145
- /** What the settings page shows for a MiniMax account. */
146
- export interface MinimaxUsageSnapshot {
147
- at: number
148
- region: MinimaxRegion
149
- signedIn: boolean
150
- /** Whether the `mcode` executable was found. */
151
- installed: boolean
152
- /** The site refused this machine's network and redirected to the other one. */
153
- regionBlocked?: boolean
154
- error?: string
155
- account?: MinimaxAccountInfo
156
- plan?: MinimaxPlanInfo
157
- credits?: MinimaxCreditInfo
158
- /** Coding-plan windows, empty for accounts without a token plan. */
159
- windows?: MinimaxQuotaWindow[]
160
- }
161
-
162
- /** The per-user CLI state directory. */
163
- export function minimaxDataDir(): string {
164
- const override = process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim()
165
- return override !== undefined && override.length > 0 ? override : join(homedir(), '.minimax')
166
- }
167
-
168
- /** Path of one region's auth-state file. */
169
- export function minimaxAuthStatePath(region: MinimaxRegion): string {
170
- const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || 'prod'
171
- return join(minimaxDataDir(), 'auth', buildEnv, minimaxCliRegion(region), 'mcode-public', 'auth-state.json')
172
- }
173
-
174
- /** Path of the credential file the CLI writes its OAuth token to. */
175
- function minimaxAuthRecordPath(region: MinimaxRegion): string {
176
- const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || 'prod'
177
- return join(minimaxDataDir(), 'auth', buildEnv, minimaxCliRegion(region), 'mcode-public', 'auth.json')
178
- }
179
-
180
- /** The CLI command name, for error text. */
181
- export function minimaxCliCommand(): string {
182
- return 'mcode'
183
- }
184
-
185
- /** The host-side MCP namespace the CLI exposes for the injected server. */
186
- const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, '_')}__`]
187
-
188
- /** Whether a CLI tool name belongs to this plugin's MCP server. */
189
- export function isHostMcpTool(name: string): boolean {
190
- return HOST_TOOL_PREFIXES.some(prefix => name.startsWith(prefix))
191
- }
192
-
193
- /** The host-side name of an MCP tool, without the namespace. */
194
- export function hostMcpToolName(name: string): string {
195
- for (const prefix of HOST_TOOL_PREFIXES) {
196
- if (name.startsWith(prefix)) return name.slice(prefix.length)
197
- }
198
- return name
199
- }
200
-
201
- /** Thinking-effort values an ACP config option advertises, minus `default`. */
202
- function effortValues(options: readonly any[] | null | undefined): string[] {
203
- if (!Array.isArray(options)) return []
204
- return options
205
- .map((entry: any) => typeof entry?.value === 'string' ? entry.value : '')
206
- .filter((value: string) => value.length > 0 && value !== 'default')
207
- }
208
-
209
- /** Build one row from a model option entry and the efforts that model accepts. */
210
- function modelRow(entry: any, efforts: readonly string[]): MinimaxModel | undefined {
211
- if (typeof entry?.value !== 'string' || entry.value.length === 0) return undefined
212
- return {
213
- id: entry.value,
214
- name: typeof entry.name === 'string' && entry.name.length > 0 ? entry.name : entry.value,
215
- ...typeof entry.description === 'string' && entry.description.length > 0 ? { description: entry.description } : {},
216
- contextWindows: [...MINIMAX_CONTEXT_CHOICES],
217
- defaultContextWindow: MINIMAX_DEFAULT_CONTEXT_WINDOW,
218
- vision: true,
219
- reasoning: efforts.length > 0,
220
- reasoningEfforts: [...efforts],
221
- }
222
- }
223
-
224
- /** The model config option's values as rows. */
225
- export function minimaxModelsFromConfigOptions(options: readonly any[] | null | undefined): MinimaxModel[] {
226
- if (!Array.isArray(options)) return []
227
- const modelOption = options.find(option => option?.category === 'model' || option?.id === 'model')
228
- const effortOption = options.find(option => option?.id === 'thinkingEffort' || option?.category === 'thought_level')
229
- const efforts = effortValues(effortOption?.options)
230
- if (!Array.isArray(modelOption?.options)) return []
231
- const seen = new Set<string>()
232
- const models: MinimaxModel[] = []
233
- for (const entry of modelOption.options) {
234
- if (typeof entry?.value !== 'string' || entry.value.length === 0 || seen.has(entry.value)) continue
235
- seen.add(entry.value)
236
- const row = modelRow(entry, efforts)
237
- if (row !== undefined) models.push(row)
238
- }
239
- return models
240
- }
241
-
242
- /**
243
- * Read one region's stored auth state, without spawning anything.
244
- *
245
- * The file records its own region; a copy left over from another build or a
246
- * CLI that rotates its layout must not be read as this region's login.
247
- */
248
- function readAuthState(region: MinimaxRegion): { status?: string, expiresAtMs?: number } | undefined {
249
- try {
250
- const parsed = JSON.parse(readFileSync(minimaxAuthStatePath(region), 'utf8')) as {
251
- status?: unknown
252
- expiresAtMs?: unknown
253
- region?: unknown
254
- }
255
- if (typeof parsed.region === 'string' && parsed.region !== minimaxCliRegion(region)) return undefined
256
- return {
257
- ...typeof parsed.status === 'string' ? { status: parsed.status } : {},
258
- ...typeof parsed.expiresAtMs === 'number' ? { expiresAtMs: parsed.expiresAtMs } : {},
259
- }
260
- } catch {
261
- return undefined
262
- }
263
- }
264
-
265
- /** Whether the region has a stored login. */
266
- export function minimaxSignedIn(region: MinimaxRegion): boolean {
267
- return readAuthState(region)?.status === 'authenticated'
268
- }
269
-
270
- // ── Account and quota ──────────────────────────────────────────────────────
271
- //
272
- // The CLI's own account calls run against MiniMax's signed gateway. Its web
273
- // console and TUI read the same endpoints, so the numbers here match what the
274
- // user sees on minimax's site: a coding-plan subscription exposes rolling
275
- // windows, a credit balance exposes the remaining amount.
276
- //
277
- // The signed gateway needs `yy`/`x-timestamp`/`x-signature` derived with the
278
- // CLI's own salt; the quota endpoint takes a plain bearer token plus the
279
- // account's `op_group_id`.
280
-
281
- /** Signed account gateway (the CLI's `agent` host). */
282
- const MINIMAX_ACCOUNT_HOSTS: Readonly<Record<MinimaxRegion, string>> = {
283
- cn: 'https://agent.minimaxi.com',
284
- global: 'https://agent.minimax.io',
285
- }
286
-
287
- /** Host serving the coding-plan quota. */
288
- const MINIMAX_QUOTA_HOSTS: Readonly<Record<MinimaxRegion, string>> = {
289
- cn: 'https://www.minimaxi.com',
290
- global: 'https://platform.minimax.io',
291
- }
292
-
293
- /** Salt the CLI signs account requests with. */
294
- const MINIMAX_ACCOUNT_SALT = 'I*7Cf%WZ#S&%1RlZJ&C2'
295
- /** Bound for one account/quota read. */
296
- const MINIMAX_USAGE_TIMEOUT_MS = 15_000
297
- /** How long one quota reading stays fresh. */
298
- export const MINIMAX_USAGE_CACHE_TTL_MS = 60_000
299
- /** Bound for one region-reachability probe. */
300
- const MINIMAX_REGION_PROBE_TIMEOUT_MS = 5_000
301
- /** How long one reachability verdict stays fresh. */
302
- const MINIMAX_REGION_ACCESS_TTL_MS = 30_000
303
-
304
- /** Domains the two sites serve their API and console from. */
305
- const MINIMAX_INTL_DOMAIN = 'minimax.io'
306
- const MINIMAX_CN_DOMAIN = 'minimaxi.com'
307
-
308
- function hostMatches(hostname: string, domain: string): boolean {
309
- return hostname === domain || hostname.endsWith(`.${domain}`)
310
- }
311
-
312
- /**
313
- * Whether a URL points at the other site.
314
- *
315
- * MiniMax's edge answers a request from the wrong side of the border with a
316
- * 307 to the other site (`.io` -> `.minimaxi.com` and the reverse). The two
317
- * are different origins, so a redirect also drops the Authorization header;
318
- * that is why the CLI reports `401 token is required` instead of an
319
- * actionable error, and why a stale token is not the real cause.
320
- */
321
- export function minimaxHostBelongsToOtherRegion(region: MinimaxRegion, target: string | URL): boolean {
322
- let hostname: string
323
- try {
324
- hostname = typeof target === 'string' ? new URL(target).hostname : target.hostname
325
- } catch {
326
- return false
327
- }
328
- return region === 'global'
329
- ? hostMatches(hostname, MINIMAX_CN_DOMAIN)
330
- : hostMatches(hostname, MINIMAX_INTL_DOMAIN)
331
- }
332
-
333
- /** The sentence the card and the chat surface show for a refused region. */
334
- export function minimaxRegionBlockMessage(region: MinimaxRegion): string {
335
- return region === 'global'
336
- ? '本机 IP 不在 MiniMax 国际站的服务区域,国际站已拒绝连接(请求被重定向到国内站)。请切换到国内站,或更换网络后重试。'
337
- : '本机 IP 不在 MiniMax 国内站的服务区域,国内站已拒绝连接(请求被重定向到国际站)。请切换到国际站,或更换网络后重试。'
338
- }
339
-
340
- /** A region whose hosts refused this machine's network. */
341
- export class MinimaxRegionBlockedError extends Error {
342
- constructor(readonly region: MinimaxRegion) {
343
- super(minimaxRegionBlockMessage(region))
344
- this.name = 'MinimaxRegionBlockedError'
345
- }
346
- }
347
-
348
- const regionAccessCache = new Map<MinimaxRegion, { at: number, blocked: boolean }>()
349
- /**
350
- * Probes already on the wire.
351
- *
352
- * A region switch asks for the quota and the catalog at the same time, and
353
- * both need the same verdict; sharing the request keeps them from disagreeing
354
- * and spares the remote host a duplicate round trip.
355
- */
356
- const regionAccessInflight = new Map<MinimaxRegion, Promise<boolean>>()
357
-
358
- /** Forget a cached reachability verdict. */
359
- export function invalidateMinimaxRegionAccess(region?: MinimaxRegion): void {
360
- if (region === undefined) regionAccessCache.clear()
361
- else regionAccessCache.delete(region)
362
- }
363
-
364
- function rememberRegionAccess(region: MinimaxRegion, blocked: boolean): void {
365
- regionAccessCache.set(region, { at: Date.now(), blocked })
366
- }
367
-
368
- /** The last verdict, for synchronous rendering under the card. */
369
- export function minimaxRegionBlockedCached(region: MinimaxRegion): boolean {
370
- const cached = regionAccessCache.get(region)
371
- return cached?.blocked === true && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS
372
- }
373
-
374
- /**
375
- * Probe the region's account host for a cross-region redirect.
376
- *
377
- * Only a redirect to the other site's domain counts as a block. A timeout or
378
- * DNS failure leaves the previous verdict alone, so callers report the real
379
- * network error instead of blaming the IP.
380
- */
381
- export async function minimaxRegionBlocked(
382
- region: MinimaxRegion,
383
- options: { fresh?: boolean; fetchImpl?: typeof fetch; signal?: AbortSignal } = {},
384
- ): Promise<boolean> {
385
- const cached = regionAccessCache.get(region)
386
- if (options.fresh !== true && cached !== undefined && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS) {
387
- return cached.blocked
388
- }
389
- let pending = regionAccessInflight.get(region)
390
- if (pending === undefined) {
391
- pending = probeRegionAccess(region, options)
392
- .finally(() => { regionAccessInflight.delete(region) })
393
- regionAccessInflight.set(region, pending)
394
- }
395
- return await pending
396
- }
397
-
398
- async function probeRegionAccess(
399
- region: MinimaxRegion,
400
- options: { fetchImpl?: typeof fetch; signal?: AbortSignal },
401
- ): Promise<boolean> {
402
- const cached = regionAccessCache.get(region)
403
- const fetchImpl = options.fetchImpl ?? fetch
404
- const timeout = AbortSignal.timeout(MINIMAX_REGION_PROBE_TIMEOUT_MS)
405
- const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
406
- try {
407
- const response = await fetchImpl(`${MINIMAX_ACCOUNT_HOSTS[region]}/`, {
408
- redirect: 'manual',
409
- signal,
410
- headers: { Accept: 'text/html,application/json' },
411
- })
412
- const location = response.headers.get('location')
413
- const blocked = response.status >= 300 && response.status < 400
414
- && location !== null
415
- && minimaxHostBelongsToOtherRegion(region, location)
416
- rememberRegionAccess(region, blocked)
417
- return blocked
418
- } catch {
419
- return cached?.blocked === true
420
- }
421
- }
422
-
423
- /** Whether one response is the edge redirecting this machine to the other site. */
424
- function redirectTargetsOtherRegion(
425
- region: MinimaxRegion,
426
- requestUrl: URL,
427
- response: Response,
428
- ): boolean {
429
- if (response.status < 300 || response.status >= 400) return false
430
- const location = response.headers.get('location')
431
- if (location === null) return false
432
- try {
433
- return minimaxHostBelongsToOtherRegion(region, new URL(location, requestUrl))
434
- } catch {
435
- return false
436
- }
437
- }
438
-
439
- function asRecord(value: unknown): Record<string, unknown> | undefined {
440
- return value !== null && typeof value === 'object' && !Array.isArray(value)
441
- ? value as Record<string, unknown>
442
- : undefined
443
- }
444
-
445
- function asNumber(value: unknown): number | undefined {
446
- if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
447
- if (typeof value === 'string' && value.trim() !== '') {
448
- const parsed = Number(value)
449
- return Number.isFinite(parsed) ? parsed : undefined
450
- }
451
- return undefined
452
- }
453
-
454
- function asString(value: unknown): string | undefined {
455
- return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
456
- }
457
-
458
- /** Read the OAuth access token the CLI stored for one region. */
459
- function readStoredToken(region: MinimaxRegion): string | undefined {
460
- try {
461
- const parsed = JSON.parse(readFileSync(minimaxAuthRecordPath(region), 'utf8')) as {
462
- records?: Record<string, { accessToken?: unknown }>
463
- }
464
- for (const record of Object.values(parsed.records ?? {})) {
465
- const token = record?.accessToken
466
- if (typeof token === 'string' && token.trim().length > 0) return token.trim()
467
- }
468
- } catch {
469
- // Missing or unreadable; the caller reports a re-login.
470
- }
471
- return undefined
472
- }
473
-
474
- function minimaxMd5(value: string): string {
475
- return createHash('md5').update(value).digest('hex')
476
- }
477
-
478
- /** Build one signed-gateway URL exactly as the CLI does. */
479
- function minimaxAccountUrl(
480
- region: MinimaxRegion,
481
- path: string,
482
- nowMs: number,
483
- realUserId?: string,
484
- ): URL {
485
- const url = new URL(path, MINIMAX_ACCOUNT_HOSTS[region])
486
- const lang = region === 'cn' ? 'zh' : 'en'
487
- url.search = new URLSearchParams({
488
- device_platform: 'mcode',
489
- biz_id: '3',
490
- app_id: '3001',
491
- version_code: '22201',
492
- unix: String(nowMs),
493
- timezone_offset: String(new Date().getTimezoneOffset() * -60),
494
- sys_language: lang,
495
- lang,
496
- device_id: '0',
497
- os_name: process.platform,
498
- browser_name: 'mcode',
499
- user_id: realUserId?.trim() || '0',
500
- client: 'mcode',
501
- }).toString()
502
- return url
503
- }
504
-
505
- interface MinimaxAccountCall {
506
- method?: 'GET' | 'POST'
507
- body?: Record<string, unknown>
508
- realUserId?: string
509
- token: string
510
- fetchImpl: typeof fetch
511
- signal?: AbortSignal
512
- }
513
-
514
- /** One request to the signed gateway, with the CLI's signature headers. */
515
- async function minimaxAccountCall(
516
- region: MinimaxRegion,
517
- path: string,
518
- call: MinimaxAccountCall,
519
- ): Promise<Record<string, unknown>> {
520
- const now = Date.now()
521
- const url = minimaxAccountUrl(region, path, now, call.realUserId)
522
- const target = `${url.pathname}${url.search}`
523
- const body = call.body === undefined ? '' : JSON.stringify(call.body)
524
- const seconds = Math.floor(now / 1000)
525
- const response = await call.fetchImpl(url, {
526
- method: call.method ?? 'GET',
527
- redirect: 'manual',
528
- headers: {
529
- Accept: 'application/json',
530
- 'Content-Type': 'application/json',
531
- 'User-Agent': 'MiniMaxCode',
532
- Authorization: `Bearer ${call.token}`,
533
- yy: minimaxMd5(`${encodeURIComponent(target)}_${body}${minimaxMd5(String(now))}ooui`),
534
- 'x-timestamp': String(seconds),
535
- 'x-signature': minimaxMd5(`${seconds}${MINIMAX_ACCOUNT_SALT}${body}`),
536
- },
537
- ...body === '' ? {} : { body },
538
- ...call.signal === undefined ? {} : { signal: call.signal },
539
- })
540
- if (redirectTargetsOtherRegion(region, url, response)) {
541
- rememberRegionAccess(region, true)
542
- throw new MinimaxRegionBlockedError(region)
543
- }
544
- if (response.status >= 300 && response.status < 400) {
545
- throw new Error(`MiniMax 账号接口返回了意外的重定向(HTTP ${response.status})。`)
546
- }
547
- if (!response.ok) {
548
- if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) {
549
- throw new MinimaxRegionBlockedError(region)
550
- }
551
- throw new Error(response.status === 401 || response.status === 403
552
- ? 'MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。'
553
- : `MiniMax 账号接口返回 HTTP ${response.status}。`)
554
- }
555
- const payload = asRecord(await response.json())
556
- if (payload === undefined) throw new Error('MiniMax 账号接口返回了无法解析的响应。')
557
- const statusInfo = asRecord(payload.statusInfo)
558
- const statusCode = asNumber(statusInfo?.code)
559
- if (statusCode !== undefined && statusCode !== 0) {
560
- throw new Error(asString(statusInfo?.message) ?? `MiniMax 账号接口错误 ${statusCode}。`)
561
- }
562
- const baseResp = asRecord(payload.base_resp)
563
- const baseCode = asNumber(baseResp?.status_code)
564
- if (baseCode !== undefined && baseCode !== 0) {
565
- throw new Error(asString(baseResp?.status_msg) ?? `MiniMax 账号接口错误 ${baseCode}。`)
566
- }
567
- return payload
568
- }
569
-
570
- /**
571
- * Literal characters in a prompt payload; images contribute pixels, not text.
572
- *
573
- * The per-turn input estimate must charge text only, exactly as the Qoder path
574
- * counts a feed, so sending a picture cannot inflate the reported prompt size.
575
- */
576
- function feedTextLengthOf(prompt: string | readonly MinimaxPromptBlock[] | null): number {
577
- if (prompt === null) return 0
578
- if (typeof prompt === 'string') return prompt.length
579
- return prompt.reduce((total, block) => total + (block.type === 'text' ? block.text.length : 0), 0)
580
- }
581
-
582
- /** One window's numbers, named the way the coding-plan endpoint reports them. */
583
- function quotaWindow(
584
- bucket: Record<string, unknown>,
585
- kind: 'interval' | 'weekly',
586
- ): Omit<MinimaxQuotaWindow, 'id' | 'label'> | undefined {
587
- const prefix = kind === 'interval' ? 'current_interval' : 'current_weekly'
588
- const status = asNumber(bucket[`${prefix}_status`])
589
- const unlimited = status === 3
590
- const percent = asNumber(bucket[`${prefix}_remaining_percent`])
591
- const total = asNumber(bucket[`${prefix}_total_count`])
592
- const used = asNumber(bucket[`${prefix}_usage_count`])
593
- // The endpoint calls the count field `usage_count`, but the CLI reads it as
594
- // the remaining amount; keep that interpretation so the card agrees with the
595
- // TUI. A percentage, when present, always wins.
596
- const remaining = percent ?? (total !== undefined && total > 0 && used !== undefined
597
- ? (used / total) * 100
598
- : undefined)
599
- const resetAt = asNumber(bucket[kind === 'interval' ? 'end_time' : 'weekly_end_time'])
600
- if (remaining === undefined && !unlimited && (resetAt === undefined || resetAt <= 0)) return undefined
601
- return {
602
- ...remaining === undefined || unlimited
603
- ? {}
604
- : { remainingPercent: Math.round(Math.min(100, Math.max(0, remaining))) },
605
- ...resetAt !== undefined && resetAt > 0 ? { resetAt } : {},
606
- unlimited,
607
- ...kind === 'interval' && used !== undefined ? { remainingCount: Math.max(0, used) } : {},
608
- ...kind === 'interval' && total !== undefined ? { totalCount: Math.max(0, total) } : {},
609
- }
610
- }
611
-
612
- /** Turn one `model_remains` bucket into its 5-hour and weekly rows. */
613
- function windowRows(
614
- id: string,
615
- label: string,
616
- bucket: Record<string, unknown>,
617
- ): MinimaxQuotaWindow[] {
618
- const rows: MinimaxQuotaWindow[] = []
619
- const interval = quotaWindow(bucket, 'interval')
620
- if (interval !== undefined) rows.push({ id: `${id}:5h`, label: `${label} · 5 小时`, ...interval })
621
- const weekly = quotaWindow(bucket, 'weekly')
622
- if (weekly !== undefined) rows.push({ id: `${id}:7d`, label: `${label} · 本周`, ...weekly })
623
- return rows
624
- }
625
-
626
- /** Parse `/v1/api/openplatform/coding_plan/remains`. */
627
- function parseMinimaxRemains(payload: Record<string, unknown> | undefined): MinimaxQuotaWindow[] {
628
- if (payload === undefined) return []
629
- const baseResp = asRecord(payload.base_resp)
630
- const code = asNumber(baseResp?.status_code)
631
- // 2062 is "no active token plan", not an error worth showing.
632
- if (code !== undefined && code !== 0) return []
633
- const buckets = Array.isArray(payload.model_remains)
634
- ? payload.model_remains
635
- .map(asRecord)
636
- .filter((bucket): bucket is Record<string, unknown> => bucket !== undefined)
637
- : []
638
- const rows: MinimaxQuotaWindow[] = []
639
- const general = buckets[0]
640
- if (general !== undefined) rows.push(...windowRows('general', '通用', general))
641
- const video = buckets.find(bucket => {
642
- const name = asString(bucket.model_name) ?? ''
643
- return /video/i.test(name) && (asNumber(bucket.current_interval_total_count) ?? 0) > 0
644
- })
645
- if (video !== undefined) rows.push(...windowRows('video', '视频', video))
646
- return rows
647
- }
648
-
649
- /**
650
- * Build a snapshot from the three account documents.
651
- *
652
- * Split out from the network path so the mapping is testable without a live
653
- * account: the membership record is the source of the plan and credit
654
- * balance, `remains` only exists for token-plan subscribers.
655
- */
656
- export function minimaxUsageFromParts(parts: {
657
- region: MinimaxRegion
658
- at?: number
659
- installed?: boolean
660
- userInfo?: Record<string, unknown>
661
- workspaces?: readonly Record<string, unknown>[]
662
- membership?: Record<string, unknown>
663
- remains?: Record<string, unknown>
664
- }): MinimaxUsageSnapshot {
665
- const userInfo = parts.userInfo ?? {}
666
- const membership = parts.membership ?? {}
667
- const personal = parts.workspaces?.find(workspace => asNumber(workspace.workspace_type) === 0)
668
- ?? parts.workspaces?.[0]
669
-
670
- const name = asString(userInfo.name)
671
- const email = asString(userInfo.email)
672
- const avatar = asString(userInfo.avatar)
673
- const userId = asString(userInfo.userID)
674
- const account = name === undefined && email === undefined && avatar === undefined && userId === undefined
675
- ? undefined
676
- : {
677
- ...name === undefined ? {} : { name },
678
- ...email === undefined ? {} : { email },
679
- ...avatar === undefined ? {} : { avatar },
680
- ...userId === undefined ? {} : { userId },
681
- }
682
-
683
- const summary = asRecord(membership.op_credit_summary) ?? asRecord(personal?.op_credit_summary)
684
- const remaining = asNumber(summary?.total_remaining_amount)
685
- ?? asNumber(personal?.opcredit_balance)
686
- ?? asNumber(membership.opcredit_balance)
687
- const purchased = asNumber(summary?.purchased_remaining_amount)
688
- const free = asNumber(summary?.free_remaining_amount)
689
- const credits = remaining === undefined
690
- ? undefined
691
- : {
692
- remaining,
693
- ...purchased === undefined ? {} : { purchasedRemaining: purchased },
694
- ...free === undefined ? {} : { freeRemaining: free },
695
- }
696
-
697
- const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true
698
- const kind = hasTokenPlan ? 'token-plan' : credits !== undefined && credits.remaining > 0 ? 'credits' : 'free'
699
- const planName = asString(membership.plan_name) ?? asString(personal?.plan_name)
700
- const tier = asString(membership.token_plan_tier) ?? asString(personal?.token_plan_tier)
701
- const expiresRaw = asNumber(membership.token_plan_expires_at)
702
- ?? asNumber(personal?.token_plan_expires_at)
703
- ?? asNumber(membership.expires_at)
704
- const expiresAt = expiresRaw !== undefined && expiresRaw > 0 ? expiresRaw : undefined
705
- const subscriptionType = asString(membership.subscription_type)
706
- const windows = parseMinimaxRemains(parts.remains)
707
-
708
- return {
709
- at: parts.at ?? Date.now(),
710
- region: parts.region,
711
- signedIn: true,
712
- installed: parts.installed ?? true,
713
- ...account === undefined ? {} : { account },
714
- plan: {
715
- kind,
716
- hasTokenPlan,
717
- ...planName === undefined ? {} : { name: planName },
718
- ...tier === undefined ? {} : { tier },
719
- ...expiresAt === undefined ? {} : { expiresAt },
720
- ...subscriptionType === undefined ? {} : { subscriptionType },
721
- },
722
- ...credits === undefined ? {} : { credits },
723
- ...windows.length === 0 ? {} : { windows },
724
- }
725
- }
726
-
727
- /** Read the quota for a token-plan subscriber; a plain account has none. */
728
- async function readMinimaxRemains(
729
- region: MinimaxRegion,
730
- token: string,
731
- groupId: string,
732
- fetchImpl: typeof fetch,
733
- signal: AbortSignal,
734
- ): Promise<Record<string, unknown> | undefined> {
735
- const url = new URL('/v1/api/openplatform/coding_plan/remains', MINIMAX_QUOTA_HOSTS[region])
736
- const response = await fetchImpl(url, {
737
- redirect: 'manual',
738
- headers: {
739
- Accept: 'application/json',
740
- Authorization: `Bearer ${token}`,
741
- 'X-Group-Id': groupId,
742
- },
743
- signal,
744
- })
745
- if (redirectTargetsOtherRegion(region, url, response)) {
746
- rememberRegionAccess(region, true)
747
- throw new MinimaxRegionBlockedError(region)
748
- }
749
- if (response.status >= 300 && response.status < 400) return undefined
750
- if (!response.ok) {
751
- if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) {
752
- throw new MinimaxRegionBlockedError(region)
753
- }
754
- if (response.status === 401 || response.status === 403) {
755
- throw new Error('MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。')
756
- }
757
- return undefined
758
- }
759
- return asRecord(await response.json())
760
- }
761
-
762
- const usageCache = new Map<MinimaxRegion, { at: number, snapshot: MinimaxUsageSnapshot }>()
763
- const usageInflight = new Map<MinimaxRegion, Promise<MinimaxUsageSnapshot>>()
764
-
765
- /** Drop a cached quota reading, so the next request re-reads it. */
766
- export function invalidateMinimaxUsage(region?: MinimaxRegion): void {
767
- if (region === undefined) {
768
- usageCache.clear()
769
- return
770
- }
771
- usageCache.delete(region)
772
- }
773
-
774
- /**
775
- * Read one region's account, plan and quota.
776
- *
777
- * A failed account call keeps the login state and reports the reason in
778
- * `error`; the settings card shows the account it already knows with that
779
- * message instead of silently claiming nothing is configured.
780
- */
781
- export async function minimaxUsage(
782
- region: MinimaxRegion,
783
- options: {
784
- fresh?: boolean
785
- token?: string
786
- fetchImpl?: typeof fetch
787
- signal?: AbortSignal
788
- } = {},
789
- ): Promise<MinimaxUsageSnapshot> {
790
- const installed = resolveMinimaxCli() !== undefined
791
- const token = options.token ?? readStoredToken(region)
792
- const signedIn = token !== undefined || minimaxSignedIn(region)
793
- if (!signedIn) {
794
- return { at: Date.now(), region, signedIn: false, installed }
795
- }
796
- if (await minimaxRegionBlocked(region, {
797
- fresh: options.fresh,
798
- fetchImpl: options.fetchImpl,
799
- signal: options.signal,
800
- })) {
801
- return {
802
- at: Date.now(),
803
- region,
804
- signedIn: true,
805
- installed,
806
- regionBlocked: true,
807
- error: minimaxRegionBlockMessage(region),
808
- }
809
- }
810
- if (token === undefined) {
811
- return {
812
- at: Date.now(),
813
- region,
814
- signedIn: true,
815
- installed,
816
- error: '未找到 MiniMax 登录凭据,请重新登录。',
817
- }
818
- }
819
- if (options.token === undefined && options.fresh !== true) {
820
- const cached = usageCache.get(region)
821
- if (cached !== undefined && Date.now() - cached.at < MINIMAX_USAGE_CACHE_TTL_MS) return cached.snapshot
822
- }
823
- let pending = usageInflight.get(region)
824
- if (pending === undefined) {
825
- pending = readUsage(region, token, installed, options)
826
- .finally(() => { usageInflight.delete(region) })
827
- usageInflight.set(region, pending)
828
- }
829
- const snapshot = await pending
830
- if (snapshot.error === undefined && options.token === undefined) {
831
- usageCache.set(region, { at: snapshot.at, snapshot })
832
- }
833
- return snapshot
834
- }
835
-
836
- async function readUsage(
837
- region: MinimaxRegion,
838
- token: string,
839
- installed: boolean,
840
- options: { fetchImpl?: typeof fetch, signal?: AbortSignal },
841
- ): Promise<MinimaxUsageSnapshot> {
842
- const timeout = AbortSignal.timeout(MINIMAX_USAGE_TIMEOUT_MS)
843
- const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
844
- const fetchImpl = options.fetchImpl ?? fetch
845
- try {
846
- const info = await minimaxAccountCall(region, '/v1/api/user/info', { token, fetchImpl, signal })
847
- const data = asRecord(info.data)
848
- const userInfo = asRecord(data?.userInfo) ?? asRecord(info.userInfo) ?? {}
849
- const realUserId = asString(userInfo.realUserID) ?? asString(userInfo.real_user_id)
850
- const extra = await minimaxAccountCall(region, '/matrix/api/v1/user/get_user_extra_info', {
851
- method: 'POST',
852
- body: {},
853
- realUserId,
854
- token,
855
- fetchImpl,
856
- signal,
857
- })
858
- const rawWorkspaces = Array.isArray(extra.workspaces)
859
- ? extra.workspaces
860
- : Array.isArray(asRecord(extra.data)?.workspaces)
861
- ? (asRecord(extra.data)?.workspaces as unknown[])
862
- : []
863
- const workspaces = rawWorkspaces
864
- .map(asRecord)
865
- .filter((workspace): workspace is Record<string, unknown> => workspace !== undefined)
866
- const personal = workspaces.find(workspace => asNumber(workspace.workspace_type) === 0)
867
- ?? workspaces[0]
868
- const workspaceId = asNumber(personal?.workspace_id)
869
- const membership = workspaceId === undefined
870
- ? {}
871
- : await minimaxAccountCall(region, '/matrix/api/v1/commerce/get_membership_info', {
872
- method: 'POST',
873
- body: { workspace_id: workspaceId },
874
- realUserId,
875
- token,
876
- fetchImpl,
877
- signal,
878
- })
879
- const groupId = asString(membership.op_group_id) ?? asString(personal?.op_group_id)
880
- const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true
881
- const remains = hasTokenPlan && groupId !== undefined
882
- ? await readMinimaxRemains(region, token, groupId, fetchImpl, signal)
883
- : undefined
884
- return minimaxUsageFromParts({ region, installed, userInfo, workspaces, membership, remains })
885
- } catch (error) {
886
- const blocked = error instanceof MinimaxRegionBlockedError
887
- return {
888
- at: Date.now(),
889
- region,
890
- signedIn: true,
891
- installed,
892
- ...blocked ? { regionBlocked: true } : {},
893
- error: blocked
894
- ? minimaxRegionBlockMessage(region)
895
- : error instanceof Error ? error.message : String(error),
896
- }
897
- }
898
- }
899
-
900
- /** Trim CLI output to a short, token-free sentence. */
901
- function outputTail(lines: readonly string[]): string {
902
- return lines
903
- .slice(-4)
904
- .map(line => line.replace(/mmo(at|rt)_[A-Za-z0-9_-]+/g, 'mmo***'))
905
- .join(' ')
906
- .slice(0, 400)
907
- }
908
-
909
- /**
910
- * Browser login/logout, one run per region.
911
- *
912
- * The CLI owns the OAuth device flow and the credential file. The plugin only
913
- * starts the process, surfaces the authorization URL while it waits, and then
914
- * re-reads the auth-state file to decide whether the region is signed in.
915
- */
916
- export class MinimaxAuth {
917
- private readonly runs = new Map<MinimaxRegion, {
918
- status: MinimaxAuthStatus
919
- child: ChildProcess
920
- lines: string[]
921
- finish: (code: number | null) => void
922
- }>()
923
-
924
- status(region: MinimaxRegion): MinimaxAuthStatus {
925
- const run = this.runs.get(region)
926
- if (run !== undefined) return run.status
927
- const state = readAuthState(region)
928
- return {
929
- running: false,
930
- region,
931
- signedIn: state?.status === 'authenticated',
932
- ...state?.expiresAtMs === undefined ? {} : { expiresAt: state.expiresAtMs },
933
- }
934
- }
935
-
936
- /** Start the CLI's browser login. */
937
- start(region: MinimaxRegion, onFinish?: (ok: boolean) => void): { started: true } | { started: false, error: string } {
938
- const existing = this.runs.get(region)
939
- if (existing !== undefined && existing.status.running) {
940
- return { started: false, error: '该区域正在登录,请先在浏览器中完成授权。' }
941
- }
942
- const spec = resolveMinimaxCli()
943
- if (spec === undefined) {
944
- return { started: false, error: '未安装 MiniMax Code CLI(mcode),请先安装后再登录。' }
945
- }
946
-
947
- const status: MinimaxAuthStatus = { running: true, region, signedIn: false, startedAt: Date.now() }
948
- const run = {
949
- status,
950
- child: undefined as unknown as ChildProcess,
951
- lines: [] as string[],
952
- finish: (_code: number | null): void => {},
953
- }
954
- const env: NodeJS.ProcessEnv = { ...process.env, MAVIS_REGION: minimaxCliRegion(region) }
955
- delete env.MAVIS_AGENT
956
- delete env.MAVIS_SESSION
957
- const child = spawn(spec.command, minimaxCliArgs(spec, ['login', '--region', region === 'cn' ? 'cn' : 'global']), {
958
- cwd: homedir(),
959
- env,
960
- windowsHide: true,
961
- stdio: ['ignore', 'pipe', 'pipe'],
962
- })
963
- run.child = child
964
- this.runs.set(region, run)
965
-
966
- const absorb = (chunk: Buffer): void => {
967
- const text = String(chunk)
968
- for (const line of text.split(/\r?\n/)) {
969
- const trimmed = line.trim()
970
- if (trimmed === '') continue
971
- run.lines.push(trimmed)
972
- const match = /^(?:Open:\s*)?(https?:\/\/\S+)/.exec(trimmed)
973
- if (match !== null) status.url = match[1]
974
- }
975
- while (run.lines.length > 40) run.lines.shift()
976
- }
977
- child.stdout?.on('data', absorb)
978
- child.stderr?.on('data', absorb)
979
-
980
- const finish = (code: number | null): void => {
981
- if (!status.running) return
982
- status.running = false
983
- status.finishedAt = Date.now()
984
- const state = readAuthState(region)
985
- status.signedIn = state?.status === 'authenticated'
986
- if (state?.expiresAtMs !== undefined) status.expiresAt = state.expiresAtMs
987
- // The CLI refuses to sign in to the second region while the other one is
988
- // signed in. That failure must surface even though the target region's
989
- // older credential file may still say `authenticated`.
990
- if (code !== 0) status.error = outputTail(run.lines) || '登录未完成'
991
- else if (!status.signedIn) status.error = outputTail(run.lines) || '登录未完成'
992
- try {
993
- onFinish?.(status.signedIn)
994
- } catch {
995
- // The caller's callback must not break the status bookkeeping.
996
- }
997
- }
998
- run.finish = finish
999
- child.on('error', error => {
1000
- status.error = `无法启动 mcode:${error.message}`
1001
- finish(null)
1002
- })
1003
- child.on('close', code => { finish(code) })
1004
- return { started: true }
1005
- }
1006
-
1007
- /** Sign one region out; the other region is untouched. */
1008
- async logout(region: MinimaxRegion): Promise<MinimaxAuthStatus> {
1009
- const spec = resolveMinimaxCli()
1010
- if (spec === undefined) {
1011
- return { running: false, region, signedIn: false, error: '未安装 MiniMax Code CLI(mcode)。' }
1012
- }
1013
- const env: NodeJS.ProcessEnv = { ...process.env, MAVIS_REGION: minimaxCliRegion(region) }
1014
- delete env.MAVIS_AGENT
1015
- delete env.MAVIS_SESSION
1016
- const result = await new Promise<{ code: number | null, lines: string[] }>(resolve => {
1017
- const lines: string[] = []
1018
- const child = spawn(spec.command, minimaxCliArgs(spec, ['logout', '--region', region === 'cn' ? 'cn' : 'global']), {
1019
- cwd: homedir(),
1020
- env,
1021
- windowsHide: true,
1022
- stdio: ['ignore', 'pipe', 'pipe'],
1023
- })
1024
- const absorb = (chunk: Buffer): void => {
1025
- for (const line of String(chunk).split(/\r?\n/)) {
1026
- if (line.trim() !== '') lines.push(line.trim())
1027
- }
1028
- while (lines.length > 40) lines.shift()
1029
- }
1030
- child.stdout?.on('data', absorb)
1031
- child.stderr?.on('data', absorb)
1032
- const timer = setTimeout(() => {
1033
- child.kill()
1034
- resolve({ code: null, lines })
1035
- }, 20_000)
1036
- child.on('error', () => {
1037
- clearTimeout(timer)
1038
- resolve({ code: null, lines })
1039
- })
1040
- child.on('close', code => {
1041
- clearTimeout(timer)
1042
- resolve({ code, lines })
1043
- })
1044
- })
1045
- this.runs.delete(region)
1046
- const state = readAuthState(region)
1047
- const signedIn = state?.status === 'authenticated'
1048
- return {
1049
- running: false,
1050
- region,
1051
- signedIn,
1052
- ...state?.expiresAtMs === undefined ? {} : { expiresAt: state.expiresAtMs },
1053
- ...result.code !== 0 ? { error: outputTail(result.lines) || '退出登录未完成' } : {},
1054
- }
1055
- }
1056
-
1057
- /** Cancel any login process (plugin disposal). */
1058
- stop(): void {
1059
- for (const run of this.runs.values()) {
1060
- if (run.status.running) run.child.kill()
1061
- }
1062
- }
1063
- }
1064
-
1065
- /** One event the ACP client or the MCP bridge delivers to a turn. */
1066
- type SessionEvent =
1067
- | { kind: 'text', text: string }
1068
- | { kind: 'reasoning', text: string }
1069
- | { kind: 'usage', used: number, size: number }
1070
- | { kind: 'host-tool', callId: string, name: string, args: Record<string, unknown> }
1071
- | { kind: 'native-tool', name: string }
1072
- | { kind: 'prompt-done', stopReason: string }
1073
- | { kind: 'prompt-error', error: Error }
1074
- | { kind: 'closed', error: Error }
1075
-
1076
- /** A single-consumer async event queue. */
1077
- class EventQueue {
1078
- private readonly items: SessionEvent[] = []
1079
- private waiter: ((event: SessionEvent | undefined) => void) | null = null
1080
- private closed = false
1081
-
1082
- push(event: SessionEvent): void {
1083
- if (this.closed) return
1084
- if (this.waiter !== null) {
1085
- const settle = this.waiter
1086
- this.waiter = null
1087
- settle(event)
1088
- return
1089
- }
1090
- this.items.push(event)
1091
- }
1092
-
1093
- close(): void {
1094
- if (this.closed) return
1095
- this.closed = true
1096
- if (this.waiter !== null) {
1097
- const settle = this.waiter
1098
- this.waiter = null
1099
- settle(undefined)
1100
- }
1101
- }
1102
-
1103
- get isClosed(): boolean {
1104
- return this.closed
1105
- }
1106
-
1107
- next(): Promise<SessionEvent | undefined> {
1108
- const item = this.items.shift()
1109
- if (item !== undefined) return Promise.resolve(item)
1110
- if (this.closed) return Promise.resolve(undefined)
1111
- return new Promise<SessionEvent | undefined>(resolve => { this.waiter = resolve })
1112
- }
1113
- }
1114
-
1115
- /** A pending host tool call, waiting for the harness to deliver its result. */
1116
- interface PendingHostCall {
1117
- resolve: (result: MinimaxMcpToolResult) => void
1118
- reject: (error: Error) => void
1119
- timer: NodeJS.Timeout
1120
- }
1121
-
1122
- /** Render a harness tool result for the MCP caller. */
1123
- function renderToolResult(content: unknown): MinimaxMcpToolResult {
1124
- const text = (value: unknown): string => {
1125
- if (typeof value === 'string') return value
1126
- if (value === null || value === undefined) return ''
1127
- try {
1128
- return JSON.stringify(value)
1129
- } catch {
1130
- return String(value)
1131
- }
1132
- }
1133
- if (Array.isArray(content)) {
1134
- const parts: string[] = []
1135
- for (const block of content) {
1136
- if (typeof block === 'string') {
1137
- parts.push(block)
1138
- continue
1139
- }
1140
- if (block !== null && typeof block === 'object' && (block as { type?: unknown }).type === 'text') {
1141
- parts.push(text((block as { text?: unknown }).text))
1142
- continue
1143
- }
1144
- parts.push(text(block))
1145
- }
1146
- const joined = parts.join('\n').trim()
1147
- return { content: [{ type: 'text', text: joined === '' ? '(宿主工具没有返回内容)' : joined }] }
1148
- }
1149
- const joined = text(content).trim()
1150
- return { content: [{ type: 'text', text: joined === '' ? '(宿主工具没有返回内容)' : joined }] }
1151
- }
1152
-
1153
- /** Options for one ACP process. */
1154
- interface MinimaxAcpOptions {
1155
- region: MinimaxRegion
1156
- cwd: string
1157
- systemPrompt: string
1158
- /** HTTP MCP endpoint for host tools; absent for catalog/title calls. */
1159
- mcpUrl?: string
1160
- mcpToken?: string
1161
- /** Disable all CLI tools (catalog and title reads need none). */
1162
- disableTools?: boolean
1163
- timeoutMs?: number
1164
- onUpdate?: (update: SessionEvent) => void
1165
- onExit?: (error: Error) => void
1166
- onPermissionDenied?: (toolName: string) => void
1167
- }
1168
-
1169
- /**
1170
- * One `mcode acp` process and its ACP session.
1171
- *
1172
- * The class only speaks protocol: model/effort config, prompts, cancellation,
1173
- * and the translation of `session/update` into {@link SessionEvent}s. Turn
1174
- * policy (tool calls, retries, harness chunks) lives in {@link MinimaxSession}.
1175
- */
1176
- export class MinimaxAcp {
1177
- private child: ChildProcess | null = null
1178
- private conn: ClientSideConnection | null = null
1179
- private sessionId: string | undefined
1180
- private configOptions: any[] = []
1181
- private systemFile: string | undefined
1182
- private tempDir: string | undefined
1183
- private closing = false
1184
- private stderr: string[] = []
1185
- private readonly options: MinimaxAcpOptions
1186
-
1187
- constructor(options: MinimaxAcpOptions) {
1188
- this.options = options
1189
- }
1190
-
1191
- /** The model/effort options the CLI currently offers. */
1192
- get optionsList(): readonly any[] {
1193
- return this.configOptions
1194
- }
1195
-
1196
- /** The selected model config value. */
1197
- get currentModel(): string | undefined {
1198
- const option = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1199
- return typeof option?.currentValue === 'string' ? option.currentValue : undefined
1200
- }
1201
-
1202
- /** Start the process and create one ACP session. */
1203
- async start(): Promise<void> {
1204
- const spec = resolveMinimaxCli()
1205
- if (spec === undefined) {
1206
- throw new Error('未安装 MiniMax Code CLI(mcode)。请在设置页安装,或运行 npm install -g @minimax-ai/code。')
1207
- }
1208
- const timeout = this.options.timeoutMs ?? MINIMAX_FETCH_TIMEOUT_MS
1209
- const directory = mkdtempSync(join(tmpdir(), 'dsh-minimax-acp-'))
1210
- const systemFile = join(directory, 'system.md')
1211
- writeFileSync(systemFile, this.options.systemPrompt, 'utf8')
1212
- this.systemFile = systemFile
1213
- this.tempDir = directory
1214
-
1215
- const env: NodeJS.ProcessEnv = {
1216
- ...process.env,
1217
- MAVIS_REGION: minimaxCliRegion(this.options.region),
1218
- ...this.options.disableTools === true ? { MAVIS_LOCAL_RUNTIME_DISABLE_TOOLS: '1' } : {},
1219
- }
1220
- delete env.MAVIS_AGENT
1221
- delete env.MAVIS_SESSION
1222
- const child = spawn(
1223
- spec.command,
1224
- minimaxCliArgs(spec, ['acp', '--system-prompt-file', systemFile]),
1225
- { cwd: this.options.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] },
1226
- )
1227
- this.child = child
1228
- child.stderr?.on('data', (chunk: Buffer) => {
1229
- for (const line of String(chunk).split(/\r?\n/)) {
1230
- if (line.trim() !== '') this.stderr.push(line.trim())
1231
- }
1232
- while (this.stderr.length > 30) this.stderr.shift()
1233
- })
1234
- child.on('exit', (code, signal) => {
1235
- if (this.closing) return
1236
- const detail = outputTail(this.stderr) || `mcode acp 退出(code=${String(code)}, signal=${String(signal)})`
1237
- this.options.onExit?.(new Error(detail))
1238
- })
1239
- if (child.stdin === null || child.stdout === null) {
1240
- throw new Error('mcode acp 没有可用的 stdio。')
1241
- }
1242
-
1243
- const client = {
1244
- sessionUpdate: (params: { sessionId?: string, update?: any }): void => {
1245
- if (params.sessionId !== undefined && this.sessionId !== undefined && params.sessionId !== this.sessionId) return
1246
- const update = params.update
1247
- if (update === null || typeof update !== 'object') return
1248
- switch (update.sessionUpdate) {
1249
- case 'agent_message_chunk': {
1250
- const text = typeof update.content?.text === 'string' ? update.content.text : ''
1251
- if (text.length > 0) this.options.onUpdate?.({ kind: 'text', text })
1252
- return
1253
- }
1254
- case 'agent_thought_chunk': {
1255
- const text = typeof update.content?.text === 'string' ? update.content.text : ''
1256
- if (text.length > 0) this.options.onUpdate?.({ kind: 'reasoning', text })
1257
- return
1258
- }
1259
- case 'usage_update': {
1260
- const used = typeof update.used === 'number' ? update.used : 0
1261
- const size = typeof update.size === 'number' ? update.size : 0
1262
- if (size > 0) this.options.onUpdate?.({ kind: 'usage', used, size })
1263
- return
1264
- }
1265
- case 'tool_call':
1266
- case 'tool_call_update': {
1267
- const name = typeof update.title === 'string' && update.title.length > 0
1268
- ? update.title
1269
- : typeof update.name === 'string' ? update.name : ''
1270
- if (name.length === 0) return
1271
- if (!isHostMcpTool(name)) {
1272
- // Built-in tool: the session cancels the prompt before it runs.
1273
- if (update.sessionUpdate === 'tool_call' || update.status === 'in_progress') {
1274
- this.options.onUpdate?.({ kind: 'native-tool', name })
1275
- }
1276
- return
1277
- }
1278
- return
1279
- }
1280
- default:
1281
- return
1282
- }
1283
- },
1284
- requestPermission: async (params: any): Promise<any> => {
1285
- const name = typeof params?.toolCall?.title === 'string' && params.toolCall.title.length > 0
1286
- ? params.toolCall.title
1287
- : typeof params?.toolCall?.name === 'string' ? params.toolCall.name : ''
1288
- const options = Array.isArray(params?.options) ? params.options : []
1289
- if (isHostMcpTool(name)) {
1290
- const allow = options.find((entry: any) => entry?.kind === 'allow_once')
1291
- ?? options.find((entry: any) => entry?.kind === 'allow_always')
1292
- ?? options[0]
1293
- if (allow !== undefined) return { outcome: { outcome: 'selected', optionId: allow.optionId } }
1294
- return { outcome: { outcome: 'cancelled' } }
1295
- }
1296
- this.options.onPermissionDenied?.(name)
1297
- const deny = options.find((entry: any) => entry?.kind === 'reject_once')
1298
- ?? options.find((entry: any) => entry?.kind === 'reject_always')
1299
- return deny === undefined
1300
- ? { outcome: { outcome: 'cancelled' } }
1301
- : { outcome: { outcome: 'selected', optionId: deny.optionId } }
1302
- },
1303
- }
1304
-
1305
- const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout))
1306
- const conn = new ClientSideConnection(() => client as any, stream)
1307
- this.conn = conn
1308
-
1309
- const init = await withTimeout(conn.initialize({
1310
- protocolVersion: PROTOCOL_VERSION,
1311
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
1312
- clientInfo: { name: 'dsh-agent-sdk-bridge', version: '1.1.0' },
1313
- }), timeout, 'mcode acp initialize')
1314
- void init
1315
-
1316
- const mcpServers = this.options.mcpUrl === undefined
1317
- ? []
1318
- : [{
1319
- type: 'http',
1320
- name: MINIMAX_MCP_SERVER,
1321
- url: this.options.mcpUrl,
1322
- headers: [{ name: 'Authorization', value: `Bearer ${this.options.mcpToken ?? ''}` }],
1323
- }]
1324
- const session = await withTimeout(conn.newSession({
1325
- cwd: this.options.cwd,
1326
- mcpServers: mcpServers as any,
1327
- }), timeout, 'mcode acp session/new')
1328
- this.sessionId = session.sessionId
1329
- this.configOptions = Array.isArray(session.configOptions) ? [...session.configOptions] : []
1330
- }
1331
-
1332
- /**
1333
- * Run one prompt; resolves when the agent's turn ends.
1334
- *
1335
- * ACP carries images as `{ type: 'image', data, mimeType }` blocks next to
1336
- * text, which is what makes a pasted picture reach the model at all; a plain
1337
- * string keeps the historical text-only shape.
1338
- */
1339
- async prompt(prompt: string | readonly MinimaxPromptBlock[]): Promise<{ stopReason: string }> {
1340
- if (this.conn === null || this.sessionId === undefined) throw new Error('ACP 会话尚未启动。')
1341
- const blocks: MinimaxPromptBlock[] = typeof prompt === 'string'
1342
- ? [{ type: 'text', text: prompt }]
1343
- : [...prompt]
1344
- const response = await this.conn.prompt({
1345
- sessionId: this.sessionId,
1346
- prompt: blocks,
1347
- } as any)
1348
- return { stopReason: String(response.stopReason) }
1349
- }
1350
-
1351
- /** Ask the agent to stop the active turn. */
1352
- async cancel(): Promise<void> {
1353
- if (this.conn === null || this.sessionId === undefined) return
1354
- try {
1355
- await this.conn.cancel({ sessionId: this.sessionId })
1356
- } catch {
1357
- // A turn that already ended has nothing to cancel.
1358
- }
1359
- }
1360
-
1361
- /** Set a session config option and remember the updated list. */
1362
- async setConfig(id: string, value: string): Promise<void> {
1363
- if (this.conn === null || this.sessionId === undefined) return
1364
- const option = this.configOptions.find(entry => entry?.id === id)
1365
- if (option === undefined) return
1366
- if (option.currentValue === value) return
1367
- const allowed = Array.isArray(option.options)
1368
- ? option.options.some((entry: any) => entry?.value === value)
1369
- : true
1370
- if (!allowed) return
1371
- const response = await this.conn.setSessionConfigOption({
1372
- sessionId: this.sessionId,
1373
- configId: id,
1374
- value,
1375
- } as any)
1376
- if (Array.isArray(response.configOptions)) this.configOptions = [...response.configOptions]
1377
- }
1378
-
1379
- /**
1380
- * List the models the CLI actually accepts, with each model's own efforts.
1381
- *
1382
- * The advertised option list can contain values the agent rejects (0.6.12
1383
- * lists a `M3.1-Flash` non-thinking value and answers `Invalid model
1384
- * reasoning` when it is selected). Selecting each value once is the only
1385
- * reliable filter, and it also reveals that non-thinking models drop the
1386
- * `thinkingEffort` option entirely, so reasoning has to be reported per
1387
- * model rather than once for the catalog.
1388
- */
1389
- async probeModels(): Promise<MinimaxModel[]> {
1390
- const modelOption = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1391
- if (!Array.isArray(modelOption?.options)) return []
1392
- const initial = typeof modelOption.currentValue === 'string' ? modelOption.currentValue : undefined
1393
- const seen = new Set<string>()
1394
- const models: MinimaxModel[] = []
1395
- for (const entry of modelOption.options) {
1396
- if (typeof entry?.value !== 'string' || entry.value.length === 0 || seen.has(entry.value)) continue
1397
- seen.add(entry.value)
1398
- try {
1399
- await this.setConfig(String(modelOption.id), entry.value)
1400
- } catch {
1401
- continue
1402
- }
1403
- const effortOption = this.configOptions.find(option => option?.id === 'thinkingEffort' || option?.category === 'thought_level')
1404
- const row = modelRow(entry, effortValues(effortOption?.options))
1405
- if (row !== undefined) models.push(row)
1406
- }
1407
- if (initial !== undefined && this.currentModel !== initial) {
1408
- try {
1409
- await this.setConfig(String(modelOption.id), initial)
1410
- } catch {
1411
- // The restore is best effort; the caller never prompts this session.
1412
- }
1413
- }
1414
- return models
1415
- }
1416
-
1417
- /** Select the model (and, when supported, the thinking effort). */
1418
- async selectModel(model: string, effort?: string): Promise<void> {
1419
- const modelOption = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1420
- if (modelOption !== undefined) {
1421
- const values = Array.isArray(modelOption.options)
1422
- ? modelOption.options.map((entry: any) => entry?.value)
1423
- : []
1424
- if (values.includes(model)) await this.setConfig(String(modelOption.id), model)
1425
- }
1426
- if (effort !== undefined && effort.length > 0 && effort !== 'default') {
1427
- const effortOption = this.configOptions.find(entry => entry?.id === 'thinkingEffort' || entry?.category === 'thought_level')
1428
- if (effortOption !== undefined) {
1429
- try {
1430
- await this.setConfig(String(effortOption.id), effort)
1431
- } catch {
1432
- // A model that no longer advertises this effort still accepts the
1433
- // turn with its own default; failing here would lose the request.
1434
- }
1435
- }
1436
- }
1437
- }
1438
-
1439
- /** Exit the session and reap the process. */
1440
- async close(): Promise<void> {
1441
- if (this.closing) return
1442
- this.closing = true
1443
- const conn = this.conn
1444
- const sessionId = this.sessionId
1445
- this.conn = null
1446
- this.sessionId = undefined
1447
- if (conn !== null && sessionId !== undefined) {
1448
- await withTimeout(conn.closeSession({ sessionId } as any), 3_000, 'mcode acp session/close').catch(() => undefined)
1449
- }
1450
- this.child?.kill()
1451
- this.child = null
1452
- if (this.tempDir !== undefined) {
1453
- try {
1454
- rmSync(this.tempDir, { recursive: true, force: true })
1455
- } catch {
1456
- // The temp directory may already be gone.
1457
- }
1458
- this.tempDir = undefined
1459
- }
1460
- this.systemFile = undefined
1461
- }
1462
- }
1463
-
1464
- /** A one-shot ACP process used by the catalog and title side channels. */
1465
- async function withAcp<T>(
1466
- region: MinimaxRegion,
1467
- timeoutMs: number,
1468
- run: (acp: MinimaxAcp) => Promise<T>,
1469
- options: { systemPrompt?: string, disableTools?: boolean } = {},
1470
- ): Promise<T> {
1471
- const cwd = mkdtempSync(join(tmpdir(), 'dsh-minimax-side-'))
1472
- const acp = new MinimaxAcp({
1473
- region,
1474
- cwd,
1475
- systemPrompt: options.systemPrompt ?? 'You are a helper. Do not use tools.',
1476
- disableTools: options.disableTools ?? true,
1477
- timeoutMs,
1478
- })
1479
- try {
1480
- await acp.start()
1481
- return await run(acp)
1482
- } finally {
1483
- await acp.close()
1484
- try {
1485
- rmSync(cwd, { recursive: true, force: true })
1486
- } catch {
1487
- // Best effort.
1488
- }
1489
- }
1490
- }
1491
-
1492
- /** Read the model list for one region (cached). */
1493
- export class MinimaxCatalog {
1494
- private readonly snapshots = new Map<MinimaxRegion, { at: number, models: readonly MinimaxModel[] }>()
1495
- private readonly inflight = new Map<MinimaxRegion, Promise<readonly MinimaxModel[]>>()
1496
- private readonly failures = new Map<MinimaxRegion, string>()
1497
-
1498
- constructor(
1499
- private readonly region: Live<MinimaxRegion>,
1500
- private readonly ttlMs: Live<number> = MINIMAX_CACHE_TTL_MS,
1501
- private readonly timeoutMs: Live<number> = MINIMAX_FETCH_TIMEOUT_MS,
1502
- ) {}
1503
-
1504
- /** Models for one region; a failed refresh keeps the last good list. */
1505
- async models(requested?: MinimaxRegion): Promise<readonly MinimaxModel[]> {
1506
- const region = requested ?? readLive(this.region, 'cn')
1507
- if (await minimaxRegionBlocked(region)) {
1508
- this.invalidate(region)
1509
- return []
1510
- }
1511
- const ttl = readLive(this.ttlMs, MINIMAX_CACHE_TTL_MS)
1512
- const cached = this.snapshots.get(region)
1513
- if (cached !== undefined && Date.now() - cached.at < ttl) return cached.models
1514
- let pending = this.inflight.get(region)
1515
- if (pending === undefined) {
1516
- pending = this.fetch(region).finally(() => { this.inflight.delete(region) })
1517
- this.inflight.set(region, pending)
1518
- }
1519
- try {
1520
- const models = await pending
1521
- this.snapshots.set(region, { at: Date.now(), models })
1522
- this.failures.delete(region)
1523
- return models
1524
- } catch (error) {
1525
- this.failures.set(region, error instanceof Error ? error.message : String(error))
1526
- return cached?.models ?? []
1527
- }
1528
- }
1529
-
1530
- /**
1531
- * The last successful list for a region, without probing.
1532
- *
1533
- * The picker resolves a route on every switch; awaiting an ACP probe there
1534
- * cost a process round-trip whenever the TTL had just expired.
1535
- */
1536
- snapshot(requested?: MinimaxRegion): readonly MinimaxModel[] | undefined {
1537
- return this.snapshots.get(requested ?? readLive(this.region, 'cn'))?.models
1538
- }
1539
-
1540
- /** Why the last refresh failed, or undefined when it succeeded. */
1541
- error(requested?: MinimaxRegion): string | undefined {
1542
- return this.failures.get(requested ?? readLive(this.region, 'cn'))
1543
- }
1544
-
1545
- invalidate(region?: MinimaxRegion): void {
1546
- if (region === undefined) {
1547
- this.snapshots.clear()
1548
- this.failures.clear()
1549
- return
1550
- }
1551
- this.snapshots.delete(region)
1552
- this.failures.delete(region)
1553
- }
1554
-
1555
- private async fetch(region: MinimaxRegion): Promise<readonly MinimaxModel[]> {
1556
- if (!minimaxSignedIn(region)) {
1557
- throw new Error(`${region === 'cn' ? 'MiniMax 国内站' : 'MiniMax 国际站'}尚未登录,请先在设置页登录。`)
1558
- }
1559
- if (await minimaxRegionBlocked(region)) {
1560
- throw new MinimaxRegionBlockedError(region)
1561
- }
1562
- const timeout = readLive(this.timeoutMs, MINIMAX_FETCH_TIMEOUT_MS)
1563
- return await withAcp(region, timeout, async acp => acp.probeModels(), {
1564
- systemPrompt: 'You are a helper used only to list models. Do not call any tool.',
1565
- disableTools: true,
1566
- })
1567
- }
1568
- }
1569
-
1570
- /** One shared HTTP MCP server for every warm MiniMax session. */
1571
- export class MinimaxMcpServer {
1572
- private server: Server | undefined
1573
- private port = 0
1574
- private readonly bridges = new Map<string, MinimaxMcpBridge>()
1575
-
1576
- /** The base URL, or undefined before {@link start}. */
1577
- get baseUrl(): string | undefined {
1578
- return this.server === undefined ? undefined : `http://127.0.0.1:${this.port}`
1579
- }
1580
-
1581
- /** Bind to an ephemeral loopback port. */
1582
- async start(): Promise<void> {
1583
- if (this.server !== undefined) return
1584
- const server = createServer((req, res) => { void this.handle(req, res) })
1585
- await new Promise<void>((resolve, reject) => {
1586
- server.once('error', reject)
1587
- server.listen(0, '127.0.0.1', () => resolve())
1588
- })
1589
- const address = server.address()
1590
- if (address === null || typeof address === 'string') {
1591
- server.close()
1592
- throw new Error('无法为 MiniMax 宿主工具分配本地端口。')
1593
- }
1594
- this.port = address.port
1595
- this.server = server
1596
- }
1597
-
1598
- /** Add one session's bridge under a random token. */
1599
- register(bridge: MinimaxMcpBridge): { url: string, token: string } {
1600
- if (this.server === undefined) throw new Error('MiniMax MCP server 尚未启动。')
1601
- const token = randomBytes(24).toString('hex')
1602
- this.bridges.set(token, bridge)
1603
- return { url: `${this.baseUrl}/mcp/${token}`, token }
1604
- }
1605
-
1606
- unregister(token: string): void {
1607
- this.bridges.delete(token)
1608
- }
1609
-
1610
- /** Close the server and release every session. */
1611
- close(): void {
1612
- this.bridges.clear()
1613
- this.server?.close()
1614
- this.server = undefined
1615
- }
1616
-
1617
- private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
1618
- const url = new URL(req.url ?? '/', 'http://127.0.0.1')
1619
- const match = /^\/mcp\/([a-f0-9]+)$/.exec(url.pathname)
1620
- const bridge = match === null ? undefined : this.bridges.get(match[1])
1621
- if (bridge === undefined) {
1622
- res.writeHead(404, { 'content-type': 'application/json' }).end('{"error":"unknown MCP session"}')
1623
- return
1624
- }
1625
- if (req.method === 'GET') {
1626
- res.writeHead(405).end()
1627
- return
1628
- }
1629
- if (req.method === 'DELETE') {
1630
- res.writeHead(200).end()
1631
- return
1632
- }
1633
- if (req.method !== 'POST') {
1634
- res.writeHead(405).end()
1635
- return
1636
- }
1637
- // The path token is unguessable, and the bearer header is required on top
1638
- // of it so a local process cannot reuse a URL it saw in a log.
1639
- if (req.headers.authorization !== `Bearer ${match?.[1] ?? ''}`) {
1640
- res.writeHead(403).end()
1641
- return
1642
- }
1643
- let raw = ''
1644
- for await (const chunk of req) {
1645
- raw += chunk
1646
- if (raw.length > 8 * 1024 * 1024) {
1647
- res.writeHead(413).end()
1648
- return
1649
- }
1650
- }
1651
- let message: any
1652
- try {
1653
- message = JSON.parse(raw)
1654
- } catch {
1655
- res.writeHead(400).end()
1656
- return
1657
- }
1658
- const id = message?.id
1659
- const reply = (payload: unknown): void => {
1660
- const body = JSON.stringify(payload)
1661
- res.writeHead(200, {
1662
- 'content-type': 'application/json',
1663
- 'mcp-session-id': match?.[1] ?? 'dsh-host',
1664
- }).end(body)
1665
- }
1666
- if (message?.method === undefined) {
1667
- res.writeHead(202).end()
1668
- return
1669
- }
1670
- if (id === undefined) {
1671
- // Notifications, including notifications/initialized.
1672
- res.writeHead(202).end()
1673
- return
1674
- }
1675
- try {
1676
- switch (message.method) {
1677
- case 'initialize':
1678
- reply({
1679
- jsonrpc: '2.0',
1680
- id,
1681
- result: {
1682
- protocolVersion: message.params?.protocolVersion ?? '2025-06-18',
1683
- capabilities: { tools: {} },
1684
- serverInfo: { name: MINIMAX_MCP_SERVER, version: '1.0.0' },
1685
- },
1686
- })
1687
- return
1688
- case 'ping':
1689
- reply({ jsonrpc: '2.0', id, result: {} })
1690
- return
1691
- case 'tools/list':
1692
- reply({ jsonrpc: '2.0', id, result: { tools: bridge.tools() } })
1693
- return
1694
- case 'tools/call': {
1695
- const name = typeof message.params?.name === 'string' ? message.params.name : ''
1696
- const args = message.params?.arguments !== null && typeof message.params?.arguments === 'object'
1697
- ? message.params.arguments as Record<string, unknown>
1698
- : {}
1699
- const result = await bridge.call(name, args)
1700
- reply({ jsonrpc: '2.0', id, result })
1701
- return
1702
- }
1703
- default:
1704
- reply({ jsonrpc: '2.0', id, error: { code: -32601, message: `Unknown method ${String(message.method)}` } })
1705
- return
1706
- }
1707
- } catch (error) {
1708
- reply({
1709
- jsonrpc: '2.0',
1710
- id,
1711
- result: {
1712
- content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
1713
- isError: true,
1714
- },
1715
- })
1716
- }
1717
- }
1718
- }
1719
-
1720
- /** One session's view of the MCP server. */
1721
- export class MinimaxMcpBridge {
1722
- private schemas: readonly { name: string, description: string, parameters?: unknown }[] = []
1723
-
1724
- constructor(
1725
- private readonly callHost: (name: string, args: Record<string, unknown>) => Promise<MinimaxMcpToolResult>,
1726
- ) {}
1727
-
1728
- setTools(tools: readonly { name: string, description: string, parameters?: unknown }[]): void {
1729
- this.schemas = tools
1730
- }
1731
-
1732
- tools(): { name: string, description: string, inputSchema: Record<string, unknown> }[] {
1733
- return this.schemas.map(schema => ({
1734
- name: schema.name,
1735
- description: schema.description.length > 0 ? schema.description : schema.name,
1736
- inputSchema: schema.parameters !== null && typeof schema.parameters === 'object'
1737
- ? schema.parameters as Record<string, unknown>
1738
- : { type: 'object', properties: {} },
1739
- }))
1740
- }
1741
-
1742
- async call(name: string, args: Record<string, unknown>): Promise<MinimaxMcpToolResult> {
1743
- if (!this.schemas.some(schema => schema.name === name)) {
1744
- return { content: [{ type: 'text', text: `未知工具:${name}` }], isError: true }
1745
- }
1746
- return await this.callHost(name, args)
1747
- }
1748
- }
1749
-
1750
- /** The result of one warm session's turn. */
1751
- interface TurnState {
1752
- textBlock?: { index: number, text: string }
1753
- reasoningBlock?: { index: number, text: string }
1754
- blockIndex: number
1755
- inputChars: number
1756
- outputChars: number
1757
- reasoningChars: number
1758
- /** Context occupancy the agent reported, the best input-count signal. */
1759
- contextUsed?: number
1760
- }
1761
-
1762
- /**
1763
- * Round one token count up to a whole number.
1764
- *
1765
- * The harness validates every usage bucket as `number().int().nonnegative()`.
1766
- * The text estimator prices by script and therefore returns fractions; a
1767
- * fractional reading is accepted when it streams but makes the durable usage
1768
- * projection fail, and the conversation then refuses to load at all (the
1769
- * "failed to project session" error). Counts must leave this module whole.
1770
- */
1771
- function wholeTokens(value: number): number {
1772
- return Math.max(1, Math.ceil(value))
1773
- }
1774
-
1775
- /** Build a turn's usage from its character counts and the reported context. */
1776
- export function minimaxTurnUsage(counts: {
1777
- contextUsed?: number
1778
- inputChars: number
1779
- outputChars: number
1780
- reasoningChars: number
1781
- }): TokenUsage {
1782
- const inputTokens = wholeTokens(counts.contextUsed ?? estimateTextTokens(counts.inputChars, 0))
1783
- const outputTokens = wholeTokens(estimateTextTokens(counts.outputChars + counts.reasoningChars, 0))
1784
- const reasoningTokens = counts.reasoningChars === 0
1785
- ? undefined
1786
- : Math.min(outputTokens, wholeTokens(estimateTextTokens(counts.reasoningChars, 0)))
1787
- return {
1788
- inputTokens,
1789
- outputTokens,
1790
- ...reasoningTokens === undefined ? {} : { reasoningTokens },
1791
- cacheReadTokens: 0,
1792
- cacheWriteTokens: 0,
1793
- totalTokens: inputTokens + outputTokens,
1794
- }
1795
- }
1796
-
1797
- /** A prompt that asks the model to retry without native tools. */
1798
- const NATIVE_TOOL_CORRECTION = [
1799
- 'SYSTEM NOTICE (not from the user):',
1800
- 'The built-in tools (bash, read, write, edit, glob, grep, web_fetch, task, and every other native tool)',
1801
- 'are disabled in this deployment. Any call to them is cancelled before execution.',
1802
- 'The only valid tools are the host MCP tools whose names begin with mcp__dsh-host__.',
1803
- 'Re-answer the user\'s last request using only those host tools. Do not mention this notice.',
1804
- ].join('\n')
1805
-
1806
- /** The tool policy appended to the host system prompt. */
1807
- const HOST_TOOL_POLICY = [
1808
- '## Host tool protocol',
1809
- 'You are the model backend of DeepSeek Harness.',
1810
- 'The ONLY tools you may call are the host MCP tools exposed by the `dsh-host` MCP server;',
1811
- 'their names begin with `mcp__dsh-host__`. The built-in tools (bash, read, write, edit, glob,',
1812
- 'grep, web_fetch, task, and every other native tool) are disabled in this deployment: calling',
1813
- 'one aborts the turn before execution. Never mention this rule to the user.',
1814
- ].join('\n')
1815
-
1816
- /**
1817
- * One warm MiniMax conversation for a harness session id.
1818
- *
1819
- * The ACP agent owns the history. A turn ends either when the prompt finishes
1820
- * or when a host tool call is handed to the harness; in the latter case the
1821
- * ACP prompt stays open until the harness returns the result on its next
1822
- * request, exactly like the CodeBuddy bridge.
1823
- */
1824
- export class MinimaxSession {
1825
- private acp: MinimaxAcp | null = null
1826
- private readonly events = new EventQueue()
1827
- private readonly bridge: MinimaxMcpBridge
1828
- private readonly pending = new Map<string, PendingHostCall>()
1829
- private readonly toolResultTimeoutMs: number
1830
- private readonly abortGraceMs: number
1831
- private readonly callNonce = randomUUID().slice(0, 8)
1832
- private toolCounter = 0
1833
- private promptInFlight = false
1834
- private activeTurn = false
1835
- private disposed = false
1836
- private region: MinimaxRegion = 'cn'
1837
- private model = ''
1838
- private effort: string | undefined
1839
- private systemPrompt = ''
1840
- private workspace: string | undefined
1841
- /** The harness workspace; absent means the session owns a temp directory. */
1842
- private requestedCwd: string | undefined
1843
- private ownsWorkspace = false
1844
- private mcpToken: string | undefined
1845
- private toolSchemas: readonly { name: string, description: string, parameters?: unknown }[] = []
1846
- private nativeViolation = false
1847
- private cancelSent = false
1848
- private correctionCount = 0
1849
- private observedContextWindow: number | undefined
1850
- /** Was the last turn closed with tool-calls, leaving the ACP prompt open? */
1851
- private awaitingToolResults = false
1852
- /** Host messages already fed to the ACP session, for continuation planning. */
1853
- fedMessages: readonly RequestMessage[] | undefined
1854
- /** Host system prompt last applied; informational for the adapter. */
1855
- fedSystem: string | undefined
1856
-
1857
- constructor(
1858
- readonly sessionId: string,
1859
- initialModel: string,
1860
- private readonly mcpServer: MinimaxMcpServer,
1861
- runtime: { toolResultTimeoutMs?: Live<number>, abortGraceMs?: Live<number> } = {},
1862
- ) {
1863
- this.model = initialModel
1864
- this.toolResultTimeoutMs = readLive(runtime.toolResultTimeoutMs, 120_000)
1865
- this.abortGraceMs = readLive(runtime.abortGraceMs, 5_000)
1866
- this.bridge = new MinimaxMcpBridge((name, args) => this.handleToolCall(name, args))
1867
- }
1868
-
1869
- /** Model context window observed from a real turn, when one was reported. */
1870
- get contextWindow(): number | undefined {
1871
- return this.observedContextWindow
1872
- }
1873
-
1874
- /**
1875
- * Whether the ACP session still owns an unfinished turn.
1876
- *
1877
- * A turn closed with `tool-calls` keeps its prompt open while the host runs
1878
- * the tools, so this stays true between the two host requests. A brand-new
1879
- * user message in that state cannot be injected; the adapter rebuilds the
1880
- * session and feeds the whole history instead.
1881
- */
1882
- get busy(): boolean {
1883
- return this.promptInFlight || this.activeTurn
1884
- }
1885
-
1886
- /**
1887
- * Point the session at a region, model and system prompt.
1888
- *
1889
- * @returns true when the warm ACP process was dropped, which means the
1890
- * conversation state must be rebuilt from the durable history.
1891
- */
1892
- configure(
1893
- region: MinimaxRegion,
1894
- model: string,
1895
- options: { effort?: string, system?: string, cwd?: string } = {},
1896
- ): boolean {
1897
- const nextSystem = options.system ?? ''
1898
- const nextCwd = options.cwd
1899
- let reset = false
1900
- if (this.acp !== null && (
1901
- nextSystem !== this.systemPrompt
1902
- || region !== this.region
1903
- || nextCwd !== this.requestedCwd
1904
- )) {
1905
- // systemPrompt and cwd are fixed when the ACP process starts. Drop the
1906
- // warm session so the adapter's next turn rebuilds it.
1907
- void this.dropAcp()
1908
- this.fedMessages = undefined
1909
- reset = true
1910
- }
1911
- this.region = region
1912
- this.model = model
1913
- this.effort = options.effort
1914
- this.systemPrompt = nextSystem
1915
- this.requestedCwd = nextCwd
1916
- return reset
1917
- }
1918
-
1919
- /** Register the host tools this session's MCP server advertises. */
1920
- ensureTools(tools: readonly { name: string, description: string, parameters?: unknown }[]): void {
1921
- this.toolSchemas = tools
1922
- this.bridge.setTools(tools)
1923
- }
1924
-
1925
- /** Hand the host's tool results to parked handlers. */
1926
- deliverToolResults(tail: readonly { role: string, toolCallId?: unknown, content?: unknown, isError?: boolean }[]): void {
1927
- let freshUserTurn = false
1928
- for (const message of tail) {
1929
- if (message.role === 'user') {
1930
- freshUserTurn = true
1931
- continue
1932
- }
1933
- if (message.role !== 'tool') continue
1934
- const callId = message.toolCallId === undefined ? '' : String(message.toolCallId)
1935
- const pending = this.pending.get(callId)
1936
- if (pending === undefined) continue
1937
- clearTimeout(pending.timer)
1938
- this.pending.delete(callId)
1939
- pending.resolve({
1940
- ...renderToolResult(message.content),
1941
- ...message.isError === true ? { isError: true } : {},
1942
- })
1943
- }
1944
- if (freshUserTurn && this.pending.size > 0) {
1945
- // The user interrupted a tool round; the ACP turn cannot receive these
1946
- // results any more, so settle it and let the next prompt rebuild.
1947
- for (const [callId, pending] of this.pending) {
1948
- clearTimeout(pending.timer)
1949
- pending.reject(new Error('宿主开始了新的用户轮次,未返回的工具结果已取消。'))
1950
- this.pending.delete(callId)
1951
- }
1952
- if (this.promptInFlight) {
1953
- void this.acp?.cancel()
1954
- }
1955
- this.awaitingToolResults = false
1956
- }
1957
- }
1958
-
1959
- /** Run one harness turn. `feed` is new user content, or null for a continuation. */
1960
- async *stream(options: GenerateOptions, feed: string | readonly MinimaxPromptBlock[] | null): AsyncGenerator<StreamChunk> {
1961
- if (this.disposed) throw new Error(`MiniMax session ${this.sessionId} was disposed`)
1962
- if (this.activeTurn) throw new Error(`MiniMax session ${this.sessionId} already has a turn in flight`)
1963
- this.activeTurn = true
1964
- const signal = options.signal
1965
- const turn: TurnState = {
1966
- blockIndex: 0,
1967
- inputChars: feedTextLengthOf(feed),
1968
- outputChars: 0,
1969
- reasoningChars: 0,
1970
- }
1971
- let abortRequested = false
1972
- let abortTimer: ReturnType<typeof setTimeout> | undefined
1973
- let onAbortListener: (() => void) | undefined
1974
-
1975
- try {
1976
- await this.ensureStarted()
1977
- if (!this.promptInFlight) {
1978
- await this.startPrompt(feed ?? '')
1979
- this.awaitingToolResults = false
1980
- } else if (feed !== null && feedTextLengthOf(feed) > 0 && !this.awaitingToolResults) {
1981
- throw new Error('MiniMax 会话正忙:上一轮尚未结束。')
1982
- }
1983
-
1984
- const onAbort = (): void => {
1985
- abortRequested = true
1986
- void this.acp?.cancel()
1987
- abortTimer = setTimeout(() => { void this.dropAcp() }, this.abortGraceMs)
1988
- }
1989
- onAbortListener = onAbort
1990
- signal?.addEventListener('abort', onAbort, { once: true })
1991
-
1992
- while (true) {
1993
- if (signal?.aborted === true) {
1994
- if (!abortRequested) onAbort()
1995
- rejectPending(this.pending, new Error('MiniMax 会话被宿主中止。'))
1996
- this.promptInFlight = false
1997
- this.awaitingToolResults = false
1998
- yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn aborted by host', code: 'ABORTED' } })
1999
- return
2000
- }
2001
- const event = await raceAbort(this.events.next(), signal)
2002
- if (event === undefined) {
2003
- // raceAbort resolves undefined for an abort too; the loop head
2004
- // settles that case with an `aborted` finish.
2005
- if (abortRequested) continue
2006
- yield* this.finish(turn, { kind: 'error', failure: { message: 'MiniMax ACP stream closed', code: 'STREAM_CLOSED' } })
2007
- return
2008
- }
2009
- switch (event.kind) {
2010
- case 'text': {
2011
- turn.outputChars += event.text.length
2012
- if (turn.textBlock === undefined) {
2013
- turn.textBlock = { index: turn.blockIndex++, text: '' }
2014
- yield { type: 'block-start', index: turn.textBlock.index, blockType: 'text' }
2015
- }
2016
- turn.textBlock.text += event.text
2017
- yield { type: 'text-delta', index: turn.textBlock.index, text: event.text }
2018
- continue
2019
- }
2020
- case 'reasoning': {
2021
- turn.reasoningChars += event.text.length
2022
- if (turn.reasoningBlock === undefined) {
2023
- turn.reasoningBlock = { index: turn.blockIndex++, text: '' }
2024
- yield { type: 'block-start', index: turn.reasoningBlock.index, blockType: 'reasoning' }
2025
- }
2026
- turn.reasoningBlock.text += event.text
2027
- yield { type: 'reasoning-delta', index: turn.reasoningBlock.index, text: event.text }
2028
- continue
2029
- }
2030
- case 'usage': {
2031
- if (event.size > 0) this.observedContextWindow = event.size
2032
- if (event.used > 0) turn.contextUsed = event.used
2033
- continue
2034
- }
2035
- case 'host-tool': {
2036
- // Close the prose before the tool block so the harness assembler
2037
- // sees text -> tool-call rather than an end frame after it.
2038
- if (turn.textBlock !== undefined) {
2039
- yield { type: 'block-end', index: turn.textBlock.index, block: { type: 'text', text: turn.textBlock.text } }
2040
- turn.textBlock = undefined
2041
- }
2042
- if (turn.reasoningBlock !== undefined) {
2043
- yield { type: 'block-end', index: turn.reasoningBlock.index, block: { type: 'reasoning', text: turn.reasoningBlock.text } }
2044
- turn.reasoningBlock = undefined
2045
- }
2046
- const index = turn.blockIndex++
2047
- yield { type: 'block-start', index, blockType: 'tool-call' }
2048
- const args = JSON.stringify(event.args)
2049
- yield {
2050
- type: 'tool-call-delta',
2051
- index,
2052
- id: ToolCallId(event.callId),
2053
- name: event.name,
2054
- argumentsDelta: args,
2055
- }
2056
- yield {
2057
- type: 'block-end',
2058
- index,
2059
- block: { type: 'tool-call', id: ToolCallId(event.callId), name: event.name, arguments: args },
2060
- }
2061
- this.awaitingToolResults = true
2062
- yield* this.finish(turn, { kind: 'tool-calls' })
2063
- return
2064
- }
2065
- case 'native-tool': {
2066
- if (!this.cancelSent) {
2067
- this.cancelSent = true
2068
- this.nativeViolation = true
2069
- await this.acp?.cancel()
2070
- }
2071
- continue
2072
- }
2073
- case 'prompt-done': {
2074
- this.promptInFlight = false
2075
- this.cancelSent = false
2076
- if (abortRequested) {
2077
- rejectPending(this.pending, new Error('MiniMax 会话被宿主中止。'))
2078
- yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn aborted by host', code: 'ABORTED' } })
2079
- return
2080
- }
2081
- if (this.nativeViolation) {
2082
- this.nativeViolation = false
2083
- this.correctionCount += 1
2084
- if (this.correctionCount <= MAX_NATIVE_TOOL_RETRIES) {
2085
- await new Promise(resolve => setTimeout(resolve, 350))
2086
- try {
2087
- await this.startPrompt(NATIVE_TOOL_CORRECTION)
2088
- this.awaitingToolResults = false
2089
- continue
2090
- } catch (error) {
2091
- yield* this.finish(turn, {
2092
- kind: 'error',
2093
- failure: {
2094
- message: `MiniMax 内置工具不可用,重试失败:${error instanceof Error ? error.message : String(error)}`,
2095
- code: 'BACKEND_TURN_ERROR',
2096
- },
2097
- })
2098
- return
2099
- }
2100
- }
2101
- yield* this.finish(turn, {
2102
- kind: 'error',
2103
- failure: {
2104
- message: 'MiniMax 连续尝试调用内置工具。本插件只允许宿主 MCP 工具,已取消本轮。',
2105
- code: 'BACKEND_TURN_ERROR',
2106
- },
2107
- })
2108
- return
2109
- }
2110
- if (event.stopReason === 'end_turn' || event.stopReason === 'max_tokens') {
2111
- yield* this.finish(turn, event.stopReason === 'max_tokens' ? { kind: 'max-tokens' } : { kind: 'stop' })
2112
- return
2113
- }
2114
- if (event.stopReason === 'cancelled') {
2115
- yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn cancelled', code: 'ABORTED' } })
2116
- return
2117
- }
2118
- yield* this.finish(turn, { kind: 'stop' })
2119
- return
2120
- }
2121
- case 'prompt-error': {
2122
- this.promptInFlight = false
2123
- this.cancelSent = false
2124
- yield* this.finish(turn, {
2125
- kind: 'error',
2126
- failure: { message: event.error.message, code: 'BACKEND_TURN_ERROR' },
2127
- })
2128
- return
2129
- }
2130
- case 'closed': {
2131
- this.promptInFlight = false
2132
- yield* this.finish(turn, {
2133
- kind: 'error',
2134
- failure: { message: event.error.message, code: 'BACKEND_TURN_ERROR' },
2135
- })
2136
- return
2137
- }
2138
- }
2139
- }
2140
- } finally {
2141
- if (onAbortListener !== undefined) signal?.removeEventListener('abort', onAbortListener)
2142
- if (abortTimer !== undefined) clearTimeout(abortTimer)
2143
- this.activeTurn = false
2144
- }
2145
- }
2146
-
2147
- /** Tear the ACP process down; parked handlers settle with a cancellation. */
2148
- close(): void {
2149
- if (this.disposed) return
2150
- this.disposed = true
2151
- rejectPending(this.pending, new Error('MiniMax 会话已关闭。'))
2152
- this.events.close()
2153
- const workspace = this.workspace
2154
- const owned = this.ownsWorkspace
2155
- this.workspace = undefined
2156
- this.ownsWorkspace = false
2157
- void this.dropAcp().finally(() => {
2158
- if (workspace === undefined || !owned) return
2159
- try {
2160
- rmSync(workspace, { recursive: true, force: true })
2161
- } catch {
2162
- // Best effort.
2163
- }
2164
- })
2165
- }
2166
-
2167
- private async ensureStarted(): Promise<void> {
2168
- if (this.acp !== null) return
2169
- await this.mcpServer.start()
2170
- if (this.workspace === undefined) {
2171
- if (this.requestedCwd !== undefined) {
2172
- this.workspace = this.requestedCwd
2173
- this.ownsWorkspace = false
2174
- } else {
2175
- this.workspace = mkdtempSync(join(tmpdir(), 'dsh-minimax-session-'))
2176
- this.ownsWorkspace = true
2177
- }
2178
- }
2179
- this.bridge.setTools(this.toolSchemas)
2180
- const registered = this.mcpServer.register(this.bridge)
2181
- this.mcpToken = registered.token
2182
- const system = `${this.systemPrompt.trim()}\n\n${HOST_TOOL_POLICY}\n`
2183
- const acp = new MinimaxAcp({
2184
- region: this.region,
2185
- cwd: this.workspace,
2186
- systemPrompt: system,
2187
- mcpUrl: registered.url,
2188
- mcpToken: registered.token,
2189
- onUpdate: update => { this.events.push(update) },
2190
- onExit: error => { this.events.push({ kind: 'closed', error }) },
2191
- })
2192
- try {
2193
- await acp.start()
2194
- await acp.selectModel(this.model, this.effort)
2195
- this.acp = acp
2196
- } catch (error) {
2197
- await acp.close()
2198
- this.mcpServer.unregister(registered.token)
2199
- this.mcpToken = undefined
2200
- throw error
2201
- }
2202
- }
2203
-
2204
- private async startPrompt(prompt: string | readonly MinimaxPromptBlock[]): Promise<void> {
2205
- const acp = this.acp
2206
- if (acp === null) throw new Error('MiniMax ACP 尚未启动。')
2207
- this.promptInFlight = true
2208
- this.cancelSent = false
2209
- void this.launchPrompt(acp, prompt, 0)
2210
- }
2211
-
2212
- /**
2213
- * Start one ACP prompt and publish its outcome.
2214
- *
2215
- * Cancelling a turn makes the next `session/prompt` fail with "Session
2216
- * already has an active Turn" for a short while even though the cancelled
2217
- * prompt has already resolved. That race is routine here: the native-tool
2218
- * correction is sent immediately after such a cancel, so it is retried with
2219
- * a short backoff instead of being reported as a failed turn.
2220
- */
2221
- private async launchPrompt(
2222
- acp: MinimaxAcp,
2223
- prompt: string | readonly MinimaxPromptBlock[],
2224
- attempt: number,
2225
- ): Promise<void> {
2226
- try {
2227
- const response = await acp.prompt(prompt)
2228
- this.events.push({ kind: 'prompt-done', stopReason: response.stopReason })
2229
- } catch (error) {
2230
- const message = error instanceof Error ? error.message : String(error)
2231
- if (/401 token is required/i.test(message)) {
2232
- // With a China IP the international edge redirects to the mainland
2233
- // host, which drops the Authorization header; the CLI then reports a
2234
- // missing token. Refresh the verdict in the background and explain the
2235
- // real cause instead of asking for another login.
2236
- void minimaxRegionBlocked(this.region, { fresh: true })
2237
- const hint = minimaxRegionBlockedCached(this.region)
2238
- ? minimaxRegionBlockMessage(this.region)
2239
- : this.region === 'global'
2240
- ? 'MiniMax 国际站拒绝了本机连接(401 token is required)。通常是本机网络 IP 不在国际站服务区域;请检查网络后重试,或切换到国内站。'
2241
- : 'MiniMax 国内站拒绝了本机连接(401 token is required)。请检查网络或重新登录后重试。'
2242
- this.events.push({ kind: 'prompt-error', error: new Error(hint) })
2243
- return
2244
- }
2245
- const retryable = /active Turn|already has an active/i.test(message)
2246
- if (retryable && attempt < 4 && !this.disposed && this.acp === acp) {
2247
- await new Promise(resolve => setTimeout(resolve, 200 * 2 ** attempt))
2248
- if (!this.disposed && this.acp === acp) {
2249
- await this.launchPrompt(acp, prompt, attempt + 1)
2250
- return
2251
- }
2252
- }
2253
- this.events.push({ kind: 'prompt-error', error: error instanceof Error ? error : new Error(message) })
2254
- }
2255
- }
2256
-
2257
- private async dropAcp(): Promise<void> {
2258
- const acp = this.acp
2259
- this.acp = null
2260
- this.promptInFlight = false
2261
- this.awaitingToolResults = false
2262
- if (acp !== null) await acp.close()
2263
- if (this.mcpToken !== undefined) {
2264
- this.mcpServer.unregister(this.mcpToken)
2265
- this.mcpToken = undefined
2266
- }
2267
- }
2268
-
2269
- private async handleToolCall(name: string, args: Record<string, unknown>): Promise<MinimaxMcpToolResult> {
2270
- if (this.disposed) return { content: [{ type: 'text', text: 'MiniMax 会话已关闭。' }], isError: true }
2271
- const callId = `mm-${this.callNonce}-${++this.toolCounter}`
2272
- const result = new Promise<MinimaxMcpToolResult>((resolve, reject) => {
2273
- const timer = setTimeout(() => {
2274
- this.pending.delete(callId)
2275
- reject(new Error(`宿主工具 ${name} 在 ${Math.round(this.toolResultTimeoutMs / 1000)} 秒内没有返回结果。`))
2276
- }, this.toolResultTimeoutMs)
2277
- this.pending.set(callId, { resolve, reject, timer })
2278
- })
2279
- this.events.push({ kind: 'host-tool', callId, name, args })
2280
- try {
2281
- return await result
2282
- } catch (error) {
2283
- return {
2284
- content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
2285
- isError: true,
2286
- }
2287
- }
2288
- }
2289
-
2290
- private async *finish(turn: TurnState, reason: FinishReason): AsyncGenerator<StreamChunk> {
2291
- if (turn.textBlock !== undefined) {
2292
- yield { type: 'block-end', index: turn.textBlock.index, block: { type: 'text', text: turn.textBlock.text } }
2293
- }
2294
- if (turn.reasoningBlock !== undefined) {
2295
- yield { type: 'block-end', index: turn.reasoningBlock.index, block: { type: 'reasoning', text: turn.reasoningBlock.text } }
2296
- }
2297
- // The CLI reports whole-context occupancy, which is the real prompt size;
2298
- // the character estimate is only the fallback for providers that omit it.
2299
- const usage = minimaxTurnUsage({
2300
- ...turn.contextUsed === undefined ? {} : { contextUsed: turn.contextUsed },
2301
- inputChars: turn.inputChars,
2302
- outputChars: turn.outputChars,
2303
- reasoningChars: turn.reasoningChars,
2304
- })
2305
- yield { type: 'usage', usage }
2306
- yield { type: 'finish', reason }
2307
- if (reason.kind !== 'tool-calls' && !this.disposed) {
2308
- this.correctionCount = 0
2309
- }
2310
- }
2311
- }
2312
-
2313
- /** Reject every parked handler with the same reason. */
2314
- function rejectPending(pending: Map<string, PendingHostCall>, error: Error): void {
2315
- for (const [callId, entry] of pending) {
2316
- clearTimeout(entry.timer)
2317
- entry.reject(error)
2318
- pending.delete(callId)
2319
- }
2320
- }
2321
-
2322
- /** Wait for a promise, or give up after `ms`. */
2323
- function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
2324
- return new Promise<T>((resolve, reject) => {
2325
- const timer = setTimeout(() => { reject(new Error(`${label} timed out after ${ms}ms`)) }, ms)
2326
- promise.then(
2327
- value => { clearTimeout(timer); resolve(value) },
2328
- error => { clearTimeout(timer); reject(error) },
2329
- )
2330
- })
2331
- }
2332
-
2333
- /** Await a queue read, giving up when the harness aborts the turn. */
2334
- function raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T | undefined> {
2335
- if (signal === undefined) return promise
2336
- if (signal.aborted) return Promise.resolve(undefined)
2337
- return new Promise((resolve, reject) => {
2338
- const onAbort = (): void => {
2339
- signal.removeEventListener('abort', onAbort)
2340
- resolve(undefined)
2341
- }
2342
- signal.addEventListener('abort', onAbort, { once: true })
2343
- promise.then(
2344
- value => {
2345
- signal.removeEventListener('abort', onAbort)
2346
- resolve(value)
2347
- },
2348
- error => {
2349
- signal.removeEventListener('abort', onAbort)
2350
- reject(error)
2351
- },
2352
- )
2353
- })
2354
- }
2355
-
2356
- /** Warm session pool, keyed by harness session id. */
2357
- export class MinimaxSessionManager {
2358
- private readonly sessions = new Map<string, { session: MinimaxSession, region: MinimaxRegion }>()
2359
-
2360
- constructor(
2361
- readonly maxSessions: Live<number>,
2362
- private readonly mcpServer: MinimaxMcpServer,
2363
- private readonly runtime: { toolResultTimeoutMs?: Live<number>, abortGraceMs?: Live<number> } = {},
2364
- ) {}
2365
-
2366
- forSession(sessionId: string, region: MinimaxRegion, model: string): MinimaxSession {
2367
- const existing = this.sessions.get(sessionId)
2368
- if (existing !== undefined) {
2369
- if (existing.region !== region) {
2370
- existing.session.close()
2371
- this.sessions.delete(sessionId)
2372
- } else {
2373
- this.sessions.delete(sessionId)
2374
- this.sessions.set(sessionId, existing)
2375
- return existing.session
2376
- }
2377
- }
2378
- const session = new MinimaxSession(sessionId, model, this.mcpServer, this.runtime)
2379
- this.sessions.set(sessionId, { session, region })
2380
- const cap = readLive(this.maxSessions, 8)
2381
- while (this.sessions.size > cap) {
2382
- const oldest = this.sessions.keys().next()
2383
- if (oldest.done === true) break
2384
- const victim = this.sessions.get(oldest.value)
2385
- this.sessions.delete(oldest.value)
2386
- victim?.session.close()
2387
- }
2388
- return session
2389
- }
2390
-
2391
- dispose(sessionId: string): void {
2392
- const entry = this.sessions.get(sessionId)
2393
- if (entry === undefined) return
2394
- this.sessions.delete(sessionId)
2395
- entry.session.close()
2396
- }
2397
-
2398
- closeAll(): void {
2399
- for (const entry of this.sessions.values()) entry.session.close()
2400
- this.sessions.clear()
2401
- }
2402
- }
2403
-
2404
- /** A one-shot turn, used for titles and compaction summaries. */
2405
- export async function minimaxColdStream(
2406
- region: MinimaxRegion,
2407
- prompt: string,
2408
- model: string | undefined,
2409
- options: GenerateOptions,
2410
- ): Promise<StreamChunk[]> {
2411
- const chunks: StreamChunk[] = []
2412
- let text = ''
2413
- const cwd = mkdtempSync(join(tmpdir(), 'dsh-minimax-cold-'))
2414
- const acp = new MinimaxAcp({
2415
- region,
2416
- cwd,
2417
- systemPrompt: 'You are a concise helper used only for titles and summaries. Do not call any tool.',
2418
- disableTools: true,
2419
- onUpdate: update => {
2420
- if (update.kind === 'text') text += update.text
2421
- },
2422
- })
2423
- const signal = options.signal
2424
- const onAbort = (): void => { void acp.cancel() }
2425
- signal?.addEventListener('abort', onAbort, { once: true })
2426
- try {
2427
- await acp.start()
2428
- if (model !== undefined) await acp.selectModel(model)
2429
- const response = await acp.prompt(prompt)
2430
- if (signal?.aborted === true || response.stopReason === 'cancelled') {
2431
- chunks.push({ type: 'finish', reason: { kind: 'aborted', failure: { message: 'aborted by host', code: 'ABORTED' } } })
2432
- return chunks
2433
- }
2434
- if (text.trim().length === 0) {
2435
- chunks.push({ type: 'finish', reason: { kind: 'error', failure: { message: 'MiniMax side-channel returned no content', code: EMPTY_RESPONSE_CODE } } })
2436
- return chunks
2437
- }
2438
- chunks.push({ type: 'block-start', index: 0, blockType: 'text' })
2439
- for (let index = 0; index < text.length; index += 192) {
2440
- chunks.push({ type: 'text-delta', index: 0, text: text.slice(index, index + 192) })
2441
- }
2442
- chunks.push({ type: 'block-end', index: 0, block: { type: 'text', text } })
2443
- chunks.push({
2444
- type: 'usage',
2445
- usage: minimaxTurnUsage({ inputChars: prompt.length, outputChars: text.length, reasoningChars: 0 }),
2446
- })
2447
- chunks.push({ type: 'finish', reason: { kind: 'stop' } })
2448
- return chunks
2449
- } finally {
2450
- signal?.removeEventListener('abort', onAbort)
2451
- await acp.close()
2452
- try {
2453
- rmSync(cwd, { recursive: true, force: true })
2454
- } catch {
2455
- // Best effort.
2456
- }
2457
- }
2458
- }
1
+ /**
2
+ * MiniMax Code over the Agent Client Protocol.
3
+ *
4
+ * `mcode acp` is a stdio ACP server: the plugin starts one process per warm
5
+ * host session, negotiates capabilities, creates one ACP session, and streams
6
+ * `session/update` notifications back to the harness. Host tools are injected
7
+ * as an HTTP MCP server (`mcpServers` in `session/new`), so a tool call the
8
+ * model makes reaches this plugin and then the harness, exactly like the
9
+ * CodeBuddy path.
10
+ *
11
+ * Two MiniMax behaviours shape this module:
12
+ *
13
+ * - ACP has no way to turn off the CLI's built-in tools. The model may call
14
+ * `bash`/`write`/`read` directly, which would bypass the harness. The client
15
+ * watches `tool_call` notifications and cancels the prompt before execution;
16
+ * the turn is then retried with a correction. Host MCP tools are the only
17
+ * calls allowed through.
18
+ * - The CLI stores one auth state per region and selects it with
19
+ * `MAVIS_REGION`; every process is pinned so the mainland and international
20
+ * accounts can coexist.
21
+ *
22
+ * @module dsh-agent-sdk-bridge/minimax
23
+ */
24
+
25
+ import { spawn, type ChildProcess } from 'node:child_process'
26
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
27
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
28
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
29
+ import { homedir, tmpdir } from 'node:os'
30
+ import { join } from 'node:path'
31
+ import { Readable, Writable } from 'node:stream'
32
+ import {
33
+ ClientSideConnection, ndJsonStream, PROTOCOL_VERSION,
34
+ } from '@agentclientprotocol/sdk'
35
+ import { EMPTY_RESPONSE_CODE, ToolCallId } from '@deepseek-ai/dsh-llm'
36
+ import type {
37
+ FinishReason, GenerateOptions, RequestMessage, StreamChunk, TokenUsage,
38
+ } from '@deepseek-ai/dsh-llm'
39
+ import type { MinimaxRegion } from './brand.ts'
40
+ import { minimaxCliRegion } from './brand.ts'
41
+ import type { Live } from './live.ts'
42
+ import { readLive } from './live.ts'
43
+ import { stripMcpNamespace } from './mcp-naming.ts'
44
+ import { resolveMinimaxCli, minimaxCliArgs } from './minimax-cli.ts'
45
+ import { estimateTextTokens } from './tokens.ts'
46
+
47
+ /** Default context capacity shown for a MiniMax model that declares none. */
48
+ export const MINIMAX_DEFAULT_CONTEXT_WINDOW = 512_000
49
+ /** Default output cap; the published MiniMax models allow 128k. */
50
+ export const MINIMAX_DEFAULT_MAX_TOKENS = 128_000
51
+ /** How long one model catalog stays fresh. */
52
+ export const MINIMAX_CACHE_TTL_MS = 300_000
53
+ /** Bound for one ACP control round trip. */
54
+ export const MINIMAX_FETCH_TIMEOUT_MS = 30_000
55
+ /** The MCP server name the model sees; its tools are `mcp__dsh-host__*`. */
56
+ export const MINIMAX_MCP_SERVER = 'dsh-host'
57
+ /** Context choices the hosted models publish. */
58
+ const MINIMAX_CONTEXT_CHOICES = [MINIMAX_DEFAULT_CONTEXT_WINDOW, 1_000_000]
59
+ /** How many native-tool corrections a turn may trigger before it fails. */
60
+ const MAX_NATIVE_TOOL_RETRIES = 2
61
+
62
+ /** One model as the settings page and the adapter see it. */
63
+ export interface MinimaxModel {
64
+ id: string
65
+ name: string
66
+ description?: string
67
+ contextWindows: number[]
68
+ defaultContextWindow: number
69
+ vision: boolean
70
+ reasoning: boolean
71
+ reasoningEfforts: string[]
72
+ defaultEffort?: string
73
+ }
74
+
75
+ /** One tool call's result, in the shape the MCP bridge returns. */
76
+ export interface MinimaxMcpToolResult {
77
+ content: { type: 'text', text: string }[]
78
+ isError?: boolean
79
+ }
80
+
81
+ /**
82
+ * One ACP prompt content block.
83
+ *
84
+ * ACP defines image blocks as base64 `data` plus a `mimeType`; text blocks are
85
+ * the historical shape and remain the only kind a text-only feed produces.
86
+ */
87
+ export type MinimaxPromptBlock =
88
+ | { type: 'text', text: string }
89
+ | { type: 'image', data: string, mimeType: string }
90
+
91
+ /** Login progress and state for one region. */
92
+ export interface MinimaxAuthStatus {
93
+ running: boolean
94
+ region: MinimaxRegion
95
+ signedIn: boolean
96
+ startedAt?: number
97
+ finishedAt?: number
98
+ /** Authorization URL, once the CLI prints one. */
99
+ url?: string
100
+ /** Expiry of the stored access token, when reported. */
101
+ expiresAt?: number
102
+ error?: string
103
+ }
104
+
105
+ /** One rolling quota window reported by the coding-plan endpoint. */
106
+ export interface MinimaxQuotaWindow {
107
+ id: string
108
+ label: string
109
+ /** Percent still available; absent when the CLI reports no percentage. */
110
+ remainingPercent?: number
111
+ /** When this window resets. */
112
+ resetAt?: number
113
+ /** The plan does not count this window (status 3). */
114
+ unlimited: boolean
115
+ /** Remaining units, when the endpoint reports a count instead of a ratio. */
116
+ remainingCount?: number
117
+ totalCount?: number
118
+ }
119
+
120
+ /** Which quota model the account is on. */
121
+ export interface MinimaxPlanInfo {
122
+ kind: 'token-plan' | 'credits' | 'free'
123
+ hasTokenPlan: boolean
124
+ /** Plan name the account itself reports, when it has one. */
125
+ name?: string
126
+ tier?: string
127
+ expiresAt?: number
128
+ subscriptionType?: string
129
+ }
130
+
131
+ /** Credit balance from the membership record. */
132
+ export interface MinimaxCreditInfo {
133
+ remaining: number
134
+ purchasedRemaining?: number
135
+ freeRemaining?: number
136
+ }
137
+
138
+ /** Display identity of the signed-in MiniMax account. */
139
+ export interface MinimaxAccountInfo {
140
+ name?: string
141
+ email?: string
142
+ avatar?: string
143
+ userId?: string
144
+ }
145
+
146
+ /** What the settings page shows for a MiniMax account. */
147
+ export interface MinimaxUsageSnapshot {
148
+ at: number
149
+ region: MinimaxRegion
150
+ signedIn: boolean
151
+ /** Whether the `mcode` executable was found. */
152
+ installed: boolean
153
+ /** The site refused this machine's network and redirected to the other one. */
154
+ regionBlocked?: boolean
155
+ error?: string
156
+ account?: MinimaxAccountInfo
157
+ plan?: MinimaxPlanInfo
158
+ credits?: MinimaxCreditInfo
159
+ /** Coding-plan windows, empty for accounts without a token plan. */
160
+ windows?: MinimaxQuotaWindow[]
161
+ }
162
+
163
+ /** The per-user CLI state directory. */
164
+ export function minimaxDataDir(): string {
165
+ const override = process.env.MINIMAX_DATA_DIR?.trim() || process.env.MAVIS_DATA_DIR?.trim()
166
+ return override !== undefined && override.length > 0 ? override : join(homedir(), '.minimax')
167
+ }
168
+
169
+ /** Path of one region's auth-state file. */
170
+ export function minimaxAuthStatePath(region: MinimaxRegion): string {
171
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || 'prod'
172
+ return join(minimaxDataDir(), 'auth', buildEnv, minimaxCliRegion(region), 'mcode-public', 'auth-state.json')
173
+ }
174
+
175
+ /** Path of the credential file the CLI writes its OAuth token to. */
176
+ function minimaxAuthRecordPath(region: MinimaxRegion): string {
177
+ const buildEnv = process.env.MAVIS_BUILD_ENV?.trim() || 'prod'
178
+ return join(minimaxDataDir(), 'auth', buildEnv, minimaxCliRegion(region), 'mcode-public', 'auth.json')
179
+ }
180
+
181
+ /** The CLI command name, for error text. */
182
+ export function minimaxCliCommand(): string {
183
+ return 'mcode'
184
+ }
185
+
186
+ /** The host-side MCP namespace the CLI exposes for the injected server. */
187
+ const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, '_')}__`]
188
+
189
+ /** Whether a CLI tool name belongs to this plugin's MCP server. */
190
+ export function isHostMcpTool(name: string): boolean {
191
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) !== null
192
+ }
193
+
194
+ /**
195
+ * The host-side name of an MCP tool, without any namespace layer.
196
+ *
197
+ * Every layer is peeled, not just one: a model that emits an already-qualified
198
+ * name has it qualified again by the CLI, and handing the host
199
+ * `mcp__dsh-host__edit` made DSH answer `unknown tool` even though the tool was
200
+ * registered under `edit`. See {@link stripMcpNamespace}.
201
+ */
202
+ export function hostMcpToolName(name: string): string {
203
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) ?? name
204
+ }
205
+
206
+ /** Thinking-effort values an ACP config option advertises, minus `default`. */
207
+ function effortValues(options: readonly any[] | null | undefined): string[] {
208
+ if (!Array.isArray(options)) return []
209
+ return options
210
+ .map((entry: any) => typeof entry?.value === 'string' ? entry.value : '')
211
+ .filter((value: string) => value.length > 0 && value !== 'default')
212
+ }
213
+
214
+ /** Build one row from a model option entry and the efforts that model accepts. */
215
+ function modelRow(entry: any, efforts: readonly string[]): MinimaxModel | undefined {
216
+ if (typeof entry?.value !== 'string' || entry.value.length === 0) return undefined
217
+ return {
218
+ id: entry.value,
219
+ name: typeof entry.name === 'string' && entry.name.length > 0 ? entry.name : entry.value,
220
+ ...typeof entry.description === 'string' && entry.description.length > 0 ? { description: entry.description } : {},
221
+ contextWindows: [...MINIMAX_CONTEXT_CHOICES],
222
+ defaultContextWindow: MINIMAX_DEFAULT_CONTEXT_WINDOW,
223
+ vision: true,
224
+ reasoning: efforts.length > 0,
225
+ reasoningEfforts: [...efforts],
226
+ }
227
+ }
228
+
229
+ /** The model config option's values as rows. */
230
+ export function minimaxModelsFromConfigOptions(options: readonly any[] | null | undefined): MinimaxModel[] {
231
+ if (!Array.isArray(options)) return []
232
+ const modelOption = options.find(option => option?.category === 'model' || option?.id === 'model')
233
+ const effortOption = options.find(option => option?.id === 'thinkingEffort' || option?.category === 'thought_level')
234
+ const efforts = effortValues(effortOption?.options)
235
+ if (!Array.isArray(modelOption?.options)) return []
236
+ const seen = new Set<string>()
237
+ const models: MinimaxModel[] = []
238
+ for (const entry of modelOption.options) {
239
+ if (typeof entry?.value !== 'string' || entry.value.length === 0 || seen.has(entry.value)) continue
240
+ seen.add(entry.value)
241
+ const row = modelRow(entry, efforts)
242
+ if (row !== undefined) models.push(row)
243
+ }
244
+ return models
245
+ }
246
+
247
+ /**
248
+ * Read one region's stored auth state, without spawning anything.
249
+ *
250
+ * The file records its own region; a copy left over from another build or a
251
+ * CLI that rotates its layout must not be read as this region's login.
252
+ */
253
+ function readAuthState(region: MinimaxRegion): { status?: string, expiresAtMs?: number } | undefined {
254
+ try {
255
+ const parsed = JSON.parse(readFileSync(minimaxAuthStatePath(region), 'utf8')) as {
256
+ status?: unknown
257
+ expiresAtMs?: unknown
258
+ region?: unknown
259
+ }
260
+ if (typeof parsed.region === 'string' && parsed.region !== minimaxCliRegion(region)) return undefined
261
+ return {
262
+ ...typeof parsed.status === 'string' ? { status: parsed.status } : {},
263
+ ...typeof parsed.expiresAtMs === 'number' ? { expiresAtMs: parsed.expiresAtMs } : {},
264
+ }
265
+ } catch {
266
+ return undefined
267
+ }
268
+ }
269
+
270
+ /** Whether the region has a stored login. */
271
+ export function minimaxSignedIn(region: MinimaxRegion): boolean {
272
+ return readAuthState(region)?.status === 'authenticated'
273
+ }
274
+
275
+ // ── Account and quota ──────────────────────────────────────────────────────
276
+ //
277
+ // The CLI's own account calls run against MiniMax's signed gateway. Its web
278
+ // console and TUI read the same endpoints, so the numbers here match what the
279
+ // user sees on minimax's site: a coding-plan subscription exposes rolling
280
+ // windows, a credit balance exposes the remaining amount.
281
+ //
282
+ // The signed gateway needs `yy`/`x-timestamp`/`x-signature` derived with the
283
+ // CLI's own salt; the quota endpoint takes a plain bearer token plus the
284
+ // account's `op_group_id`.
285
+
286
+ /** Signed account gateway (the CLI's `agent` host). */
287
+ const MINIMAX_ACCOUNT_HOSTS: Readonly<Record<MinimaxRegion, string>> = {
288
+ cn: 'https://agent.minimaxi.com',
289
+ global: 'https://agent.minimax.io',
290
+ }
291
+
292
+ /** Host serving the coding-plan quota. */
293
+ const MINIMAX_QUOTA_HOSTS: Readonly<Record<MinimaxRegion, string>> = {
294
+ cn: 'https://www.minimaxi.com',
295
+ global: 'https://platform.minimax.io',
296
+ }
297
+
298
+ /** Salt the CLI signs account requests with. */
299
+ const MINIMAX_ACCOUNT_SALT = 'I*7Cf%WZ#S&%1RlZJ&C2'
300
+ /** Bound for one account/quota read. */
301
+ const MINIMAX_USAGE_TIMEOUT_MS = 15_000
302
+ /** How long one quota reading stays fresh. */
303
+ export const MINIMAX_USAGE_CACHE_TTL_MS = 60_000
304
+ /** Bound for one region-reachability probe. */
305
+ const MINIMAX_REGION_PROBE_TIMEOUT_MS = 5_000
306
+ /** How long one reachability verdict stays fresh. */
307
+ const MINIMAX_REGION_ACCESS_TTL_MS = 30_000
308
+
309
+ /** Domains the two sites serve their API and console from. */
310
+ const MINIMAX_INTL_DOMAIN = 'minimax.io'
311
+ const MINIMAX_CN_DOMAIN = 'minimaxi.com'
312
+
313
+ function hostMatches(hostname: string, domain: string): boolean {
314
+ return hostname === domain || hostname.endsWith(`.${domain}`)
315
+ }
316
+
317
+ /**
318
+ * Whether a URL points at the other site.
319
+ *
320
+ * MiniMax's edge answers a request from the wrong side of the border with a
321
+ * 307 to the other site (`.io` -> `.minimaxi.com` and the reverse). The two
322
+ * are different origins, so a redirect also drops the Authorization header;
323
+ * that is why the CLI reports `401 token is required` instead of an
324
+ * actionable error, and why a stale token is not the real cause.
325
+ */
326
+ export function minimaxHostBelongsToOtherRegion(region: MinimaxRegion, target: string | URL): boolean {
327
+ let hostname: string
328
+ try {
329
+ hostname = typeof target === 'string' ? new URL(target).hostname : target.hostname
330
+ } catch {
331
+ return false
332
+ }
333
+ return region === 'global'
334
+ ? hostMatches(hostname, MINIMAX_CN_DOMAIN)
335
+ : hostMatches(hostname, MINIMAX_INTL_DOMAIN)
336
+ }
337
+
338
+ /** The sentence the card and the chat surface show for a refused region. */
339
+ export function minimaxRegionBlockMessage(region: MinimaxRegion): string {
340
+ return region === 'global'
341
+ ? '本机 IP 不在 MiniMax 国际站的服务区域,国际站已拒绝连接(请求被重定向到国内站)。请切换到国内站,或更换网络后重试。'
342
+ : '本机 IP 不在 MiniMax 国内站的服务区域,国内站已拒绝连接(请求被重定向到国际站)。请切换到国际站,或更换网络后重试。'
343
+ }
344
+
345
+ /** A region whose hosts refused this machine's network. */
346
+ export class MinimaxRegionBlockedError extends Error {
347
+ constructor(readonly region: MinimaxRegion) {
348
+ super(minimaxRegionBlockMessage(region))
349
+ this.name = 'MinimaxRegionBlockedError'
350
+ }
351
+ }
352
+
353
+ const regionAccessCache = new Map<MinimaxRegion, { at: number, blocked: boolean }>()
354
+ /**
355
+ * Probes already on the wire.
356
+ *
357
+ * A region switch asks for the quota and the catalog at the same time, and
358
+ * both need the same verdict; sharing the request keeps them from disagreeing
359
+ * and spares the remote host a duplicate round trip.
360
+ */
361
+ const regionAccessInflight = new Map<MinimaxRegion, Promise<boolean>>()
362
+
363
+ /** Forget a cached reachability verdict. */
364
+ export function invalidateMinimaxRegionAccess(region?: MinimaxRegion): void {
365
+ if (region === undefined) regionAccessCache.clear()
366
+ else regionAccessCache.delete(region)
367
+ }
368
+
369
+ function rememberRegionAccess(region: MinimaxRegion, blocked: boolean): void {
370
+ regionAccessCache.set(region, { at: Date.now(), blocked })
371
+ }
372
+
373
+ /** The last verdict, for synchronous rendering under the card. */
374
+ export function minimaxRegionBlockedCached(region: MinimaxRegion): boolean {
375
+ const cached = regionAccessCache.get(region)
376
+ return cached?.blocked === true && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS
377
+ }
378
+
379
+ /**
380
+ * Probe the region's account host for a cross-region redirect.
381
+ *
382
+ * Only a redirect to the other site's domain counts as a block. A timeout or
383
+ * DNS failure leaves the previous verdict alone, so callers report the real
384
+ * network error instead of blaming the IP.
385
+ */
386
+ export async function minimaxRegionBlocked(
387
+ region: MinimaxRegion,
388
+ options: { fresh?: boolean; fetchImpl?: typeof fetch; signal?: AbortSignal } = {},
389
+ ): Promise<boolean> {
390
+ const cached = regionAccessCache.get(region)
391
+ if (options.fresh !== true && cached !== undefined && Date.now() - cached.at < MINIMAX_REGION_ACCESS_TTL_MS) {
392
+ return cached.blocked
393
+ }
394
+ let pending = regionAccessInflight.get(region)
395
+ if (pending === undefined) {
396
+ pending = probeRegionAccess(region, options)
397
+ .finally(() => { regionAccessInflight.delete(region) })
398
+ regionAccessInflight.set(region, pending)
399
+ }
400
+ return await pending
401
+ }
402
+
403
+ async function probeRegionAccess(
404
+ region: MinimaxRegion,
405
+ options: { fetchImpl?: typeof fetch; signal?: AbortSignal },
406
+ ): Promise<boolean> {
407
+ const cached = regionAccessCache.get(region)
408
+ const fetchImpl = options.fetchImpl ?? fetch
409
+ const timeout = AbortSignal.timeout(MINIMAX_REGION_PROBE_TIMEOUT_MS)
410
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
411
+ try {
412
+ const response = await fetchImpl(`${MINIMAX_ACCOUNT_HOSTS[region]}/`, {
413
+ redirect: 'manual',
414
+ signal,
415
+ headers: { Accept: 'text/html,application/json' },
416
+ })
417
+ const location = response.headers.get('location')
418
+ const blocked = response.status >= 300 && response.status < 400
419
+ && location !== null
420
+ && minimaxHostBelongsToOtherRegion(region, location)
421
+ rememberRegionAccess(region, blocked)
422
+ return blocked
423
+ } catch {
424
+ return cached?.blocked === true
425
+ }
426
+ }
427
+
428
+ /** Whether one response is the edge redirecting this machine to the other site. */
429
+ function redirectTargetsOtherRegion(
430
+ region: MinimaxRegion,
431
+ requestUrl: URL,
432
+ response: Response,
433
+ ): boolean {
434
+ if (response.status < 300 || response.status >= 400) return false
435
+ const location = response.headers.get('location')
436
+ if (location === null) return false
437
+ try {
438
+ return minimaxHostBelongsToOtherRegion(region, new URL(location, requestUrl))
439
+ } catch {
440
+ return false
441
+ }
442
+ }
443
+
444
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
445
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
446
+ ? value as Record<string, unknown>
447
+ : undefined
448
+ }
449
+
450
+ function asNumber(value: unknown): number | undefined {
451
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
452
+ if (typeof value === 'string' && value.trim() !== '') {
453
+ const parsed = Number(value)
454
+ return Number.isFinite(parsed) ? parsed : undefined
455
+ }
456
+ return undefined
457
+ }
458
+
459
+ function asString(value: unknown): string | undefined {
460
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
461
+ }
462
+
463
+ /** Read the OAuth access token the CLI stored for one region. */
464
+ function readStoredToken(region: MinimaxRegion): string | undefined {
465
+ try {
466
+ const parsed = JSON.parse(readFileSync(minimaxAuthRecordPath(region), 'utf8')) as {
467
+ records?: Record<string, { accessToken?: unknown }>
468
+ }
469
+ for (const record of Object.values(parsed.records ?? {})) {
470
+ const token = record?.accessToken
471
+ if (typeof token === 'string' && token.trim().length > 0) return token.trim()
472
+ }
473
+ } catch {
474
+ // Missing or unreadable; the caller reports a re-login.
475
+ }
476
+ return undefined
477
+ }
478
+
479
+ function minimaxMd5(value: string): string {
480
+ return createHash('md5').update(value).digest('hex')
481
+ }
482
+
483
+ /** Build one signed-gateway URL exactly as the CLI does. */
484
+ function minimaxAccountUrl(
485
+ region: MinimaxRegion,
486
+ path: string,
487
+ nowMs: number,
488
+ realUserId?: string,
489
+ ): URL {
490
+ const url = new URL(path, MINIMAX_ACCOUNT_HOSTS[region])
491
+ const lang = region === 'cn' ? 'zh' : 'en'
492
+ url.search = new URLSearchParams({
493
+ device_platform: 'mcode',
494
+ biz_id: '3',
495
+ app_id: '3001',
496
+ version_code: '22201',
497
+ unix: String(nowMs),
498
+ timezone_offset: String(new Date().getTimezoneOffset() * -60),
499
+ sys_language: lang,
500
+ lang,
501
+ device_id: '0',
502
+ os_name: process.platform,
503
+ browser_name: 'mcode',
504
+ user_id: realUserId?.trim() || '0',
505
+ client: 'mcode',
506
+ }).toString()
507
+ return url
508
+ }
509
+
510
+ interface MinimaxAccountCall {
511
+ method?: 'GET' | 'POST'
512
+ body?: Record<string, unknown>
513
+ realUserId?: string
514
+ token: string
515
+ fetchImpl: typeof fetch
516
+ signal?: AbortSignal
517
+ }
518
+
519
+ /** One request to the signed gateway, with the CLI's signature headers. */
520
+ async function minimaxAccountCall(
521
+ region: MinimaxRegion,
522
+ path: string,
523
+ call: MinimaxAccountCall,
524
+ ): Promise<Record<string, unknown>> {
525
+ const now = Date.now()
526
+ const url = minimaxAccountUrl(region, path, now, call.realUserId)
527
+ const target = `${url.pathname}${url.search}`
528
+ const body = call.body === undefined ? '' : JSON.stringify(call.body)
529
+ const seconds = Math.floor(now / 1000)
530
+ const response = await call.fetchImpl(url, {
531
+ method: call.method ?? 'GET',
532
+ redirect: 'manual',
533
+ headers: {
534
+ Accept: 'application/json',
535
+ 'Content-Type': 'application/json',
536
+ 'User-Agent': 'MiniMaxCode',
537
+ Authorization: `Bearer ${call.token}`,
538
+ yy: minimaxMd5(`${encodeURIComponent(target)}_${body}${minimaxMd5(String(now))}ooui`),
539
+ 'x-timestamp': String(seconds),
540
+ 'x-signature': minimaxMd5(`${seconds}${MINIMAX_ACCOUNT_SALT}${body}`),
541
+ },
542
+ ...body === '' ? {} : { body },
543
+ ...call.signal === undefined ? {} : { signal: call.signal },
544
+ })
545
+ if (redirectTargetsOtherRegion(region, url, response)) {
546
+ rememberRegionAccess(region, true)
547
+ throw new MinimaxRegionBlockedError(region)
548
+ }
549
+ if (response.status >= 300 && response.status < 400) {
550
+ throw new Error(`MiniMax 账号接口返回了意外的重定向(HTTP ${response.status})。`)
551
+ }
552
+ if (!response.ok) {
553
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) {
554
+ throw new MinimaxRegionBlockedError(region)
555
+ }
556
+ throw new Error(response.status === 401 || response.status === 403
557
+ ? 'MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。'
558
+ : `MiniMax 账号接口返回 HTTP ${response.status}。`)
559
+ }
560
+ const payload = asRecord(await response.json())
561
+ if (payload === undefined) throw new Error('MiniMax 账号接口返回了无法解析的响应。')
562
+ const statusInfo = asRecord(payload.statusInfo)
563
+ const statusCode = asNumber(statusInfo?.code)
564
+ if (statusCode !== undefined && statusCode !== 0) {
565
+ throw new Error(asString(statusInfo?.message) ?? `MiniMax 账号接口错误 ${statusCode}。`)
566
+ }
567
+ const baseResp = asRecord(payload.base_resp)
568
+ const baseCode = asNumber(baseResp?.status_code)
569
+ if (baseCode !== undefined && baseCode !== 0) {
570
+ throw new Error(asString(baseResp?.status_msg) ?? `MiniMax 账号接口错误 ${baseCode}。`)
571
+ }
572
+ return payload
573
+ }
574
+
575
+ /**
576
+ * Literal characters in a prompt payload; images contribute pixels, not text.
577
+ *
578
+ * The per-turn input estimate must charge text only, exactly as the Qoder path
579
+ * counts a feed, so sending a picture cannot inflate the reported prompt size.
580
+ */
581
+ function feedTextLengthOf(prompt: string | readonly MinimaxPromptBlock[] | null): number {
582
+ if (prompt === null) return 0
583
+ if (typeof prompt === 'string') return prompt.length
584
+ return prompt.reduce((total, block) => total + (block.type === 'text' ? block.text.length : 0), 0)
585
+ }
586
+
587
+ /** One window's numbers, named the way the coding-plan endpoint reports them. */
588
+ function quotaWindow(
589
+ bucket: Record<string, unknown>,
590
+ kind: 'interval' | 'weekly',
591
+ ): Omit<MinimaxQuotaWindow, 'id' | 'label'> | undefined {
592
+ const prefix = kind === 'interval' ? 'current_interval' : 'current_weekly'
593
+ const status = asNumber(bucket[`${prefix}_status`])
594
+ const unlimited = status === 3
595
+ const percent = asNumber(bucket[`${prefix}_remaining_percent`])
596
+ const total = asNumber(bucket[`${prefix}_total_count`])
597
+ const used = asNumber(bucket[`${prefix}_usage_count`])
598
+ // The endpoint calls the count field `usage_count`, but the CLI reads it as
599
+ // the remaining amount; keep that interpretation so the card agrees with the
600
+ // TUI. A percentage, when present, always wins.
601
+ const remaining = percent ?? (total !== undefined && total > 0 && used !== undefined
602
+ ? (used / total) * 100
603
+ : undefined)
604
+ const resetAt = asNumber(bucket[kind === 'interval' ? 'end_time' : 'weekly_end_time'])
605
+ if (remaining === undefined && !unlimited && (resetAt === undefined || resetAt <= 0)) return undefined
606
+ return {
607
+ ...remaining === undefined || unlimited
608
+ ? {}
609
+ : { remainingPercent: Math.round(Math.min(100, Math.max(0, remaining))) },
610
+ ...resetAt !== undefined && resetAt > 0 ? { resetAt } : {},
611
+ unlimited,
612
+ ...kind === 'interval' && used !== undefined ? { remainingCount: Math.max(0, used) } : {},
613
+ ...kind === 'interval' && total !== undefined ? { totalCount: Math.max(0, total) } : {},
614
+ }
615
+ }
616
+
617
+ /** Turn one `model_remains` bucket into its 5-hour and weekly rows. */
618
+ function windowRows(
619
+ id: string,
620
+ label: string,
621
+ bucket: Record<string, unknown>,
622
+ ): MinimaxQuotaWindow[] {
623
+ const rows: MinimaxQuotaWindow[] = []
624
+ const interval = quotaWindow(bucket, 'interval')
625
+ if (interval !== undefined) rows.push({ id: `${id}:5h`, label: `${label} · 5 小时`, ...interval })
626
+ const weekly = quotaWindow(bucket, 'weekly')
627
+ if (weekly !== undefined) rows.push({ id: `${id}:7d`, label: `${label} · 本周`, ...weekly })
628
+ return rows
629
+ }
630
+
631
+ /** Parse `/v1/api/openplatform/coding_plan/remains`. */
632
+ function parseMinimaxRemains(payload: Record<string, unknown> | undefined): MinimaxQuotaWindow[] {
633
+ if (payload === undefined) return []
634
+ const baseResp = asRecord(payload.base_resp)
635
+ const code = asNumber(baseResp?.status_code)
636
+ // 2062 is "no active token plan", not an error worth showing.
637
+ if (code !== undefined && code !== 0) return []
638
+ const buckets = Array.isArray(payload.model_remains)
639
+ ? payload.model_remains
640
+ .map(asRecord)
641
+ .filter((bucket): bucket is Record<string, unknown> => bucket !== undefined)
642
+ : []
643
+ const rows: MinimaxQuotaWindow[] = []
644
+ const general = buckets[0]
645
+ if (general !== undefined) rows.push(...windowRows('general', '通用', general))
646
+ const video = buckets.find(bucket => {
647
+ const name = asString(bucket.model_name) ?? ''
648
+ return /video/i.test(name) && (asNumber(bucket.current_interval_total_count) ?? 0) > 0
649
+ })
650
+ if (video !== undefined) rows.push(...windowRows('video', '视频', video))
651
+ return rows
652
+ }
653
+
654
+ /**
655
+ * Build a snapshot from the three account documents.
656
+ *
657
+ * Split out from the network path so the mapping is testable without a live
658
+ * account: the membership record is the source of the plan and credit
659
+ * balance, `remains` only exists for token-plan subscribers.
660
+ */
661
+ export function minimaxUsageFromParts(parts: {
662
+ region: MinimaxRegion
663
+ at?: number
664
+ installed?: boolean
665
+ userInfo?: Record<string, unknown>
666
+ workspaces?: readonly Record<string, unknown>[]
667
+ membership?: Record<string, unknown>
668
+ remains?: Record<string, unknown>
669
+ }): MinimaxUsageSnapshot {
670
+ const userInfo = parts.userInfo ?? {}
671
+ const membership = parts.membership ?? {}
672
+ const personal = parts.workspaces?.find(workspace => asNumber(workspace.workspace_type) === 0)
673
+ ?? parts.workspaces?.[0]
674
+
675
+ const name = asString(userInfo.name)
676
+ const email = asString(userInfo.email)
677
+ const avatar = asString(userInfo.avatar)
678
+ const userId = asString(userInfo.userID)
679
+ const account = name === undefined && email === undefined && avatar === undefined && userId === undefined
680
+ ? undefined
681
+ : {
682
+ ...name === undefined ? {} : { name },
683
+ ...email === undefined ? {} : { email },
684
+ ...avatar === undefined ? {} : { avatar },
685
+ ...userId === undefined ? {} : { userId },
686
+ }
687
+
688
+ const summary = asRecord(membership.op_credit_summary) ?? asRecord(personal?.op_credit_summary)
689
+ const remaining = asNumber(summary?.total_remaining_amount)
690
+ ?? asNumber(personal?.opcredit_balance)
691
+ ?? asNumber(membership.opcredit_balance)
692
+ const purchased = asNumber(summary?.purchased_remaining_amount)
693
+ const free = asNumber(summary?.free_remaining_amount)
694
+ const credits = remaining === undefined
695
+ ? undefined
696
+ : {
697
+ remaining,
698
+ ...purchased === undefined ? {} : { purchasedRemaining: purchased },
699
+ ...free === undefined ? {} : { freeRemaining: free },
700
+ }
701
+
702
+ const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true
703
+ const kind = hasTokenPlan ? 'token-plan' : credits !== undefined && credits.remaining > 0 ? 'credits' : 'free'
704
+ const planName = asString(membership.plan_name) ?? asString(personal?.plan_name)
705
+ const tier = asString(membership.token_plan_tier) ?? asString(personal?.token_plan_tier)
706
+ const expiresRaw = asNumber(membership.token_plan_expires_at)
707
+ ?? asNumber(personal?.token_plan_expires_at)
708
+ ?? asNumber(membership.expires_at)
709
+ const expiresAt = expiresRaw !== undefined && expiresRaw > 0 ? expiresRaw : undefined
710
+ const subscriptionType = asString(membership.subscription_type)
711
+ const windows = parseMinimaxRemains(parts.remains)
712
+
713
+ return {
714
+ at: parts.at ?? Date.now(),
715
+ region: parts.region,
716
+ signedIn: true,
717
+ installed: parts.installed ?? true,
718
+ ...account === undefined ? {} : { account },
719
+ plan: {
720
+ kind,
721
+ hasTokenPlan,
722
+ ...planName === undefined ? {} : { name: planName },
723
+ ...tier === undefined ? {} : { tier },
724
+ ...expiresAt === undefined ? {} : { expiresAt },
725
+ ...subscriptionType === undefined ? {} : { subscriptionType },
726
+ },
727
+ ...credits === undefined ? {} : { credits },
728
+ ...windows.length === 0 ? {} : { windows },
729
+ }
730
+ }
731
+
732
+ /** Read the quota for a token-plan subscriber; a plain account has none. */
733
+ async function readMinimaxRemains(
734
+ region: MinimaxRegion,
735
+ token: string,
736
+ groupId: string,
737
+ fetchImpl: typeof fetch,
738
+ signal: AbortSignal,
739
+ ): Promise<Record<string, unknown> | undefined> {
740
+ const url = new URL('/v1/api/openplatform/coding_plan/remains', MINIMAX_QUOTA_HOSTS[region])
741
+ const response = await fetchImpl(url, {
742
+ redirect: 'manual',
743
+ headers: {
744
+ Accept: 'application/json',
745
+ Authorization: `Bearer ${token}`,
746
+ 'X-Group-Id': groupId,
747
+ },
748
+ signal,
749
+ })
750
+ if (redirectTargetsOtherRegion(region, url, response)) {
751
+ rememberRegionAccess(region, true)
752
+ throw new MinimaxRegionBlockedError(region)
753
+ }
754
+ if (response.status >= 300 && response.status < 400) return undefined
755
+ if (!response.ok) {
756
+ if ((response.status === 401 || response.status === 403) && minimaxRegionBlockedCached(region)) {
757
+ throw new MinimaxRegionBlockedError(region)
758
+ }
759
+ if (response.status === 401 || response.status === 403) {
760
+ throw new Error('MiniMax 登录已过期:先发一条消息让 CLI 自动续期,或重新登录后再刷新额度。')
761
+ }
762
+ return undefined
763
+ }
764
+ return asRecord(await response.json())
765
+ }
766
+
767
+ const usageCache = new Map<MinimaxRegion, { at: number, snapshot: MinimaxUsageSnapshot }>()
768
+ const usageInflight = new Map<MinimaxRegion, Promise<MinimaxUsageSnapshot>>()
769
+
770
+ /** Drop a cached quota reading, so the next request re-reads it. */
771
+ export function invalidateMinimaxUsage(region?: MinimaxRegion): void {
772
+ if (region === undefined) {
773
+ usageCache.clear()
774
+ return
775
+ }
776
+ usageCache.delete(region)
777
+ }
778
+
779
+ /**
780
+ * Read one region's account, plan and quota.
781
+ *
782
+ * A failed account call keeps the login state and reports the reason in
783
+ * `error`; the settings card shows the account it already knows with that
784
+ * message instead of silently claiming nothing is configured.
785
+ */
786
+ export async function minimaxUsage(
787
+ region: MinimaxRegion,
788
+ options: {
789
+ fresh?: boolean
790
+ token?: string
791
+ fetchImpl?: typeof fetch
792
+ signal?: AbortSignal
793
+ } = {},
794
+ ): Promise<MinimaxUsageSnapshot> {
795
+ const installed = resolveMinimaxCli() !== undefined
796
+ const token = options.token ?? readStoredToken(region)
797
+ const signedIn = token !== undefined || minimaxSignedIn(region)
798
+ if (!signedIn) {
799
+ return { at: Date.now(), region, signedIn: false, installed }
800
+ }
801
+ if (await minimaxRegionBlocked(region, {
802
+ fresh: options.fresh,
803
+ fetchImpl: options.fetchImpl,
804
+ signal: options.signal,
805
+ })) {
806
+ return {
807
+ at: Date.now(),
808
+ region,
809
+ signedIn: true,
810
+ installed,
811
+ regionBlocked: true,
812
+ error: minimaxRegionBlockMessage(region),
813
+ }
814
+ }
815
+ if (token === undefined) {
816
+ return {
817
+ at: Date.now(),
818
+ region,
819
+ signedIn: true,
820
+ installed,
821
+ error: '未找到 MiniMax 登录凭据,请重新登录。',
822
+ }
823
+ }
824
+ if (options.token === undefined && options.fresh !== true) {
825
+ const cached = usageCache.get(region)
826
+ if (cached !== undefined && Date.now() - cached.at < MINIMAX_USAGE_CACHE_TTL_MS) return cached.snapshot
827
+ }
828
+ let pending = usageInflight.get(region)
829
+ if (pending === undefined) {
830
+ pending = readUsage(region, token, installed, options)
831
+ .finally(() => { usageInflight.delete(region) })
832
+ usageInflight.set(region, pending)
833
+ }
834
+ const snapshot = await pending
835
+ if (snapshot.error === undefined && options.token === undefined) {
836
+ usageCache.set(region, { at: snapshot.at, snapshot })
837
+ }
838
+ return snapshot
839
+ }
840
+
841
+ async function readUsage(
842
+ region: MinimaxRegion,
843
+ token: string,
844
+ installed: boolean,
845
+ options: { fetchImpl?: typeof fetch, signal?: AbortSignal },
846
+ ): Promise<MinimaxUsageSnapshot> {
847
+ const timeout = AbortSignal.timeout(MINIMAX_USAGE_TIMEOUT_MS)
848
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
849
+ const fetchImpl = options.fetchImpl ?? fetch
850
+ try {
851
+ const info = await minimaxAccountCall(region, '/v1/api/user/info', { token, fetchImpl, signal })
852
+ const data = asRecord(info.data)
853
+ const userInfo = asRecord(data?.userInfo) ?? asRecord(info.userInfo) ?? {}
854
+ const realUserId = asString(userInfo.realUserID) ?? asString(userInfo.real_user_id)
855
+ const extra = await minimaxAccountCall(region, '/matrix/api/v1/user/get_user_extra_info', {
856
+ method: 'POST',
857
+ body: {},
858
+ realUserId,
859
+ token,
860
+ fetchImpl,
861
+ signal,
862
+ })
863
+ const rawWorkspaces = Array.isArray(extra.workspaces)
864
+ ? extra.workspaces
865
+ : Array.isArray(asRecord(extra.data)?.workspaces)
866
+ ? (asRecord(extra.data)?.workspaces as unknown[])
867
+ : []
868
+ const workspaces = rawWorkspaces
869
+ .map(asRecord)
870
+ .filter((workspace): workspace is Record<string, unknown> => workspace !== undefined)
871
+ const personal = workspaces.find(workspace => asNumber(workspace.workspace_type) === 0)
872
+ ?? workspaces[0]
873
+ const workspaceId = asNumber(personal?.workspace_id)
874
+ const membership = workspaceId === undefined
875
+ ? {}
876
+ : await minimaxAccountCall(region, '/matrix/api/v1/commerce/get_membership_info', {
877
+ method: 'POST',
878
+ body: { workspace_id: workspaceId },
879
+ realUserId,
880
+ token,
881
+ fetchImpl,
882
+ signal,
883
+ })
884
+ const groupId = asString(membership.op_group_id) ?? asString(personal?.op_group_id)
885
+ const hasTokenPlan = membership.has_token_plan === true || personal?.has_token_plan === true
886
+ const remains = hasTokenPlan && groupId !== undefined
887
+ ? await readMinimaxRemains(region, token, groupId, fetchImpl, signal)
888
+ : undefined
889
+ return minimaxUsageFromParts({ region, installed, userInfo, workspaces, membership, remains })
890
+ } catch (error) {
891
+ const blocked = error instanceof MinimaxRegionBlockedError
892
+ return {
893
+ at: Date.now(),
894
+ region,
895
+ signedIn: true,
896
+ installed,
897
+ ...blocked ? { regionBlocked: true } : {},
898
+ error: blocked
899
+ ? minimaxRegionBlockMessage(region)
900
+ : error instanceof Error ? error.message : String(error),
901
+ }
902
+ }
903
+ }
904
+
905
+ /** Trim CLI output to a short, token-free sentence. */
906
+ function outputTail(lines: readonly string[]): string {
907
+ return lines
908
+ .slice(-4)
909
+ .map(line => line.replace(/mmo(at|rt)_[A-Za-z0-9_-]+/g, 'mmo***'))
910
+ .join(' ')
911
+ .slice(0, 400)
912
+ }
913
+
914
+ /**
915
+ * Browser login/logout, one run per region.
916
+ *
917
+ * The CLI owns the OAuth device flow and the credential file. The plugin only
918
+ * starts the process, surfaces the authorization URL while it waits, and then
919
+ * re-reads the auth-state file to decide whether the region is signed in.
920
+ */
921
+ export class MinimaxAuth {
922
+ private readonly runs = new Map<MinimaxRegion, {
923
+ status: MinimaxAuthStatus
924
+ child: ChildProcess
925
+ lines: string[]
926
+ finish: (code: number | null) => void
927
+ }>()
928
+
929
+ status(region: MinimaxRegion): MinimaxAuthStatus {
930
+ const run = this.runs.get(region)
931
+ if (run !== undefined) return run.status
932
+ const state = readAuthState(region)
933
+ return {
934
+ running: false,
935
+ region,
936
+ signedIn: state?.status === 'authenticated',
937
+ ...state?.expiresAtMs === undefined ? {} : { expiresAt: state.expiresAtMs },
938
+ }
939
+ }
940
+
941
+ /** Start the CLI's browser login. */
942
+ start(region: MinimaxRegion, onFinish?: (ok: boolean) => void): { started: true } | { started: false, error: string } {
943
+ const existing = this.runs.get(region)
944
+ if (existing !== undefined && existing.status.running) {
945
+ return { started: false, error: '该区域正在登录,请先在浏览器中完成授权。' }
946
+ }
947
+ const spec = resolveMinimaxCli()
948
+ if (spec === undefined) {
949
+ return { started: false, error: '未安装 MiniMax Code CLI(mcode),请先安装后再登录。' }
950
+ }
951
+
952
+ const status: MinimaxAuthStatus = { running: true, region, signedIn: false, startedAt: Date.now() }
953
+ const run = {
954
+ status,
955
+ child: undefined as unknown as ChildProcess,
956
+ lines: [] as string[],
957
+ finish: (_code: number | null): void => {},
958
+ }
959
+ const env: NodeJS.ProcessEnv = { ...process.env, MAVIS_REGION: minimaxCliRegion(region) }
960
+ delete env.MAVIS_AGENT
961
+ delete env.MAVIS_SESSION
962
+ const child = spawn(spec.command, minimaxCliArgs(spec, ['login', '--region', region === 'cn' ? 'cn' : 'global']), {
963
+ cwd: homedir(),
964
+ env,
965
+ windowsHide: true,
966
+ stdio: ['ignore', 'pipe', 'pipe'],
967
+ })
968
+ run.child = child
969
+ this.runs.set(region, run)
970
+
971
+ const absorb = (chunk: Buffer): void => {
972
+ const text = String(chunk)
973
+ for (const line of text.split(/\r?\n/)) {
974
+ const trimmed = line.trim()
975
+ if (trimmed === '') continue
976
+ run.lines.push(trimmed)
977
+ const match = /^(?:Open:\s*)?(https?:\/\/\S+)/.exec(trimmed)
978
+ if (match !== null) status.url = match[1]
979
+ }
980
+ while (run.lines.length > 40) run.lines.shift()
981
+ }
982
+ child.stdout?.on('data', absorb)
983
+ child.stderr?.on('data', absorb)
984
+
985
+ const finish = (code: number | null): void => {
986
+ if (!status.running) return
987
+ status.running = false
988
+ status.finishedAt = Date.now()
989
+ const state = readAuthState(region)
990
+ status.signedIn = state?.status === 'authenticated'
991
+ if (state?.expiresAtMs !== undefined) status.expiresAt = state.expiresAtMs
992
+ // The CLI refuses to sign in to the second region while the other one is
993
+ // signed in. That failure must surface even though the target region's
994
+ // older credential file may still say `authenticated`.
995
+ if (code !== 0) status.error = outputTail(run.lines) || '登录未完成'
996
+ else if (!status.signedIn) status.error = outputTail(run.lines) || '登录未完成'
997
+ try {
998
+ onFinish?.(status.signedIn)
999
+ } catch {
1000
+ // The caller's callback must not break the status bookkeeping.
1001
+ }
1002
+ }
1003
+ run.finish = finish
1004
+ child.on('error', error => {
1005
+ status.error = `无法启动 mcode:${error.message}`
1006
+ finish(null)
1007
+ })
1008
+ child.on('close', code => { finish(code) })
1009
+ return { started: true }
1010
+ }
1011
+
1012
+ /** Sign one region out; the other region is untouched. */
1013
+ async logout(region: MinimaxRegion): Promise<MinimaxAuthStatus> {
1014
+ const spec = resolveMinimaxCli()
1015
+ if (spec === undefined) {
1016
+ return { running: false, region, signedIn: false, error: '未安装 MiniMax Code CLI(mcode)。' }
1017
+ }
1018
+ const env: NodeJS.ProcessEnv = { ...process.env, MAVIS_REGION: minimaxCliRegion(region) }
1019
+ delete env.MAVIS_AGENT
1020
+ delete env.MAVIS_SESSION
1021
+ const result = await new Promise<{ code: number | null, lines: string[] }>(resolve => {
1022
+ const lines: string[] = []
1023
+ const child = spawn(spec.command, minimaxCliArgs(spec, ['logout', '--region', region === 'cn' ? 'cn' : 'global']), {
1024
+ cwd: homedir(),
1025
+ env,
1026
+ windowsHide: true,
1027
+ stdio: ['ignore', 'pipe', 'pipe'],
1028
+ })
1029
+ const absorb = (chunk: Buffer): void => {
1030
+ for (const line of String(chunk).split(/\r?\n/)) {
1031
+ if (line.trim() !== '') lines.push(line.trim())
1032
+ }
1033
+ while (lines.length > 40) lines.shift()
1034
+ }
1035
+ child.stdout?.on('data', absorb)
1036
+ child.stderr?.on('data', absorb)
1037
+ const timer = setTimeout(() => {
1038
+ child.kill()
1039
+ resolve({ code: null, lines })
1040
+ }, 20_000)
1041
+ child.on('error', () => {
1042
+ clearTimeout(timer)
1043
+ resolve({ code: null, lines })
1044
+ })
1045
+ child.on('close', code => {
1046
+ clearTimeout(timer)
1047
+ resolve({ code, lines })
1048
+ })
1049
+ })
1050
+ this.runs.delete(region)
1051
+ const state = readAuthState(region)
1052
+ const signedIn = state?.status === 'authenticated'
1053
+ return {
1054
+ running: false,
1055
+ region,
1056
+ signedIn,
1057
+ ...state?.expiresAtMs === undefined ? {} : { expiresAt: state.expiresAtMs },
1058
+ ...result.code !== 0 ? { error: outputTail(result.lines) || '退出登录未完成' } : {},
1059
+ }
1060
+ }
1061
+
1062
+ /** Cancel any login process (plugin disposal). */
1063
+ stop(): void {
1064
+ for (const run of this.runs.values()) {
1065
+ if (run.status.running) run.child.kill()
1066
+ }
1067
+ }
1068
+ }
1069
+
1070
+ /** One event the ACP client or the MCP bridge delivers to a turn. */
1071
+ type SessionEvent =
1072
+ | { kind: 'text', text: string }
1073
+ | { kind: 'reasoning', text: string }
1074
+ | { kind: 'usage', used: number, size: number }
1075
+ | { kind: 'host-tool', callId: string, name: string, args: Record<string, unknown> }
1076
+ | { kind: 'native-tool', name: string }
1077
+ | { kind: 'prompt-done', stopReason: string }
1078
+ | { kind: 'prompt-error', error: Error }
1079
+ | { kind: 'closed', error: Error }
1080
+
1081
+ /** A single-consumer async event queue. */
1082
+ class EventQueue {
1083
+ private readonly items: SessionEvent[] = []
1084
+ private waiter: ((event: SessionEvent | undefined) => void) | null = null
1085
+ private closed = false
1086
+
1087
+ push(event: SessionEvent): void {
1088
+ if (this.closed) return
1089
+ if (this.waiter !== null) {
1090
+ const settle = this.waiter
1091
+ this.waiter = null
1092
+ settle(event)
1093
+ return
1094
+ }
1095
+ this.items.push(event)
1096
+ }
1097
+
1098
+ close(): void {
1099
+ if (this.closed) return
1100
+ this.closed = true
1101
+ if (this.waiter !== null) {
1102
+ const settle = this.waiter
1103
+ this.waiter = null
1104
+ settle(undefined)
1105
+ }
1106
+ }
1107
+
1108
+ get isClosed(): boolean {
1109
+ return this.closed
1110
+ }
1111
+
1112
+ next(): Promise<SessionEvent | undefined> {
1113
+ const item = this.items.shift()
1114
+ if (item !== undefined) return Promise.resolve(item)
1115
+ if (this.closed) return Promise.resolve(undefined)
1116
+ return new Promise<SessionEvent | undefined>(resolve => { this.waiter = resolve })
1117
+ }
1118
+ }
1119
+
1120
+ /** A pending host tool call, waiting for the harness to deliver its result. */
1121
+ interface PendingHostCall {
1122
+ resolve: (result: MinimaxMcpToolResult) => void
1123
+ reject: (error: Error) => void
1124
+ timer: NodeJS.Timeout
1125
+ }
1126
+
1127
+ /** Render a harness tool result for the MCP caller. */
1128
+ function renderToolResult(content: unknown): MinimaxMcpToolResult {
1129
+ const text = (value: unknown): string => {
1130
+ if (typeof value === 'string') return value
1131
+ if (value === null || value === undefined) return ''
1132
+ try {
1133
+ return JSON.stringify(value)
1134
+ } catch {
1135
+ return String(value)
1136
+ }
1137
+ }
1138
+ if (Array.isArray(content)) {
1139
+ const parts: string[] = []
1140
+ for (const block of content) {
1141
+ if (typeof block === 'string') {
1142
+ parts.push(block)
1143
+ continue
1144
+ }
1145
+ if (block !== null && typeof block === 'object' && (block as { type?: unknown }).type === 'text') {
1146
+ parts.push(text((block as { text?: unknown }).text))
1147
+ continue
1148
+ }
1149
+ parts.push(text(block))
1150
+ }
1151
+ const joined = parts.join('\n').trim()
1152
+ return { content: [{ type: 'text', text: joined === '' ? '(宿主工具没有返回内容)' : joined }] }
1153
+ }
1154
+ const joined = text(content).trim()
1155
+ return { content: [{ type: 'text', text: joined === '' ? '(宿主工具没有返回内容)' : joined }] }
1156
+ }
1157
+
1158
+ /** Options for one ACP process. */
1159
+ interface MinimaxAcpOptions {
1160
+ region: MinimaxRegion
1161
+ cwd: string
1162
+ systemPrompt: string
1163
+ /** HTTP MCP endpoint for host tools; absent for catalog/title calls. */
1164
+ mcpUrl?: string
1165
+ mcpToken?: string
1166
+ /** Disable all CLI tools (catalog and title reads need none). */
1167
+ disableTools?: boolean
1168
+ timeoutMs?: number
1169
+ onUpdate?: (update: SessionEvent) => void
1170
+ onExit?: (error: Error) => void
1171
+ onPermissionDenied?: (toolName: string) => void
1172
+ }
1173
+
1174
+ /**
1175
+ * One `mcode acp` process and its ACP session.
1176
+ *
1177
+ * The class only speaks protocol: model/effort config, prompts, cancellation,
1178
+ * and the translation of `session/update` into {@link SessionEvent}s. Turn
1179
+ * policy (tool calls, retries, harness chunks) lives in {@link MinimaxSession}.
1180
+ */
1181
+ export class MinimaxAcp {
1182
+ private child: ChildProcess | null = null
1183
+ private conn: ClientSideConnection | null = null
1184
+ private sessionId: string | undefined
1185
+ private configOptions: any[] = []
1186
+ private systemFile: string | undefined
1187
+ private tempDir: string | undefined
1188
+ private closing = false
1189
+ private stderr: string[] = []
1190
+ private readonly options: MinimaxAcpOptions
1191
+
1192
+ constructor(options: MinimaxAcpOptions) {
1193
+ this.options = options
1194
+ }
1195
+
1196
+ /** The model/effort options the CLI currently offers. */
1197
+ get optionsList(): readonly any[] {
1198
+ return this.configOptions
1199
+ }
1200
+
1201
+ /** The selected model config value. */
1202
+ get currentModel(): string | undefined {
1203
+ const option = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1204
+ return typeof option?.currentValue === 'string' ? option.currentValue : undefined
1205
+ }
1206
+
1207
+ /** Start the process and create one ACP session. */
1208
+ async start(): Promise<void> {
1209
+ const spec = resolveMinimaxCli()
1210
+ if (spec === undefined) {
1211
+ throw new Error('未安装 MiniMax Code CLI(mcode)。请在设置页安装,或运行 npm install -g @minimax-ai/code。')
1212
+ }
1213
+ const timeout = this.options.timeoutMs ?? MINIMAX_FETCH_TIMEOUT_MS
1214
+ const directory = mkdtempSync(join(tmpdir(), 'dsh-minimax-acp-'))
1215
+ const systemFile = join(directory, 'system.md')
1216
+ writeFileSync(systemFile, this.options.systemPrompt, 'utf8')
1217
+ this.systemFile = systemFile
1218
+ this.tempDir = directory
1219
+
1220
+ const env: NodeJS.ProcessEnv = {
1221
+ ...process.env,
1222
+ MAVIS_REGION: minimaxCliRegion(this.options.region),
1223
+ ...this.options.disableTools === true ? { MAVIS_LOCAL_RUNTIME_DISABLE_TOOLS: '1' } : {},
1224
+ }
1225
+ delete env.MAVIS_AGENT
1226
+ delete env.MAVIS_SESSION
1227
+ const child = spawn(
1228
+ spec.command,
1229
+ minimaxCliArgs(spec, ['acp', '--system-prompt-file', systemFile]),
1230
+ { cwd: this.options.cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] },
1231
+ )
1232
+ this.child = child
1233
+ child.stderr?.on('data', (chunk: Buffer) => {
1234
+ for (const line of String(chunk).split(/\r?\n/)) {
1235
+ if (line.trim() !== '') this.stderr.push(line.trim())
1236
+ }
1237
+ while (this.stderr.length > 30) this.stderr.shift()
1238
+ })
1239
+ child.on('exit', (code, signal) => {
1240
+ if (this.closing) return
1241
+ const detail = outputTail(this.stderr) || `mcode acp 退出(code=${String(code)}, signal=${String(signal)})`
1242
+ this.options.onExit?.(new Error(detail))
1243
+ })
1244
+ if (child.stdin === null || child.stdout === null) {
1245
+ throw new Error('mcode acp 没有可用的 stdio。')
1246
+ }
1247
+
1248
+ const client = {
1249
+ sessionUpdate: (params: { sessionId?: string, update?: any }): void => {
1250
+ if (params.sessionId !== undefined && this.sessionId !== undefined && params.sessionId !== this.sessionId) return
1251
+ const update = params.update
1252
+ if (update === null || typeof update !== 'object') return
1253
+ switch (update.sessionUpdate) {
1254
+ case 'agent_message_chunk': {
1255
+ const text = typeof update.content?.text === 'string' ? update.content.text : ''
1256
+ if (text.length > 0) this.options.onUpdate?.({ kind: 'text', text })
1257
+ return
1258
+ }
1259
+ case 'agent_thought_chunk': {
1260
+ const text = typeof update.content?.text === 'string' ? update.content.text : ''
1261
+ if (text.length > 0) this.options.onUpdate?.({ kind: 'reasoning', text })
1262
+ return
1263
+ }
1264
+ case 'usage_update': {
1265
+ const used = typeof update.used === 'number' ? update.used : 0
1266
+ const size = typeof update.size === 'number' ? update.size : 0
1267
+ if (size > 0) this.options.onUpdate?.({ kind: 'usage', used, size })
1268
+ return
1269
+ }
1270
+ case 'tool_call':
1271
+ case 'tool_call_update': {
1272
+ const name = typeof update.title === 'string' && update.title.length > 0
1273
+ ? update.title
1274
+ : typeof update.name === 'string' ? update.name : ''
1275
+ if (name.length === 0) return
1276
+ if (!isHostMcpTool(name)) {
1277
+ // Built-in tool: the session cancels the prompt before it runs.
1278
+ if (update.sessionUpdate === 'tool_call' || update.status === 'in_progress') {
1279
+ this.options.onUpdate?.({ kind: 'native-tool', name })
1280
+ }
1281
+ return
1282
+ }
1283
+ return
1284
+ }
1285
+ default:
1286
+ return
1287
+ }
1288
+ },
1289
+ requestPermission: async (params: any): Promise<any> => {
1290
+ const name = typeof params?.toolCall?.title === 'string' && params.toolCall.title.length > 0
1291
+ ? params.toolCall.title
1292
+ : typeof params?.toolCall?.name === 'string' ? params.toolCall.name : ''
1293
+ const options = Array.isArray(params?.options) ? params.options : []
1294
+ if (isHostMcpTool(name)) {
1295
+ const allow = options.find((entry: any) => entry?.kind === 'allow_once')
1296
+ ?? options.find((entry: any) => entry?.kind === 'allow_always')
1297
+ ?? options[0]
1298
+ if (allow !== undefined) return { outcome: { outcome: 'selected', optionId: allow.optionId } }
1299
+ return { outcome: { outcome: 'cancelled' } }
1300
+ }
1301
+ this.options.onPermissionDenied?.(name)
1302
+ const deny = options.find((entry: any) => entry?.kind === 'reject_once')
1303
+ ?? options.find((entry: any) => entry?.kind === 'reject_always')
1304
+ return deny === undefined
1305
+ ? { outcome: { outcome: 'cancelled' } }
1306
+ : { outcome: { outcome: 'selected', optionId: deny.optionId } }
1307
+ },
1308
+ }
1309
+
1310
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout))
1311
+ const conn = new ClientSideConnection(() => client as any, stream)
1312
+ this.conn = conn
1313
+
1314
+ const init = await withTimeout(conn.initialize({
1315
+ protocolVersion: PROTOCOL_VERSION,
1316
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
1317
+ clientInfo: { name: 'dsh-agent-sdk-bridge', version: '1.1.0' },
1318
+ }), timeout, 'mcode acp initialize')
1319
+ void init
1320
+
1321
+ const mcpServers = this.options.mcpUrl === undefined
1322
+ ? []
1323
+ : [{
1324
+ type: 'http',
1325
+ name: MINIMAX_MCP_SERVER,
1326
+ url: this.options.mcpUrl,
1327
+ headers: [{ name: 'Authorization', value: `Bearer ${this.options.mcpToken ?? ''}` }],
1328
+ }]
1329
+ const session = await withTimeout(conn.newSession({
1330
+ cwd: this.options.cwd,
1331
+ mcpServers: mcpServers as any,
1332
+ }), timeout, 'mcode acp session/new')
1333
+ this.sessionId = session.sessionId
1334
+ this.configOptions = Array.isArray(session.configOptions) ? [...session.configOptions] : []
1335
+ }
1336
+
1337
+ /**
1338
+ * Run one prompt; resolves when the agent's turn ends.
1339
+ *
1340
+ * ACP carries images as `{ type: 'image', data, mimeType }` blocks next to
1341
+ * text, which is what makes a pasted picture reach the model at all; a plain
1342
+ * string keeps the historical text-only shape.
1343
+ */
1344
+ async prompt(prompt: string | readonly MinimaxPromptBlock[]): Promise<{ stopReason: string }> {
1345
+ if (this.conn === null || this.sessionId === undefined) throw new Error('ACP 会话尚未启动。')
1346
+ const blocks: MinimaxPromptBlock[] = typeof prompt === 'string'
1347
+ ? [{ type: 'text', text: prompt }]
1348
+ : [...prompt]
1349
+ const response = await this.conn.prompt({
1350
+ sessionId: this.sessionId,
1351
+ prompt: blocks,
1352
+ } as any)
1353
+ return { stopReason: String(response.stopReason) }
1354
+ }
1355
+
1356
+ /** Ask the agent to stop the active turn. */
1357
+ async cancel(): Promise<void> {
1358
+ if (this.conn === null || this.sessionId === undefined) return
1359
+ try {
1360
+ await this.conn.cancel({ sessionId: this.sessionId })
1361
+ } catch {
1362
+ // A turn that already ended has nothing to cancel.
1363
+ }
1364
+ }
1365
+
1366
+ /** Set a session config option and remember the updated list. */
1367
+ async setConfig(id: string, value: string): Promise<void> {
1368
+ if (this.conn === null || this.sessionId === undefined) return
1369
+ const option = this.configOptions.find(entry => entry?.id === id)
1370
+ if (option === undefined) return
1371
+ if (option.currentValue === value) return
1372
+ const allowed = Array.isArray(option.options)
1373
+ ? option.options.some((entry: any) => entry?.value === value)
1374
+ : true
1375
+ if (!allowed) return
1376
+ const response = await this.conn.setSessionConfigOption({
1377
+ sessionId: this.sessionId,
1378
+ configId: id,
1379
+ value,
1380
+ } as any)
1381
+ if (Array.isArray(response.configOptions)) this.configOptions = [...response.configOptions]
1382
+ }
1383
+
1384
+ /**
1385
+ * List the models the CLI actually accepts, with each model's own efforts.
1386
+ *
1387
+ * The advertised option list can contain values the agent rejects (0.6.12
1388
+ * lists a `M3.1-Flash` non-thinking value and answers `Invalid model
1389
+ * reasoning` when it is selected). Selecting each value once is the only
1390
+ * reliable filter, and it also reveals that non-thinking models drop the
1391
+ * `thinkingEffort` option entirely, so reasoning has to be reported per
1392
+ * model rather than once for the catalog.
1393
+ */
1394
+ async probeModels(): Promise<MinimaxModel[]> {
1395
+ const modelOption = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1396
+ if (!Array.isArray(modelOption?.options)) return []
1397
+ const initial = typeof modelOption.currentValue === 'string' ? modelOption.currentValue : undefined
1398
+ const seen = new Set<string>()
1399
+ const models: MinimaxModel[] = []
1400
+ for (const entry of modelOption.options) {
1401
+ if (typeof entry?.value !== 'string' || entry.value.length === 0 || seen.has(entry.value)) continue
1402
+ seen.add(entry.value)
1403
+ try {
1404
+ await this.setConfig(String(modelOption.id), entry.value)
1405
+ } catch {
1406
+ continue
1407
+ }
1408
+ const effortOption = this.configOptions.find(option => option?.id === 'thinkingEffort' || option?.category === 'thought_level')
1409
+ const row = modelRow(entry, effortValues(effortOption?.options))
1410
+ if (row !== undefined) models.push(row)
1411
+ }
1412
+ if (initial !== undefined && this.currentModel !== initial) {
1413
+ try {
1414
+ await this.setConfig(String(modelOption.id), initial)
1415
+ } catch {
1416
+ // The restore is best effort; the caller never prompts this session.
1417
+ }
1418
+ }
1419
+ return models
1420
+ }
1421
+
1422
+ /** Select the model (and, when supported, the thinking effort). */
1423
+ async selectModel(model: string, effort?: string): Promise<void> {
1424
+ const modelOption = this.configOptions.find(entry => entry?.category === 'model' || entry?.id === 'model')
1425
+ if (modelOption !== undefined) {
1426
+ const values = Array.isArray(modelOption.options)
1427
+ ? modelOption.options.map((entry: any) => entry?.value)
1428
+ : []
1429
+ if (values.includes(model)) await this.setConfig(String(modelOption.id), model)
1430
+ }
1431
+ if (effort !== undefined && effort.length > 0 && effort !== 'default') {
1432
+ const effortOption = this.configOptions.find(entry => entry?.id === 'thinkingEffort' || entry?.category === 'thought_level')
1433
+ if (effortOption !== undefined) {
1434
+ try {
1435
+ await this.setConfig(String(effortOption.id), effort)
1436
+ } catch {
1437
+ // A model that no longer advertises this effort still accepts the
1438
+ // turn with its own default; failing here would lose the request.
1439
+ }
1440
+ }
1441
+ }
1442
+ }
1443
+
1444
+ /** Exit the session and reap the process. */
1445
+ async close(): Promise<void> {
1446
+ if (this.closing) return
1447
+ this.closing = true
1448
+ const conn = this.conn
1449
+ const sessionId = this.sessionId
1450
+ this.conn = null
1451
+ this.sessionId = undefined
1452
+ if (conn !== null && sessionId !== undefined) {
1453
+ await withTimeout(conn.closeSession({ sessionId } as any), 3_000, 'mcode acp session/close').catch(() => undefined)
1454
+ }
1455
+ this.child?.kill()
1456
+ this.child = null
1457
+ if (this.tempDir !== undefined) {
1458
+ try {
1459
+ rmSync(this.tempDir, { recursive: true, force: true })
1460
+ } catch {
1461
+ // The temp directory may already be gone.
1462
+ }
1463
+ this.tempDir = undefined
1464
+ }
1465
+ this.systemFile = undefined
1466
+ }
1467
+ }
1468
+
1469
+ /** A one-shot ACP process used by the catalog and title side channels. */
1470
+ async function withAcp<T>(
1471
+ region: MinimaxRegion,
1472
+ timeoutMs: number,
1473
+ run: (acp: MinimaxAcp) => Promise<T>,
1474
+ options: { systemPrompt?: string, disableTools?: boolean } = {},
1475
+ ): Promise<T> {
1476
+ const cwd = mkdtempSync(join(tmpdir(), 'dsh-minimax-side-'))
1477
+ const acp = new MinimaxAcp({
1478
+ region,
1479
+ cwd,
1480
+ systemPrompt: options.systemPrompt ?? 'You are a helper. Do not use tools.',
1481
+ disableTools: options.disableTools ?? true,
1482
+ timeoutMs,
1483
+ })
1484
+ try {
1485
+ await acp.start()
1486
+ return await run(acp)
1487
+ } finally {
1488
+ await acp.close()
1489
+ try {
1490
+ rmSync(cwd, { recursive: true, force: true })
1491
+ } catch {
1492
+ // Best effort.
1493
+ }
1494
+ }
1495
+ }
1496
+
1497
+ /** Read the model list for one region (cached). */
1498
+ export class MinimaxCatalog {
1499
+ private readonly snapshots = new Map<MinimaxRegion, { at: number, models: readonly MinimaxModel[] }>()
1500
+ private readonly inflight = new Map<MinimaxRegion, Promise<readonly MinimaxModel[]>>()
1501
+ private readonly failures = new Map<MinimaxRegion, string>()
1502
+
1503
+ constructor(
1504
+ private readonly region: Live<MinimaxRegion>,
1505
+ private readonly ttlMs: Live<number> = MINIMAX_CACHE_TTL_MS,
1506
+ private readonly timeoutMs: Live<number> = MINIMAX_FETCH_TIMEOUT_MS,
1507
+ ) {}
1508
+
1509
+ /** Models for one region; a failed refresh keeps the last good list. */
1510
+ async models(requested?: MinimaxRegion): Promise<readonly MinimaxModel[]> {
1511
+ const region = requested ?? readLive(this.region, 'cn')
1512
+ if (await minimaxRegionBlocked(region)) {
1513
+ this.invalidate(region)
1514
+ return []
1515
+ }
1516
+ const ttl = readLive(this.ttlMs, MINIMAX_CACHE_TTL_MS)
1517
+ const cached = this.snapshots.get(region)
1518
+ if (cached !== undefined && Date.now() - cached.at < ttl) return cached.models
1519
+ let pending = this.inflight.get(region)
1520
+ if (pending === undefined) {
1521
+ pending = this.fetch(region).finally(() => { this.inflight.delete(region) })
1522
+ this.inflight.set(region, pending)
1523
+ }
1524
+ try {
1525
+ const models = await pending
1526
+ this.snapshots.set(region, { at: Date.now(), models })
1527
+ this.failures.delete(region)
1528
+ return models
1529
+ } catch (error) {
1530
+ this.failures.set(region, error instanceof Error ? error.message : String(error))
1531
+ return cached?.models ?? []
1532
+ }
1533
+ }
1534
+
1535
+ /**
1536
+ * The last successful list for a region, without probing.
1537
+ *
1538
+ * The picker resolves a route on every switch; awaiting an ACP probe there
1539
+ * cost a process round-trip whenever the TTL had just expired.
1540
+ */
1541
+ snapshot(requested?: MinimaxRegion): readonly MinimaxModel[] | undefined {
1542
+ return this.snapshots.get(requested ?? readLive(this.region, 'cn'))?.models
1543
+ }
1544
+
1545
+ /** Why the last refresh failed, or undefined when it succeeded. */
1546
+ error(requested?: MinimaxRegion): string | undefined {
1547
+ return this.failures.get(requested ?? readLive(this.region, 'cn'))
1548
+ }
1549
+
1550
+ invalidate(region?: MinimaxRegion): void {
1551
+ if (region === undefined) {
1552
+ this.snapshots.clear()
1553
+ this.failures.clear()
1554
+ return
1555
+ }
1556
+ this.snapshots.delete(region)
1557
+ this.failures.delete(region)
1558
+ }
1559
+
1560
+ private async fetch(region: MinimaxRegion): Promise<readonly MinimaxModel[]> {
1561
+ if (!minimaxSignedIn(region)) {
1562
+ throw new Error(`${region === 'cn' ? 'MiniMax 国内站' : 'MiniMax 国际站'}尚未登录,请先在设置页登录。`)
1563
+ }
1564
+ if (await minimaxRegionBlocked(region)) {
1565
+ throw new MinimaxRegionBlockedError(region)
1566
+ }
1567
+ const timeout = readLive(this.timeoutMs, MINIMAX_FETCH_TIMEOUT_MS)
1568
+ return await withAcp(region, timeout, async acp => acp.probeModels(), {
1569
+ systemPrompt: 'You are a helper used only to list models. Do not call any tool.',
1570
+ disableTools: true,
1571
+ })
1572
+ }
1573
+ }
1574
+
1575
+ /** One shared HTTP MCP server for every warm MiniMax session. */
1576
+ export class MinimaxMcpServer {
1577
+ private server: Server | undefined
1578
+ private port = 0
1579
+ private readonly bridges = new Map<string, MinimaxMcpBridge>()
1580
+
1581
+ /** The base URL, or undefined before {@link start}. */
1582
+ get baseUrl(): string | undefined {
1583
+ return this.server === undefined ? undefined : `http://127.0.0.1:${this.port}`
1584
+ }
1585
+
1586
+ /** Bind to an ephemeral loopback port. */
1587
+ async start(): Promise<void> {
1588
+ if (this.server !== undefined) return
1589
+ const server = createServer((req, res) => { void this.handle(req, res) })
1590
+ await new Promise<void>((resolve, reject) => {
1591
+ server.once('error', reject)
1592
+ server.listen(0, '127.0.0.1', () => resolve())
1593
+ })
1594
+ const address = server.address()
1595
+ if (address === null || typeof address === 'string') {
1596
+ server.close()
1597
+ throw new Error('无法为 MiniMax 宿主工具分配本地端口。')
1598
+ }
1599
+ this.port = address.port
1600
+ this.server = server
1601
+ }
1602
+
1603
+ /** Add one session's bridge under a random token. */
1604
+ register(bridge: MinimaxMcpBridge): { url: string, token: string } {
1605
+ if (this.server === undefined) throw new Error('MiniMax MCP server 尚未启动。')
1606
+ const token = randomBytes(24).toString('hex')
1607
+ this.bridges.set(token, bridge)
1608
+ return { url: `${this.baseUrl}/mcp/${token}`, token }
1609
+ }
1610
+
1611
+ unregister(token: string): void {
1612
+ this.bridges.delete(token)
1613
+ }
1614
+
1615
+ /** Close the server and release every session. */
1616
+ close(): void {
1617
+ this.bridges.clear()
1618
+ this.server?.close()
1619
+ this.server = undefined
1620
+ }
1621
+
1622
+ private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
1623
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
1624
+ const match = /^\/mcp\/([a-f0-9]+)$/.exec(url.pathname)
1625
+ const bridge = match === null ? undefined : this.bridges.get(match[1])
1626
+ if (bridge === undefined) {
1627
+ res.writeHead(404, { 'content-type': 'application/json' }).end('{"error":"unknown MCP session"}')
1628
+ return
1629
+ }
1630
+ if (req.method === 'GET') {
1631
+ res.writeHead(405).end()
1632
+ return
1633
+ }
1634
+ if (req.method === 'DELETE') {
1635
+ res.writeHead(200).end()
1636
+ return
1637
+ }
1638
+ if (req.method !== 'POST') {
1639
+ res.writeHead(405).end()
1640
+ return
1641
+ }
1642
+ // The path token is unguessable, and the bearer header is required on top
1643
+ // of it so a local process cannot reuse a URL it saw in a log.
1644
+ if (req.headers.authorization !== `Bearer ${match?.[1] ?? ''}`) {
1645
+ res.writeHead(403).end()
1646
+ return
1647
+ }
1648
+ let raw = ''
1649
+ for await (const chunk of req) {
1650
+ raw += chunk
1651
+ if (raw.length > 8 * 1024 * 1024) {
1652
+ res.writeHead(413).end()
1653
+ return
1654
+ }
1655
+ }
1656
+ let message: any
1657
+ try {
1658
+ message = JSON.parse(raw)
1659
+ } catch {
1660
+ res.writeHead(400).end()
1661
+ return
1662
+ }
1663
+ const id = message?.id
1664
+ const reply = (payload: unknown): void => {
1665
+ const body = JSON.stringify(payload)
1666
+ res.writeHead(200, {
1667
+ 'content-type': 'application/json',
1668
+ 'mcp-session-id': match?.[1] ?? 'dsh-host',
1669
+ }).end(body)
1670
+ }
1671
+ if (message?.method === undefined) {
1672
+ res.writeHead(202).end()
1673
+ return
1674
+ }
1675
+ if (id === undefined) {
1676
+ // Notifications, including notifications/initialized.
1677
+ res.writeHead(202).end()
1678
+ return
1679
+ }
1680
+ try {
1681
+ switch (message.method) {
1682
+ case 'initialize':
1683
+ reply({
1684
+ jsonrpc: '2.0',
1685
+ id,
1686
+ result: {
1687
+ protocolVersion: message.params?.protocolVersion ?? '2025-06-18',
1688
+ capabilities: { tools: {} },
1689
+ serverInfo: { name: MINIMAX_MCP_SERVER, version: '1.0.0' },
1690
+ },
1691
+ })
1692
+ return
1693
+ case 'ping':
1694
+ reply({ jsonrpc: '2.0', id, result: {} })
1695
+ return
1696
+ case 'tools/list':
1697
+ reply({ jsonrpc: '2.0', id, result: { tools: bridge.tools() } })
1698
+ return
1699
+ case 'tools/call': {
1700
+ const name = typeof message.params?.name === 'string' ? message.params.name : ''
1701
+ const args = message.params?.arguments !== null && typeof message.params?.arguments === 'object'
1702
+ ? message.params.arguments as Record<string, unknown>
1703
+ : {}
1704
+ const result = await bridge.call(name, args)
1705
+ reply({ jsonrpc: '2.0', id, result })
1706
+ return
1707
+ }
1708
+ default:
1709
+ reply({ jsonrpc: '2.0', id, error: { code: -32601, message: `Unknown method ${String(message.method)}` } })
1710
+ return
1711
+ }
1712
+ } catch (error) {
1713
+ reply({
1714
+ jsonrpc: '2.0',
1715
+ id,
1716
+ result: {
1717
+ content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
1718
+ isError: true,
1719
+ },
1720
+ })
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ /** One session's view of the MCP server. */
1726
+ export class MinimaxMcpBridge {
1727
+ private schemas: readonly { name: string, description: string, parameters?: unknown }[] = []
1728
+
1729
+ constructor(
1730
+ private readonly callHost: (name: string, args: Record<string, unknown>) => Promise<MinimaxMcpToolResult>,
1731
+ ) {}
1732
+
1733
+ setTools(tools: readonly { name: string, description: string, parameters?: unknown }[]): void {
1734
+ this.schemas = tools
1735
+ }
1736
+
1737
+ tools(): { name: string, description: string, inputSchema: Record<string, unknown> }[] {
1738
+ return this.schemas.map(schema => ({
1739
+ name: schema.name,
1740
+ description: schema.description.length > 0 ? schema.description : schema.name,
1741
+ inputSchema: schema.parameters !== null && typeof schema.parameters === 'object'
1742
+ ? schema.parameters as Record<string, unknown>
1743
+ : { type: 'object', properties: {} },
1744
+ }))
1745
+ }
1746
+
1747
+ async call(name: string, args: Record<string, unknown>): Promise<MinimaxMcpToolResult> {
1748
+ if (!this.schemas.some(schema => schema.name === name)) {
1749
+ return { content: [{ type: 'text', text: `未知工具:${name}` }], isError: true }
1750
+ }
1751
+ return await this.callHost(name, args)
1752
+ }
1753
+ }
1754
+
1755
+ /** The result of one warm session's turn. */
1756
+ interface TurnState {
1757
+ textBlock?: { index: number, text: string }
1758
+ reasoningBlock?: { index: number, text: string }
1759
+ blockIndex: number
1760
+ inputChars: number
1761
+ outputChars: number
1762
+ reasoningChars: number
1763
+ /** Context occupancy the agent reported, the best input-count signal. */
1764
+ contextUsed?: number
1765
+ }
1766
+
1767
+ /**
1768
+ * Round one token count up to a whole number.
1769
+ *
1770
+ * The harness validates every usage bucket as `number().int().nonnegative()`.
1771
+ * The text estimator prices by script and therefore returns fractions; a
1772
+ * fractional reading is accepted when it streams but makes the durable usage
1773
+ * projection fail, and the conversation then refuses to load at all (the
1774
+ * "failed to project session" error). Counts must leave this module whole.
1775
+ */
1776
+ function wholeTokens(value: number): number {
1777
+ return Math.max(1, Math.ceil(value))
1778
+ }
1779
+
1780
+ /** Build a turn's usage from its character counts and the reported context. */
1781
+ export function minimaxTurnUsage(counts: {
1782
+ contextUsed?: number
1783
+ inputChars: number
1784
+ outputChars: number
1785
+ reasoningChars: number
1786
+ }): TokenUsage {
1787
+ const inputTokens = wholeTokens(counts.contextUsed ?? estimateTextTokens(counts.inputChars, 0))
1788
+ const outputTokens = wholeTokens(estimateTextTokens(counts.outputChars + counts.reasoningChars, 0))
1789
+ const reasoningTokens = counts.reasoningChars === 0
1790
+ ? undefined
1791
+ : Math.min(outputTokens, wholeTokens(estimateTextTokens(counts.reasoningChars, 0)))
1792
+ return {
1793
+ inputTokens,
1794
+ outputTokens,
1795
+ ...reasoningTokens === undefined ? {} : { reasoningTokens },
1796
+ cacheReadTokens: 0,
1797
+ cacheWriteTokens: 0,
1798
+ totalTokens: inputTokens + outputTokens,
1799
+ }
1800
+ }
1801
+
1802
+ /** A prompt that asks the model to retry without native tools. */
1803
+ const NATIVE_TOOL_CORRECTION = [
1804
+ 'SYSTEM NOTICE (not from the user):',
1805
+ 'The built-in tools (bash, read, write, edit, glob, grep, web_fetch, task, and every other native tool)',
1806
+ 'are disabled in this deployment. Any call to them is cancelled before execution.',
1807
+ 'The only valid tools are the host MCP tools whose names begin with mcp__dsh-host__.',
1808
+ 'Re-answer the user\'s last request using only those host tools. Do not mention this notice.',
1809
+ ].join('\n')
1810
+
1811
+ /** The tool policy appended to the host system prompt. */
1812
+ const HOST_TOOL_POLICY = [
1813
+ '## Host tool protocol',
1814
+ 'You are the model backend of DeepSeek Harness.',
1815
+ 'The ONLY tools you may call are the host MCP tools exposed by the `dsh-host` MCP server;',
1816
+ 'their names begin with `mcp__dsh-host__`. The built-in tools (bash, read, write, edit, glob,',
1817
+ 'grep, web_fetch, task, and every other native tool) are disabled in this deployment: calling',
1818
+ 'one aborts the turn before execution. Never mention this rule to the user.',
1819
+ ].join('\n')
1820
+
1821
+ /**
1822
+ * One warm MiniMax conversation for a harness session id.
1823
+ *
1824
+ * The ACP agent owns the history. A turn ends either when the prompt finishes
1825
+ * or when a host tool call is handed to the harness; in the latter case the
1826
+ * ACP prompt stays open until the harness returns the result on its next
1827
+ * request, exactly like the CodeBuddy bridge.
1828
+ */
1829
+ export class MinimaxSession {
1830
+ private acp: MinimaxAcp | null = null
1831
+ private readonly events = new EventQueue()
1832
+ private readonly bridge: MinimaxMcpBridge
1833
+ private readonly pending = new Map<string, PendingHostCall>()
1834
+ private readonly toolResultTimeoutMs: number
1835
+ private readonly abortGraceMs: number
1836
+ private readonly callNonce = randomUUID().slice(0, 8)
1837
+ private toolCounter = 0
1838
+ private promptInFlight = false
1839
+ private activeTurn = false
1840
+ private disposed = false
1841
+ private region: MinimaxRegion = 'cn'
1842
+ private model = ''
1843
+ private effort: string | undefined
1844
+ private systemPrompt = ''
1845
+ private workspace: string | undefined
1846
+ /** The harness workspace; absent means the session owns a temp directory. */
1847
+ private requestedCwd: string | undefined
1848
+ private ownsWorkspace = false
1849
+ private mcpToken: string | undefined
1850
+ private toolSchemas: readonly { name: string, description: string, parameters?: unknown }[] = []
1851
+ private nativeViolation = false
1852
+ private cancelSent = false
1853
+ private correctionCount = 0
1854
+ private observedContextWindow: number | undefined
1855
+ /** Was the last turn closed with tool-calls, leaving the ACP prompt open? */
1856
+ private awaitingToolResults = false
1857
+ /** Host messages already fed to the ACP session, for continuation planning. */
1858
+ fedMessages: readonly RequestMessage[] | undefined
1859
+ /** Host system prompt last applied; informational for the adapter. */
1860
+ fedSystem: string | undefined
1861
+
1862
+ constructor(
1863
+ readonly sessionId: string,
1864
+ initialModel: string,
1865
+ private readonly mcpServer: MinimaxMcpServer,
1866
+ runtime: { toolResultTimeoutMs?: Live<number>, abortGraceMs?: Live<number> } = {},
1867
+ ) {
1868
+ this.model = initialModel
1869
+ this.toolResultTimeoutMs = readLive(runtime.toolResultTimeoutMs, 120_000)
1870
+ this.abortGraceMs = readLive(runtime.abortGraceMs, 5_000)
1871
+ this.bridge = new MinimaxMcpBridge((name, args) => this.handleToolCall(name, args))
1872
+ }
1873
+
1874
+ /** Model context window observed from a real turn, when one was reported. */
1875
+ get contextWindow(): number | undefined {
1876
+ return this.observedContextWindow
1877
+ }
1878
+
1879
+ /**
1880
+ * Whether the ACP session still owns an unfinished turn.
1881
+ *
1882
+ * A turn closed with `tool-calls` keeps its prompt open while the host runs
1883
+ * the tools, so this stays true between the two host requests. A brand-new
1884
+ * user message in that state cannot be injected; the adapter rebuilds the
1885
+ * session and feeds the whole history instead.
1886
+ */
1887
+ get busy(): boolean {
1888
+ return this.promptInFlight || this.activeTurn
1889
+ }
1890
+
1891
+ /**
1892
+ * Point the session at a region, model and system prompt.
1893
+ *
1894
+ * @returns true when the warm ACP process was dropped, which means the
1895
+ * conversation state must be rebuilt from the durable history.
1896
+ */
1897
+ configure(
1898
+ region: MinimaxRegion,
1899
+ model: string,
1900
+ options: { effort?: string, system?: string, cwd?: string } = {},
1901
+ ): boolean {
1902
+ const nextSystem = options.system ?? ''
1903
+ const nextCwd = options.cwd
1904
+ let reset = false
1905
+ if (this.acp !== null && (
1906
+ nextSystem !== this.systemPrompt
1907
+ || region !== this.region
1908
+ || nextCwd !== this.requestedCwd
1909
+ )) {
1910
+ // systemPrompt and cwd are fixed when the ACP process starts. Drop the
1911
+ // warm session so the adapter's next turn rebuilds it.
1912
+ void this.dropAcp()
1913
+ this.fedMessages = undefined
1914
+ reset = true
1915
+ }
1916
+ this.region = region
1917
+ this.model = model
1918
+ this.effort = options.effort
1919
+ this.systemPrompt = nextSystem
1920
+ this.requestedCwd = nextCwd
1921
+ return reset
1922
+ }
1923
+
1924
+ /** Register the host tools this session's MCP server advertises. */
1925
+ ensureTools(tools: readonly { name: string, description: string, parameters?: unknown }[]): void {
1926
+ this.toolSchemas = tools
1927
+ this.bridge.setTools(tools)
1928
+ }
1929
+
1930
+ /** Hand the host's tool results to parked handlers. */
1931
+ deliverToolResults(tail: readonly { role: string, toolCallId?: unknown, content?: unknown, isError?: boolean }[]): void {
1932
+ let freshUserTurn = false
1933
+ for (const message of tail) {
1934
+ if (message.role === 'user') {
1935
+ freshUserTurn = true
1936
+ continue
1937
+ }
1938
+ if (message.role !== 'tool') continue
1939
+ const callId = message.toolCallId === undefined ? '' : String(message.toolCallId)
1940
+ const pending = this.pending.get(callId)
1941
+ if (pending === undefined) continue
1942
+ clearTimeout(pending.timer)
1943
+ this.pending.delete(callId)
1944
+ pending.resolve({
1945
+ ...renderToolResult(message.content),
1946
+ ...message.isError === true ? { isError: true } : {},
1947
+ })
1948
+ }
1949
+ if (freshUserTurn && this.pending.size > 0) {
1950
+ // The user interrupted a tool round; the ACP turn cannot receive these
1951
+ // results any more, so settle it and let the next prompt rebuild.
1952
+ for (const [callId, pending] of this.pending) {
1953
+ clearTimeout(pending.timer)
1954
+ pending.reject(new Error('宿主开始了新的用户轮次,未返回的工具结果已取消。'))
1955
+ this.pending.delete(callId)
1956
+ }
1957
+ if (this.promptInFlight) {
1958
+ void this.acp?.cancel()
1959
+ }
1960
+ this.awaitingToolResults = false
1961
+ }
1962
+ }
1963
+
1964
+ /** Run one harness turn. `feed` is new user content, or null for a continuation. */
1965
+ async *stream(options: GenerateOptions, feed: string | readonly MinimaxPromptBlock[] | null): AsyncGenerator<StreamChunk> {
1966
+ if (this.disposed) throw new Error(`MiniMax session ${this.sessionId} was disposed`)
1967
+ if (this.activeTurn) throw new Error(`MiniMax session ${this.sessionId} already has a turn in flight`)
1968
+ this.activeTurn = true
1969
+ const signal = options.signal
1970
+ const turn: TurnState = {
1971
+ blockIndex: 0,
1972
+ inputChars: feedTextLengthOf(feed),
1973
+ outputChars: 0,
1974
+ reasoningChars: 0,
1975
+ }
1976
+ let abortRequested = false
1977
+ let abortTimer: ReturnType<typeof setTimeout> | undefined
1978
+ let onAbortListener: (() => void) | undefined
1979
+
1980
+ try {
1981
+ await this.ensureStarted()
1982
+ if (!this.promptInFlight) {
1983
+ await this.startPrompt(feed ?? '')
1984
+ this.awaitingToolResults = false
1985
+ } else if (feed !== null && feedTextLengthOf(feed) > 0 && !this.awaitingToolResults) {
1986
+ throw new Error('MiniMax 会话正忙:上一轮尚未结束。')
1987
+ }
1988
+
1989
+ const onAbort = (): void => {
1990
+ abortRequested = true
1991
+ void this.acp?.cancel()
1992
+ abortTimer = setTimeout(() => { void this.dropAcp() }, this.abortGraceMs)
1993
+ }
1994
+ onAbortListener = onAbort
1995
+ signal?.addEventListener('abort', onAbort, { once: true })
1996
+
1997
+ while (true) {
1998
+ if (signal?.aborted === true) {
1999
+ if (!abortRequested) onAbort()
2000
+ rejectPending(this.pending, new Error('MiniMax 会话被宿主中止。'))
2001
+ this.promptInFlight = false
2002
+ this.awaitingToolResults = false
2003
+ yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn aborted by host', code: 'ABORTED' } })
2004
+ return
2005
+ }
2006
+ const event = await raceAbort(this.events.next(), signal)
2007
+ if (event === undefined) {
2008
+ // raceAbort resolves undefined for an abort too; the loop head
2009
+ // settles that case with an `aborted` finish.
2010
+ if (abortRequested) continue
2011
+ yield* this.finish(turn, { kind: 'error', failure: { message: 'MiniMax ACP stream closed', code: 'STREAM_CLOSED' } })
2012
+ return
2013
+ }
2014
+ switch (event.kind) {
2015
+ case 'text': {
2016
+ turn.outputChars += event.text.length
2017
+ if (turn.textBlock === undefined) {
2018
+ turn.textBlock = { index: turn.blockIndex++, text: '' }
2019
+ yield { type: 'block-start', index: turn.textBlock.index, blockType: 'text' }
2020
+ }
2021
+ turn.textBlock.text += event.text
2022
+ yield { type: 'text-delta', index: turn.textBlock.index, text: event.text }
2023
+ continue
2024
+ }
2025
+ case 'reasoning': {
2026
+ turn.reasoningChars += event.text.length
2027
+ if (turn.reasoningBlock === undefined) {
2028
+ turn.reasoningBlock = { index: turn.blockIndex++, text: '' }
2029
+ yield { type: 'block-start', index: turn.reasoningBlock.index, blockType: 'reasoning' }
2030
+ }
2031
+ turn.reasoningBlock.text += event.text
2032
+ yield { type: 'reasoning-delta', index: turn.reasoningBlock.index, text: event.text }
2033
+ continue
2034
+ }
2035
+ case 'usage': {
2036
+ if (event.size > 0) this.observedContextWindow = event.size
2037
+ if (event.used > 0) turn.contextUsed = event.used
2038
+ continue
2039
+ }
2040
+ case 'host-tool': {
2041
+ // Close the prose before the tool block so the harness assembler
2042
+ // sees text -> tool-call rather than an end frame after it.
2043
+ if (turn.textBlock !== undefined) {
2044
+ yield { type: 'block-end', index: turn.textBlock.index, block: { type: 'text', text: turn.textBlock.text } }
2045
+ turn.textBlock = undefined
2046
+ }
2047
+ if (turn.reasoningBlock !== undefined) {
2048
+ yield { type: 'block-end', index: turn.reasoningBlock.index, block: { type: 'reasoning', text: turn.reasoningBlock.text } }
2049
+ turn.reasoningBlock = undefined
2050
+ }
2051
+ const index = turn.blockIndex++
2052
+ yield { type: 'block-start', index, blockType: 'tool-call' }
2053
+ const args = JSON.stringify(event.args)
2054
+ yield {
2055
+ type: 'tool-call-delta',
2056
+ index,
2057
+ id: ToolCallId(event.callId),
2058
+ name: event.name,
2059
+ argumentsDelta: args,
2060
+ }
2061
+ yield {
2062
+ type: 'block-end',
2063
+ index,
2064
+ block: { type: 'tool-call', id: ToolCallId(event.callId), name: event.name, arguments: args },
2065
+ }
2066
+ this.awaitingToolResults = true
2067
+ yield* this.finish(turn, { kind: 'tool-calls' })
2068
+ return
2069
+ }
2070
+ case 'native-tool': {
2071
+ if (!this.cancelSent) {
2072
+ this.cancelSent = true
2073
+ this.nativeViolation = true
2074
+ await this.acp?.cancel()
2075
+ }
2076
+ continue
2077
+ }
2078
+ case 'prompt-done': {
2079
+ this.promptInFlight = false
2080
+ this.cancelSent = false
2081
+ if (abortRequested) {
2082
+ rejectPending(this.pending, new Error('MiniMax 会话被宿主中止。'))
2083
+ yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn aborted by host', code: 'ABORTED' } })
2084
+ return
2085
+ }
2086
+ if (this.nativeViolation) {
2087
+ this.nativeViolation = false
2088
+ this.correctionCount += 1
2089
+ if (this.correctionCount <= MAX_NATIVE_TOOL_RETRIES) {
2090
+ await new Promise(resolve => setTimeout(resolve, 350))
2091
+ try {
2092
+ await this.startPrompt(NATIVE_TOOL_CORRECTION)
2093
+ this.awaitingToolResults = false
2094
+ continue
2095
+ } catch (error) {
2096
+ yield* this.finish(turn, {
2097
+ kind: 'error',
2098
+ failure: {
2099
+ message: `MiniMax 内置工具不可用,重试失败:${error instanceof Error ? error.message : String(error)}`,
2100
+ code: 'BACKEND_TURN_ERROR',
2101
+ },
2102
+ })
2103
+ return
2104
+ }
2105
+ }
2106
+ yield* this.finish(turn, {
2107
+ kind: 'error',
2108
+ failure: {
2109
+ message: 'MiniMax 连续尝试调用内置工具。本插件只允许宿主 MCP 工具,已取消本轮。',
2110
+ code: 'BACKEND_TURN_ERROR',
2111
+ },
2112
+ })
2113
+ return
2114
+ }
2115
+ if (event.stopReason === 'end_turn' || event.stopReason === 'max_tokens') {
2116
+ yield* this.finish(turn, event.stopReason === 'max_tokens' ? { kind: 'max-tokens' } : { kind: 'stop' })
2117
+ return
2118
+ }
2119
+ if (event.stopReason === 'cancelled') {
2120
+ yield* this.finish(turn, { kind: 'aborted', failure: { message: 'MiniMax turn cancelled', code: 'ABORTED' } })
2121
+ return
2122
+ }
2123
+ yield* this.finish(turn, { kind: 'stop' })
2124
+ return
2125
+ }
2126
+ case 'prompt-error': {
2127
+ this.promptInFlight = false
2128
+ this.cancelSent = false
2129
+ yield* this.finish(turn, {
2130
+ kind: 'error',
2131
+ failure: { message: event.error.message, code: 'BACKEND_TURN_ERROR' },
2132
+ })
2133
+ return
2134
+ }
2135
+ case 'closed': {
2136
+ this.promptInFlight = false
2137
+ yield* this.finish(turn, {
2138
+ kind: 'error',
2139
+ failure: { message: event.error.message, code: 'BACKEND_TURN_ERROR' },
2140
+ })
2141
+ return
2142
+ }
2143
+ }
2144
+ }
2145
+ } finally {
2146
+ if (onAbortListener !== undefined) signal?.removeEventListener('abort', onAbortListener)
2147
+ if (abortTimer !== undefined) clearTimeout(abortTimer)
2148
+ this.activeTurn = false
2149
+ }
2150
+ }
2151
+
2152
+ /** Tear the ACP process down; parked handlers settle with a cancellation. */
2153
+ close(): void {
2154
+ if (this.disposed) return
2155
+ this.disposed = true
2156
+ rejectPending(this.pending, new Error('MiniMax 会话已关闭。'))
2157
+ this.events.close()
2158
+ const workspace = this.workspace
2159
+ const owned = this.ownsWorkspace
2160
+ this.workspace = undefined
2161
+ this.ownsWorkspace = false
2162
+ void this.dropAcp().finally(() => {
2163
+ if (workspace === undefined || !owned) return
2164
+ try {
2165
+ rmSync(workspace, { recursive: true, force: true })
2166
+ } catch {
2167
+ // Best effort.
2168
+ }
2169
+ })
2170
+ }
2171
+
2172
+ private async ensureStarted(): Promise<void> {
2173
+ if (this.acp !== null) return
2174
+ await this.mcpServer.start()
2175
+ if (this.workspace === undefined) {
2176
+ if (this.requestedCwd !== undefined) {
2177
+ this.workspace = this.requestedCwd
2178
+ this.ownsWorkspace = false
2179
+ } else {
2180
+ this.workspace = mkdtempSync(join(tmpdir(), 'dsh-minimax-session-'))
2181
+ this.ownsWorkspace = true
2182
+ }
2183
+ }
2184
+ this.bridge.setTools(this.toolSchemas)
2185
+ const registered = this.mcpServer.register(this.bridge)
2186
+ this.mcpToken = registered.token
2187
+ const system = `${this.systemPrompt.trim()}\n\n${HOST_TOOL_POLICY}\n`
2188
+ const acp = new MinimaxAcp({
2189
+ region: this.region,
2190
+ cwd: this.workspace,
2191
+ systemPrompt: system,
2192
+ mcpUrl: registered.url,
2193
+ mcpToken: registered.token,
2194
+ onUpdate: update => { this.events.push(update) },
2195
+ onExit: error => { this.events.push({ kind: 'closed', error }) },
2196
+ })
2197
+ try {
2198
+ await acp.start()
2199
+ await acp.selectModel(this.model, this.effort)
2200
+ this.acp = acp
2201
+ } catch (error) {
2202
+ await acp.close()
2203
+ this.mcpServer.unregister(registered.token)
2204
+ this.mcpToken = undefined
2205
+ throw error
2206
+ }
2207
+ }
2208
+
2209
+ private async startPrompt(prompt: string | readonly MinimaxPromptBlock[]): Promise<void> {
2210
+ const acp = this.acp
2211
+ if (acp === null) throw new Error('MiniMax ACP 尚未启动。')
2212
+ this.promptInFlight = true
2213
+ this.cancelSent = false
2214
+ void this.launchPrompt(acp, prompt, 0)
2215
+ }
2216
+
2217
+ /**
2218
+ * Start one ACP prompt and publish its outcome.
2219
+ *
2220
+ * Cancelling a turn makes the next `session/prompt` fail with "Session
2221
+ * already has an active Turn" for a short while even though the cancelled
2222
+ * prompt has already resolved. That race is routine here: the native-tool
2223
+ * correction is sent immediately after such a cancel, so it is retried with
2224
+ * a short backoff instead of being reported as a failed turn.
2225
+ */
2226
+ private async launchPrompt(
2227
+ acp: MinimaxAcp,
2228
+ prompt: string | readonly MinimaxPromptBlock[],
2229
+ attempt: number,
2230
+ ): Promise<void> {
2231
+ try {
2232
+ const response = await acp.prompt(prompt)
2233
+ this.events.push({ kind: 'prompt-done', stopReason: response.stopReason })
2234
+ } catch (error) {
2235
+ const message = error instanceof Error ? error.message : String(error)
2236
+ if (/401 token is required/i.test(message)) {
2237
+ // With a China IP the international edge redirects to the mainland
2238
+ // host, which drops the Authorization header; the CLI then reports a
2239
+ // missing token. Refresh the verdict in the background and explain the
2240
+ // real cause instead of asking for another login.
2241
+ void minimaxRegionBlocked(this.region, { fresh: true })
2242
+ const hint = minimaxRegionBlockedCached(this.region)
2243
+ ? minimaxRegionBlockMessage(this.region)
2244
+ : this.region === 'global'
2245
+ ? 'MiniMax 国际站拒绝了本机连接(401 token is required)。通常是本机网络 IP 不在国际站服务区域;请检查网络后重试,或切换到国内站。'
2246
+ : 'MiniMax 国内站拒绝了本机连接(401 token is required)。请检查网络或重新登录后重试。'
2247
+ this.events.push({ kind: 'prompt-error', error: new Error(hint) })
2248
+ return
2249
+ }
2250
+ const retryable = /active Turn|already has an active/i.test(message)
2251
+ if (retryable && attempt < 4 && !this.disposed && this.acp === acp) {
2252
+ await new Promise(resolve => setTimeout(resolve, 200 * 2 ** attempt))
2253
+ if (!this.disposed && this.acp === acp) {
2254
+ await this.launchPrompt(acp, prompt, attempt + 1)
2255
+ return
2256
+ }
2257
+ }
2258
+ this.events.push({ kind: 'prompt-error', error: error instanceof Error ? error : new Error(message) })
2259
+ }
2260
+ }
2261
+
2262
+ private async dropAcp(): Promise<void> {
2263
+ const acp = this.acp
2264
+ this.acp = null
2265
+ this.promptInFlight = false
2266
+ this.awaitingToolResults = false
2267
+ if (acp !== null) await acp.close()
2268
+ if (this.mcpToken !== undefined) {
2269
+ this.mcpServer.unregister(this.mcpToken)
2270
+ this.mcpToken = undefined
2271
+ }
2272
+ }
2273
+
2274
+ private async handleToolCall(name: string, args: Record<string, unknown>): Promise<MinimaxMcpToolResult> {
2275
+ if (this.disposed) return { content: [{ type: 'text', text: 'MiniMax 会话已关闭。' }], isError: true }
2276
+ const callId = `mm-${this.callNonce}-${++this.toolCounter}`
2277
+ const result = new Promise<MinimaxMcpToolResult>((resolve, reject) => {
2278
+ const timer = setTimeout(() => {
2279
+ this.pending.delete(callId)
2280
+ reject(new Error(`宿主工具 ${name} 在 ${Math.round(this.toolResultTimeoutMs / 1000)} 秒内没有返回结果。`))
2281
+ }, this.toolResultTimeoutMs)
2282
+ this.pending.set(callId, { resolve, reject, timer })
2283
+ })
2284
+ this.events.push({ kind: 'host-tool', callId, name, args })
2285
+ try {
2286
+ return await result
2287
+ } catch (error) {
2288
+ return {
2289
+ content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }],
2290
+ isError: true,
2291
+ }
2292
+ }
2293
+ }
2294
+
2295
+ private async *finish(turn: TurnState, reason: FinishReason): AsyncGenerator<StreamChunk> {
2296
+ if (turn.textBlock !== undefined) {
2297
+ yield { type: 'block-end', index: turn.textBlock.index, block: { type: 'text', text: turn.textBlock.text } }
2298
+ }
2299
+ if (turn.reasoningBlock !== undefined) {
2300
+ yield { type: 'block-end', index: turn.reasoningBlock.index, block: { type: 'reasoning', text: turn.reasoningBlock.text } }
2301
+ }
2302
+ // The CLI reports whole-context occupancy, which is the real prompt size;
2303
+ // the character estimate is only the fallback for providers that omit it.
2304
+ const usage = minimaxTurnUsage({
2305
+ ...turn.contextUsed === undefined ? {} : { contextUsed: turn.contextUsed },
2306
+ inputChars: turn.inputChars,
2307
+ outputChars: turn.outputChars,
2308
+ reasoningChars: turn.reasoningChars,
2309
+ })
2310
+ yield { type: 'usage', usage }
2311
+ yield { type: 'finish', reason }
2312
+ if (reason.kind !== 'tool-calls' && !this.disposed) {
2313
+ this.correctionCount = 0
2314
+ }
2315
+ }
2316
+ }
2317
+
2318
+ /** Reject every parked handler with the same reason. */
2319
+ function rejectPending(pending: Map<string, PendingHostCall>, error: Error): void {
2320
+ for (const [callId, entry] of pending) {
2321
+ clearTimeout(entry.timer)
2322
+ entry.reject(error)
2323
+ pending.delete(callId)
2324
+ }
2325
+ }
2326
+
2327
+ /** Wait for a promise, or give up after `ms`. */
2328
+ function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
2329
+ return new Promise<T>((resolve, reject) => {
2330
+ const timer = setTimeout(() => { reject(new Error(`${label} timed out after ${ms}ms`)) }, ms)
2331
+ promise.then(
2332
+ value => { clearTimeout(timer); resolve(value) },
2333
+ error => { clearTimeout(timer); reject(error) },
2334
+ )
2335
+ })
2336
+ }
2337
+
2338
+ /** Await a queue read, giving up when the harness aborts the turn. */
2339
+ function raceAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T | undefined> {
2340
+ if (signal === undefined) return promise
2341
+ if (signal.aborted) return Promise.resolve(undefined)
2342
+ return new Promise((resolve, reject) => {
2343
+ const onAbort = (): void => {
2344
+ signal.removeEventListener('abort', onAbort)
2345
+ resolve(undefined)
2346
+ }
2347
+ signal.addEventListener('abort', onAbort, { once: true })
2348
+ promise.then(
2349
+ value => {
2350
+ signal.removeEventListener('abort', onAbort)
2351
+ resolve(value)
2352
+ },
2353
+ error => {
2354
+ signal.removeEventListener('abort', onAbort)
2355
+ reject(error)
2356
+ },
2357
+ )
2358
+ })
2359
+ }
2360
+
2361
+ /** Warm session pool, keyed by harness session id. */
2362
+ export class MinimaxSessionManager {
2363
+ private readonly sessions = new Map<string, { session: MinimaxSession, region: MinimaxRegion }>()
2364
+
2365
+ constructor(
2366
+ readonly maxSessions: Live<number>,
2367
+ private readonly mcpServer: MinimaxMcpServer,
2368
+ private readonly runtime: { toolResultTimeoutMs?: Live<number>, abortGraceMs?: Live<number> } = {},
2369
+ ) {}
2370
+
2371
+ forSession(sessionId: string, region: MinimaxRegion, model: string): MinimaxSession {
2372
+ const existing = this.sessions.get(sessionId)
2373
+ if (existing !== undefined) {
2374
+ if (existing.region !== region) {
2375
+ existing.session.close()
2376
+ this.sessions.delete(sessionId)
2377
+ } else {
2378
+ this.sessions.delete(sessionId)
2379
+ this.sessions.set(sessionId, existing)
2380
+ return existing.session
2381
+ }
2382
+ }
2383
+ const session = new MinimaxSession(sessionId, model, this.mcpServer, this.runtime)
2384
+ this.sessions.set(sessionId, { session, region })
2385
+ const cap = readLive(this.maxSessions, 8)
2386
+ while (this.sessions.size > cap) {
2387
+ const oldest = this.sessions.keys().next()
2388
+ if (oldest.done === true) break
2389
+ const victim = this.sessions.get(oldest.value)
2390
+ this.sessions.delete(oldest.value)
2391
+ victim?.session.close()
2392
+ }
2393
+ return session
2394
+ }
2395
+
2396
+ dispose(sessionId: string): void {
2397
+ const entry = this.sessions.get(sessionId)
2398
+ if (entry === undefined) return
2399
+ this.sessions.delete(sessionId)
2400
+ entry.session.close()
2401
+ }
2402
+
2403
+ closeAll(): void {
2404
+ for (const entry of this.sessions.values()) entry.session.close()
2405
+ this.sessions.clear()
2406
+ }
2407
+ }
2408
+
2409
+ /** A one-shot turn, used for titles and compaction summaries. */
2410
+ export async function minimaxColdStream(
2411
+ region: MinimaxRegion,
2412
+ prompt: string,
2413
+ model: string | undefined,
2414
+ options: GenerateOptions,
2415
+ ): Promise<StreamChunk[]> {
2416
+ const chunks: StreamChunk[] = []
2417
+ let text = ''
2418
+ const cwd = mkdtempSync(join(tmpdir(), 'dsh-minimax-cold-'))
2419
+ const acp = new MinimaxAcp({
2420
+ region,
2421
+ cwd,
2422
+ systemPrompt: 'You are a concise helper used only for titles and summaries. Do not call any tool.',
2423
+ disableTools: true,
2424
+ onUpdate: update => {
2425
+ if (update.kind === 'text') text += update.text
2426
+ },
2427
+ })
2428
+ const signal = options.signal
2429
+ const onAbort = (): void => { void acp.cancel() }
2430
+ signal?.addEventListener('abort', onAbort, { once: true })
2431
+ try {
2432
+ await acp.start()
2433
+ if (model !== undefined) await acp.selectModel(model)
2434
+ const response = await acp.prompt(prompt)
2435
+ if (signal?.aborted === true || response.stopReason === 'cancelled') {
2436
+ chunks.push({ type: 'finish', reason: { kind: 'aborted', failure: { message: 'aborted by host', code: 'ABORTED' } } })
2437
+ return chunks
2438
+ }
2439
+ if (text.trim().length === 0) {
2440
+ chunks.push({ type: 'finish', reason: { kind: 'error', failure: { message: 'MiniMax side-channel returned no content', code: EMPTY_RESPONSE_CODE } } })
2441
+ return chunks
2442
+ }
2443
+ chunks.push({ type: 'block-start', index: 0, blockType: 'text' })
2444
+ for (let index = 0; index < text.length; index += 192) {
2445
+ chunks.push({ type: 'text-delta', index: 0, text: text.slice(index, index + 192) })
2446
+ }
2447
+ chunks.push({ type: 'block-end', index: 0, block: { type: 'text', text } })
2448
+ chunks.push({
2449
+ type: 'usage',
2450
+ usage: minimaxTurnUsage({ inputChars: prompt.length, outputChars: text.length, reasoningChars: 0 }),
2451
+ })
2452
+ chunks.push({ type: 'finish', reason: { kind: 'stop' } })
2453
+ return chunks
2454
+ } finally {
2455
+ signal?.removeEventListener('abort', onAbort)
2456
+ await acp.close()
2457
+ try {
2458
+ rmSync(cwd, { recursive: true, force: true })
2459
+ } catch {
2460
+ // Best effort.
2461
+ }
2462
+ }
2463
+ }