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