dsh-agent-sdk-bridge 1.0.0 → 1.1.0

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