dsh-agent-sdk-bridge 1.2.3 → 1.3.2

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