dsh-agent-sdk-bridge 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,370 @@
1
+ /**
2
+ * `MinimaxAdapter`: route the harness LLM seam onto a MiniMax Code account.
3
+ *
4
+ * The ACP agent owns the conversation; this adapter decides what new text to
5
+ * send, which model/effort to select, and how the ACP tool calls map onto the
6
+ * harness's tool seam. One provider serves both login regions; the region is a
7
+ * live config choice and every ACP process is pinned to it.
8
+ *
9
+ * @module dsh-agent-sdk-bridge/minimax-adapter
10
+ */
11
+
12
+ import { LlmAdapter } from '@deepseek-ai/dsh-llm'
13
+ import type {
14
+ GenerateOptions, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo,
15
+ PreparedAdapterCall, RequestMessage, StreamChunk,
16
+ } from '@deepseek-ai/dsh-llm'
17
+ import type { MinimaxRegion } from './brand.ts'
18
+ import {
19
+ MinimaxAuth, MinimaxCatalog, MinimaxMcpServer, MinimaxSessionManager,
20
+ MINIMAX_CACHE_TTL_MS, MINIMAX_DEFAULT_CONTEXT_WINDOW, MINIMAX_DEFAULT_MAX_TOKENS,
21
+ MINIMAX_FETCH_TIMEOUT_MS, invalidateMinimaxRegionAccess, invalidateMinimaxUsage,
22
+ minimaxColdStream, minimaxRegionBlockMessage, minimaxRegionBlocked,
23
+ minimaxRegionBlockedCached, minimaxSignedIn, minimaxUsage,
24
+ } from './minimax.ts'
25
+ import type { MinimaxModel, MinimaxUsageSnapshot } from './minimax.ts'
26
+ import { resolveMinimaxCli } from './minimax-cli.ts'
27
+ import { reasoningInfo, planContinuation } from './adapter.ts'
28
+ import type { Live } from './live.ts'
29
+ import { readLive, readLiveOptional } from './live.ts'
30
+ import { feedToText, renderInitialFeed } from './render.ts'
31
+
32
+ /** The MiniMax Code provider route. */
33
+ export const MINIMAX_PROVIDER = 'minimax-acp'
34
+
35
+ /** Everything the adapter reads lazily from the plugin config. */
36
+ export interface MinimaxAdapterOptions {
37
+ maxSessions?: Live<number>
38
+ modelCacheTtlMs?: Live<number>
39
+ catalogFetchTimeoutMs?: Live<number>
40
+ toolResultTimeoutMs?: Live<number>
41
+ abortGraceMs?: Live<number>
42
+ defaultMaxTokens?: Live<number>
43
+ defaultReasoningEffort?: Live<string | undefined>
44
+ displayName?: Live<string>
45
+ region?: Live<MinimaxRegion>
46
+ /** Per-region deny-lists; the page edits each region's list separately. */
47
+ disabledModels?: (region: MinimaxRegion) => readonly string[]
48
+ /** Per-region context-window overrides, keyed by model id. */
49
+ modelContextWindows?: (region: MinimaxRegion) => Readonly<Record<string, number>>
50
+ modelAliases?: Live<Readonly<Record<string, string>>>
51
+ }
52
+
53
+ const NO_MODELS: readonly string[] = []
54
+ const NO_ALIASES: Readonly<Record<string, string>> = {}
55
+
56
+ /** Map a harness-side id onto an ACP model value. */
57
+ export function resolveMinimaxModelId(
58
+ model: string,
59
+ aliases: Readonly<Record<string, string>> = {},
60
+ ): string {
61
+ const configured = aliases[model] ?? aliases[model.toLowerCase()]
62
+ if (configured !== undefined && configured.length > 0) return configured
63
+ const stripped = model.startsWith('minimax-') ? model.slice('minimax-'.length) : model
64
+ return stripped
65
+ }
66
+
67
+ function modelInfo(provider: string, model: MinimaxModel): LlmModelInfo {
68
+ return {
69
+ provider,
70
+ id: model.id,
71
+ name: model.name,
72
+ ...model.description === undefined ? {} : { description: model.description },
73
+ inputModalities: model.vision ? ['text', 'image'] : ['text'],
74
+ }
75
+ }
76
+
77
+ /** The MiniMax Code-backed adapter. */
78
+ export class MinimaxAdapter extends LlmAdapter {
79
+ private readonly options: MinimaxAdapterOptions
80
+ private readonly sessions: MinimaxSessionManager
81
+ private readonly catalog: MinimaxCatalog
82
+ private readonly auth = new MinimaxAuth()
83
+ private readonly mcpServer = new MinimaxMcpServer()
84
+ private readonly disabledCache = new Map<MinimaxRegion, { key: string, set: ReadonlySet<string> }>()
85
+
86
+ constructor(options: MinimaxAdapterOptions = {}) {
87
+ super()
88
+ this.options = options
89
+ this.sessions = new MinimaxSessionManager(
90
+ options.maxSessions ?? 8,
91
+ this.mcpServer,
92
+ { toolResultTimeoutMs: options.toolResultTimeoutMs, abortGraceMs: options.abortGraceMs },
93
+ )
94
+ this.catalog = new MinimaxCatalog(
95
+ options.region ?? (() => 'cn'),
96
+ options.modelCacheTtlMs ?? MINIMAX_CACHE_TTL_MS,
97
+ options.catalogFetchTimeoutMs ?? MINIMAX_FETCH_TIMEOUT_MS,
98
+ )
99
+ }
100
+
101
+ private get region(): MinimaxRegion {
102
+ return readLive(this.options.region ?? (() => 'cn'), 'cn')
103
+ }
104
+
105
+ private disabledFor(region: MinimaxRegion): ReadonlySet<string> {
106
+ const source = this.options.disabledModels?.(region) ?? NO_MODELS
107
+ const key = source.join('\u0000')
108
+ const cached = this.disabledCache.get(region)
109
+ if (cached?.key === key) return cached.set
110
+ const set = new Set(source)
111
+ this.disabledCache.set(region, { key, set })
112
+ return set
113
+ }
114
+
115
+ private get aliases(): Readonly<Record<string, string>> {
116
+ return readLive(this.options.modelAliases, NO_ALIASES)
117
+ }
118
+
119
+ private get displayName(): string {
120
+ return readLive(this.options.displayName, 'MiniMax Code')
121
+ }
122
+
123
+ override providerInfo(provider: string): LlmProviderInfo {
124
+ return { id: provider, name: this.displayName }
125
+ }
126
+
127
+ /** The live catalog, unfiltered (the page must show switched-off models). */
128
+ async describeCatalog(region: MinimaxRegion = this.region): Promise<readonly MinimaxModel[]> {
129
+ if (!this.isSignedIn(region)) return []
130
+ if (await minimaxRegionBlocked(region)) return []
131
+ return this.catalog.models(region)
132
+ }
133
+
134
+ /** Whether the region's endpoints are refusing this machine's network. */
135
+ regionBlocked(region: MinimaxRegion = this.region): boolean {
136
+ return minimaxRegionBlockedCached(region)
137
+ }
138
+
139
+ /** Whether the selected (or given) region has a stored login. */
140
+ isSignedIn(region: MinimaxRegion = this.region): boolean {
141
+ return this.auth.status(region).signedIn || minimaxSignedIn(region)
142
+ }
143
+
144
+ /** Why the last catalog read failed, for the page's guidance. */
145
+ catalogError(region: MinimaxRegion = this.region): string | undefined {
146
+ if (resolveMinimaxCli() === undefined) {
147
+ return '未安装 MiniMax Code CLI(mcode)。请先安装后再登录。'
148
+ }
149
+ if (minimaxRegionBlockedCached(region)) return minimaxRegionBlockMessage(region)
150
+ if (!this.isSignedIn(region)) return '请先登录 MiniMax Code,登录后才会读取并显示模型目录。'
151
+ return this.catalog.error(region)
152
+ }
153
+
154
+ /**
155
+ * Drop the cached catalog and the region verdict behind it.
156
+ *
157
+ * The page calls this with `fresh=1` on a region switch, which is exactly
158
+ * when the network may have changed; keeping a 30-second "blocked" verdict
159
+ * would hide the catalog the switch was meant to reveal.
160
+ */
161
+ invalidateCatalog(region?: MinimaxRegion): void {
162
+ this.catalog.invalidate(region)
163
+ invalidateMinimaxRegionAccess(region)
164
+ }
165
+
166
+ /** Login status, installer state and (when signed in) the account's quota. */
167
+ async usageInfo(fresh = false, region?: MinimaxRegion): Promise<MinimaxUsageSnapshot> {
168
+ const target = region ?? this.region
169
+ const installed = resolveMinimaxCli() !== undefined
170
+ const status = this.auth.status(target)
171
+ const signedIn = status.signedIn || minimaxSignedIn(target)
172
+ if (!signedIn) {
173
+ return {
174
+ at: Date.now(),
175
+ region: target,
176
+ signedIn: false,
177
+ installed,
178
+ ...installed ? {} : { error: '未安装 MiniMax Code CLI(mcode)。' },
179
+ ...status.error === undefined ? {} : { error: status.error },
180
+ }
181
+ }
182
+ const snapshot = await minimaxUsage(target, { fresh })
183
+ return {
184
+ ...snapshot,
185
+ signedIn: true,
186
+ installed,
187
+ ...snapshot.error !== undefined || status.error === undefined ? {} : { error: status.error },
188
+ }
189
+ }
190
+
191
+ /** Drop cached quota readings and the region verdict (login, logout, CLI). */
192
+ invalidateUsage(region?: MinimaxRegion): void {
193
+ invalidateMinimaxUsage(region)
194
+ invalidateMinimaxRegionAccess(region)
195
+ }
196
+
197
+ /** Login progress for one region; the page polls this. */
198
+ authStatus(region: MinimaxRegion): ReturnType<MinimaxAuth['status']> {
199
+ return this.auth.status(region)
200
+ }
201
+
202
+ startLogin(region: MinimaxRegion): ReturnType<MinimaxAuth['start']> {
203
+ return this.auth.start(region, ok => {
204
+ if (!ok) return
205
+ this.sessions.closeAll()
206
+ this.invalidateCatalog(region)
207
+ this.invalidateUsage(region)
208
+ invalidateMinimaxRegionAccess(region)
209
+ })
210
+ }
211
+
212
+ async logout(region: MinimaxRegion): ReturnType<MinimaxAuth['logout']> {
213
+ const result = await this.auth.logout(region)
214
+ this.sessions.closeAll()
215
+ this.invalidateCatalog(region)
216
+ this.invalidateUsage(region)
217
+ invalidateMinimaxRegionAccess(region)
218
+ return result
219
+ }
220
+
221
+ isModelDisabled(id: string, region: MinimaxRegion = this.region): boolean {
222
+ return this.disabledFor(region).has(id)
223
+ }
224
+
225
+ contextWindowFor(id: string, region: MinimaxRegion = this.region): number | undefined {
226
+ return this.options.modelContextWindows?.(region)[id]
227
+ }
228
+
229
+ override async listModels(provider: string): Promise<readonly LlmModelInfo[]> {
230
+ const region = this.region
231
+ if (!this.isSignedIn(region)) return []
232
+ if (await minimaxRegionBlocked(region)) return []
233
+ const models = await this.catalog.models(region)
234
+ const disabled = this.disabledFor(region)
235
+ return models.filter(model => !disabled.has(model.id)).map(model => modelInfo(provider, model))
236
+ }
237
+
238
+ override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
239
+ const region = this.region
240
+ const target = resolveMinimaxModelId(model, this.aliases)
241
+ const live = (await this.catalog.models(region)).find(entry => entry.id === target)
242
+ if (live !== undefined) {
243
+ const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, live.reasoning)
244
+ return {
245
+ provider,
246
+ id: model,
247
+ name: live.name,
248
+ ...live.description === undefined ? {} : { description: live.description },
249
+ inputModalities: live.vision ? ['text', 'image'] : ['text'],
250
+ context: { contextWindow: this.contextWindowFor(target, region) ?? live.defaultContextWindow },
251
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
252
+ ...reasoning === undefined ? {} : { reasoning },
253
+ }
254
+ }
255
+ const reasoning = reasoningInfo(
256
+ undefined,
257
+ readLiveOptional(this.options.defaultReasoningEffort),
258
+ true,
259
+ )
260
+ return {
261
+ provider,
262
+ id: model,
263
+ name: model,
264
+ inputModalities: ['text'],
265
+ context: { contextWindow: this.contextWindowFor(target, region) ?? MINIMAX_DEFAULT_CONTEXT_WINDOW },
266
+ defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
267
+ ...reasoning === undefined ? {} : { reasoning },
268
+ }
269
+ }
270
+
271
+ override async prepareCall(provider: string, model: string, signal?: AbortSignal): Promise<PreparedAdapterCall> {
272
+ const info = await this.resolveModel(provider, model)
273
+ void signal
274
+ return { model: info, stream: options => this.dispatch(options) }
275
+ }
276
+
277
+ async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
278
+ yield* this.dispatch(options)
279
+ }
280
+
281
+ private async *dispatch(options: GenerateOptions): AsyncGenerator<StreamChunk> {
282
+ const region = this.region
283
+ if (!this.isSignedIn(region)) {
284
+ const label = region === 'cn' ? 'MiniMax 国内站' : 'MiniMax 国际站'
285
+ throw new Error(`${label}尚未登录,请先在设置 → MiniMax Code 中登录。`)
286
+ }
287
+ if (await minimaxRegionBlocked(region)) {
288
+ throw new Error(minimaxRegionBlockMessage(region))
289
+ }
290
+ const model = resolveMinimaxModelId(options.model, this.aliases)
291
+ if (options.sessionId === undefined || options.purpose !== undefined) {
292
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages))
293
+ + '\n(这是一次性旁路请求,直接输出下一条助手回复。)'
294
+ for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk
295
+ return
296
+ }
297
+ const sessionId = String(options.sessionId)
298
+ const effort = options.reasoningEffort ?? readLiveOptional(this.options.defaultReasoningEffort)
299
+ let session = this.sessions.forSession(sessionId, region, model)
300
+ if (session.fedMessages === undefined) {
301
+ yield* this.firstTurn(session, options, region, model, effort)
302
+ return
303
+ }
304
+ const tail = options.messages.slice(session.fedMessages.length)
305
+ session.deliverToolResults(tail)
306
+ const plan = planContinuation(session.fedMessages, options.messages)
307
+ if (plan.rebuild) {
308
+ this.sessions.dispose(sessionId)
309
+ session = this.sessions.forSession(sessionId, region, model)
310
+ yield* this.firstTurn(session, options, region, model, effort)
311
+ return
312
+ }
313
+ if (plan.feed !== null && session.busy) {
314
+ // The user took over while a tool round was still open. The old ACP turn
315
+ // cannot accept the new message, so rebuild from the durable history.
316
+ this.sessions.dispose(sessionId)
317
+ session = this.sessions.forSession(sessionId, region, model)
318
+ yield* this.firstTurn(session, options, region, model, effort)
319
+ return
320
+ }
321
+ const reset = session.configure(region, model, {
322
+ effort,
323
+ system: options.system,
324
+ cwd: this.cwdOf(options),
325
+ })
326
+ if (reset || (plan.feed === null && !session.busy)) {
327
+ // Either the prompt/cwd change discarded the warm ACP process, or the
328
+ // tool round it was waiting on ended without it. Only a complete replay
329
+ // can restore the conversation in both cases.
330
+ this.sessions.dispose(sessionId)
331
+ session = this.sessions.forSession(sessionId, region, model)
332
+ yield* this.firstTurn(session, options, region, model, effort)
333
+ return
334
+ }
335
+ session.ensureTools(options.tools ?? [])
336
+ session.fedMessages = options.messages
337
+ session.fedSystem = options.system
338
+ const feed = plan.feed === null ? null : feedToText(plan.feed)
339
+ yield* session.stream(options, feed)
340
+ }
341
+
342
+ private async *firstTurn(
343
+ session: ReturnType<MinimaxSessionManager['forSession']>,
344
+ options: GenerateOptions,
345
+ region: MinimaxRegion,
346
+ model: string,
347
+ effort: string | undefined,
348
+ ): AsyncGenerator<StreamChunk> {
349
+ session.configure(region, model, {
350
+ effort,
351
+ system: options.system,
352
+ cwd: this.cwdOf(options),
353
+ })
354
+ session.ensureTools(options.tools ?? [])
355
+ session.fedMessages = options.messages
356
+ session.fedSystem = options.system
357
+ const feed = feedToText(renderInitialFeed(undefined, options.messages))
358
+ yield* session.stream(options, feed)
359
+ }
360
+
361
+ private cwdOf(options: GenerateOptions): string | undefined {
362
+ return (options as GenerateOptions & { cwd?: string }).cwd
363
+ }
364
+
365
+ close(): void {
366
+ this.sessions.closeAll()
367
+ this.mcpServer.close()
368
+ this.auth.stop()
369
+ }
370
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * The MiniMax Code CLI (`mcode`): locating it and running its installer.
3
+ *
4
+ * MiniMax ships `@minimax-ai/code` as a global npm package whose `mcode`
5
+ * launcher is a Node shim. Its native SQLite dependency is installed by a
6
+ * postinstall script, and npm 12 blocks install scripts unless they are named
7
+ * with `--allow-scripts`; a plain `npm i -g` leaves a CLI that cannot start.
8
+ * The installer below therefore passes the flags the package documents.
9
+ *
10
+ * @module dsh-agent-sdk-bridge/minimax-cli
11
+ */
12
+
13
+ import { spawn, type ChildProcess } from 'node:child_process'
14
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { dirname, join, delimiter } from 'node:path'
17
+ import { TextDecoder } from 'node:util'
18
+
19
+ /** How to invoke the CLI: an executable plus its leading arguments. */
20
+ export interface MinimaxCliSpec {
21
+ command: string
22
+ args: string[]
23
+ /** The JavaScript entry, when the launcher resolves to one. */
24
+ cliPath?: string
25
+ }
26
+
27
+ /** The npm package and the version verified to work with native SQLite. */
28
+ const PACKAGE = '@minimax-ai/code'
29
+ const INSTALL_VERSION = '0.6.12'
30
+ const INSTALL_FLAGS = [
31
+ '--ignore-scripts=false',
32
+ '--include=optional',
33
+ '--allow-scripts=@minimax-ai/code,better-sqlite3',
34
+ '--registry', 'https://registry.npmjs.org/',
35
+ '--foreground-scripts',
36
+ ]
37
+
38
+ function fromJsEntry(path: string): MinimaxCliSpec {
39
+ return { command: process.execPath, args: [path], cliPath: path }
40
+ }
41
+
42
+ function fromShim(shim: string): MinimaxCliSpec | undefined {
43
+ if (shim.endsWith('.cmd') || shim.endsWith('.bat')) {
44
+ // npm's Windows shim forwards to the package's cli.js. Reading it avoids a
45
+ // cmd.exe layer, which keeps ACP's stdio byte-clean.
46
+ try {
47
+ const text = readFileSync(shim, 'utf8')
48
+ const match = /["']([^"']*node_modules[\\/]@minimax-ai[\\/]code[\\/]cli\.js)["']/.exec(text)
49
+ if (match !== null && existsSync(match[1])) return fromJsEntry(match[1])
50
+ } catch {
51
+ // Fall through to the sibling-package guess below.
52
+ }
53
+ const sibling = join(dirname(shim), 'node_modules', '@minimax-ai', 'code', 'cli.js')
54
+ if (existsSync(sibling)) return fromJsEntry(sibling)
55
+ return {
56
+ command: process.env.ComSpec ?? 'cmd.exe',
57
+ args: ['/d', '/c', shim],
58
+ }
59
+ }
60
+ if (shim.endsWith('.js') || shim.endsWith('.mjs')) return fromJsEntry(shim)
61
+ try {
62
+ const real = realpathSync(shim)
63
+ if (real.endsWith('.js') || real.endsWith('.mjs')) return fromJsEntry(real)
64
+ } catch {
65
+ // A path that cannot be resolved is still usable as a command.
66
+ }
67
+ return { command: shim, args: [] }
68
+ }
69
+
70
+ /**
71
+ * Locate `mcode`.
72
+ *
73
+ * `MCODE_CLI_PATH` wins (a cli.js path or an executable); otherwise the PATH
74
+ * shims and the global npm prefixes are checked. The explicit cli.js lookup
75
+ * matters on Windows, where spawning a `.cmd` for ACP would put cmd.exe between
76
+ * the protocol streams.
77
+ */
78
+ export function resolveMinimaxCli(): MinimaxCliSpec | undefined {
79
+ const override = process.env.MCODE_CLI_PATH?.trim()
80
+ if (override !== undefined && override.length > 0 && existsSync(override)) {
81
+ return fromShim(override)
82
+ }
83
+
84
+ const names = process.platform === 'win32'
85
+ ? ['mcode.cmd', 'mcode.exe', 'mcode']
86
+ : ['mcode']
87
+ for (const directory of (process.env.PATH ?? '').split(delimiter)) {
88
+ if (directory.trim() === '') continue
89
+ for (const name of names) {
90
+ const candidate = join(directory, name)
91
+ if (existsSync(candidate)) return fromShim(candidate)
92
+ }
93
+ }
94
+
95
+ const home = homedir()
96
+ const candidates = process.platform === 'win32'
97
+ ? [
98
+ join(process.env.APPDATA ?? join(home, 'AppData', 'Roaming'), 'npm', 'node_modules', PACKAGE, 'cli.js'),
99
+ join(process.env.LOCALAPPDATA ?? join(home, 'AppData', 'Local'), 'npm', 'node_modules', PACKAGE, 'cli.js'),
100
+ join(process.env.ProgramFiles ?? 'C:\\Program Files', 'nodejs', 'node_modules', PACKAGE, 'cli.js'),
101
+ ]
102
+ : [
103
+ join(home, '.npm-global', 'lib', 'node_modules', PACKAGE, 'cli.js'),
104
+ join('/usr', 'local', 'lib', 'node_modules', PACKAGE, 'cli.js'),
105
+ join('/usr', 'lib', 'node_modules', PACKAGE, 'cli.js'),
106
+ join(home, '.local', 'lib', 'node_modules', PACKAGE, 'cli.js'),
107
+ ]
108
+ for (const candidate of candidates) {
109
+ if (existsSync(candidate)) return fromJsEntry(candidate)
110
+ }
111
+ return undefined
112
+ }
113
+
114
+ /** The spawn argument list for one CLI invocation. */
115
+ export function minimaxCliArgs(spec: MinimaxCliSpec, args: readonly string[]): string[] {
116
+ return [...spec.args, ...args]
117
+ }
118
+
119
+ /** What the settings page may ask the installer to do. */
120
+ export type MinimaxSetupMode = 'install' | 'uninstall'
121
+
122
+ /** Whether a value names an installer action. */
123
+ export function isMinimaxSetupMode(value: unknown): value is MinimaxSetupMode {
124
+ return value === 'install' || value === 'uninstall'
125
+ }
126
+
127
+ /** One installer run's state, kept for the process lifetime. */
128
+ interface SetupRun {
129
+ child: ChildProcess
130
+ mode: MinimaxSetupMode
131
+ startedAt: number
132
+ finishedAt?: number
133
+ code?: number | null
134
+ lines: string[]
135
+ pending: string
136
+ decoder: TextDecoder
137
+ truncated: boolean
138
+ }
139
+
140
+ /** Cap on kept output. */
141
+ const MAX_LINES = 400
142
+
143
+ let current: SetupRun | undefined
144
+
145
+ /** Snapshot the page polls. */
146
+ export interface MinimaxSetupStatus {
147
+ running: boolean
148
+ mode?: MinimaxSetupMode
149
+ startedAt?: number
150
+ finishedAt?: number
151
+ code?: number | null
152
+ lines: string[]
153
+ truncated: boolean
154
+ installed: boolean
155
+ cliPath?: string
156
+ }
157
+
158
+ function absorb(run: SetupRun, chunk: Uint8Array, done: boolean): void {
159
+ run.pending += run.decoder.decode(chunk, { stream: !done })
160
+ const parts = run.pending.split(/\r\n|\r|\n/)
161
+ run.pending = done ? '' : (parts.pop() ?? '')
162
+ for (const part of parts) {
163
+ if (part.trim() === '') continue
164
+ run.lines.push(part)
165
+ }
166
+ if (done && run.pending.trim() !== '') run.lines.push(run.pending.trim())
167
+ while (run.lines.length > MAX_LINES) {
168
+ run.lines.shift()
169
+ run.truncated = true
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Start the npm installer or uninstaller.
175
+ *
176
+ * The command is fixed: the mode is an allow-list and no user input reaches
177
+ * argv. npm itself is run through cmd.exe on Windows because npm is a `.cmd`
178
+ * shim and Node refuses to spawn it directly on recent versions.
179
+ */
180
+ export function startMinimaxSetup(
181
+ mode: MinimaxSetupMode,
182
+ onFinish?: (code: number | null) => void,
183
+ ): { started: true } | { started: false, reason: 'busy' | 'unsupported', error: string } {
184
+ if (current !== undefined && current.finishedAt === undefined) {
185
+ return { started: false, reason: 'busy', error: '已经有一次 MiniMax CLI 安装在跑了,请等它结束。' }
186
+ }
187
+ if (process.platform !== 'win32' && mode === 'install') {
188
+ return {
189
+ started: false,
190
+ reason: 'unsupported',
191
+ error: '一键安装 MiniMax CLI 目前只支持 Windows;请在终端手动执行 npm install -g @minimax-ai/code。',
192
+ }
193
+ }
194
+
195
+ const npmArgs = mode === 'install'
196
+ ? ['install', '--global', `${PACKAGE}@${INSTALL_VERSION}`, ...INSTALL_FLAGS]
197
+ : ['uninstall', '--global', PACKAGE]
198
+ const command = process.platform === 'win32' ? (process.env.ComSpec ?? 'cmd.exe') : 'npm'
199
+ const args = process.platform === 'win32'
200
+ ? ['/d', '/c', 'npm', ...npmArgs]
201
+ : npmArgs
202
+
203
+ const run: SetupRun = {
204
+ child: undefined as unknown as ChildProcess,
205
+ mode,
206
+ startedAt: Date.now(),
207
+ lines: [],
208
+ pending: '',
209
+ decoder: new TextDecoder('utf-8'),
210
+ truncated: false,
211
+ }
212
+ const child = spawn(command, args, {
213
+ cwd: homedir(),
214
+ windowsHide: true,
215
+ stdio: ['ignore', 'pipe', 'pipe'],
216
+ })
217
+ run.child = child
218
+ current = run
219
+
220
+ const finish = (code: number | null): void => {
221
+ if (run.finishedAt !== undefined) return
222
+ run.finishedAt = Date.now()
223
+ run.code = code
224
+ try {
225
+ onFinish?.(code)
226
+ } catch (error) {
227
+ run.lines.push(`收尾回调失败:${error instanceof Error ? error.message : String(error)}`)
228
+ }
229
+ }
230
+ child.stdout?.on('data', (chunk: Buffer) => absorb(run, chunk, false))
231
+ child.stderr?.on('data', (chunk: Buffer) => absorb(run, chunk, false))
232
+ child.on('error', error => {
233
+ run.lines.push(`无法启动 npm:${error instanceof Error ? error.message : String(error)}`)
234
+ finish(null)
235
+ })
236
+ child.on('close', code => {
237
+ absorb(run, new Uint8Array(), true)
238
+ finish(code)
239
+ })
240
+ return { started: true }
241
+ }
242
+
243
+ /** The latest installer run, with any not-yet-newlined tail included. */
244
+ export function readMinimaxSetupStatus(): MinimaxSetupStatus {
245
+ const spec = resolveMinimaxCli()
246
+ const installed = spec !== undefined
247
+ if (current === undefined) {
248
+ return { running: false, lines: [], truncated: false, installed, ...spec?.cliPath === undefined ? {} : { cliPath: spec.cliPath } }
249
+ }
250
+ const run = current
251
+ const lines = run.pending.trim() === ''
252
+ ? run.lines
253
+ : [...run.lines, run.pending.trim()]
254
+ return {
255
+ running: run.finishedAt === undefined,
256
+ mode: run.mode,
257
+ startedAt: run.startedAt,
258
+ ...run.finishedAt === undefined ? {} : { finishedAt: run.finishedAt, code: run.code ?? null },
259
+ lines,
260
+ truncated: run.truncated,
261
+ installed,
262
+ ...spec?.cliPath === undefined ? {} : { cliPath: spec.cliPath },
263
+ }
264
+ }
265
+
266
+ /** Abandon a running installer. */
267
+ export function stopMinimaxSetup(): void {
268
+ if (current !== undefined && current.finishedAt === undefined) current.child.kill()
269
+ }
270
+
271
+ /** A small object facade for callers that prefer a service shape. */
272
+ export class MinimaxCliSetup {
273
+ readonly start = startMinimaxSetup
274
+ readonly status = readMinimaxSetupStatus
275
+ readonly stop = stopMinimaxSetup
276
+ }