@molecule/api-ai-minimax 1.0.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/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai-minimax` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai-minimax is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,26 @@
1
+ /**
2
+ * MiniMax AI provider for molecule.dev.
3
+ *
4
+ * @remarks
5
+ * Config: `MINIMAX_API_KEY` (SERVER-side only) plus an optional default model id/base URL.
6
+ *
7
+ * **Missing `MINIMAX_API_KEY` fails fast**: the provider throws naming the exact env var on
8
+ * first use (the exported `provider` is a lazy proxy, so this fires on the first `chat()` call,
9
+ * not at bond/module-load time) — it never silently sends an empty key.
10
+ *
11
+ * **Error message disambiguation**: a plain 400 that ISN'T a context-length error (bad param,
12
+ * malformed tool schema) gets its own non-retryable message distinct from the generic
13
+ * "AI service error. Please try again." used for retryable failures.
14
+ *
15
+ * @module
16
+ */
17
+ export * from './browser-guard.js';
18
+ export * from './provider.js';
19
+ export * from './secrets.js';
20
+ export * from './types.js';
21
+ import type { AIProvider } from '@molecule/api-ai';
22
+ /**
23
+ * The provider implementation.
24
+ */
25
+ export declare const provider: AIProvider;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAE1B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAMlD;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,UAUrB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * MiniMax AI provider for molecule.dev.
3
+ *
4
+ * @remarks
5
+ * Config: `MINIMAX_API_KEY` (SERVER-side only) plus an optional default model id/base URL.
6
+ *
7
+ * **Missing `MINIMAX_API_KEY` fails fast**: the provider throws naming the exact env var on
8
+ * first use (the exported `provider` is a lazy proxy, so this fires on the first `chat()` call,
9
+ * not at bond/module-load time) — it never silently sends an empty key.
10
+ *
11
+ * **Error message disambiguation**: a plain 400 that ISN'T a context-length error (bad param,
12
+ * malformed tool schema) gets its own non-retryable message distinct from the generic
13
+ * "AI service error. Please try again." used for retryable failures.
14
+ *
15
+ * @module
16
+ */
17
+ export * from './browser-guard.js';
18
+ export * from './provider.js';
19
+ export * from './secrets.js';
20
+ export * from './types.js';
21
+ import { createProvider } from './provider.js';
22
+ /** Lazily-initialized provider singleton. Defers creation until first use so that env vars / secrets are resolved. */
23
+ let _provider = null;
24
+ /**
25
+ * The provider implementation.
26
+ */
27
+ export const provider = new Proxy({}, {
28
+ get(_, prop, receiver) {
29
+ if (!_provider)
30
+ _provider = createProvider();
31
+ return Reflect.get(_provider, prop, receiver);
32
+ },
33
+ // set trap: methods run with `this` bound to the proxy — without it, instance-state writes land on the dummy target and are lost (see api-push-notifications-web-push)
34
+ set(_, prop, value) {
35
+ if (!_provider)
36
+ _provider = createProvider();
37
+ return Reflect.set(_provider, prop, value);
38
+ },
39
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * MiniMax implementation of AIProvider.
3
+ *
4
+ * Uses the MiniMax API (OpenAI-compatible) for streaming chat completions with tool use.
5
+ *
6
+ * @module
7
+ */
8
+ import type { AIProvider } from '@molecule/api-ai';
9
+ import './secrets.js';
10
+ import type { MiniMaxConfig } from './types.js';
11
+ /**
12
+ * Creates a MiniMax AI provider instance.
13
+ *
14
+ * @param config - MiniMax-specific configuration (API key, model, max tokens, base URL).
15
+ * @returns An `AIProvider` backed by the MiniMax Chat Completions API.
16
+ */
17
+ export declare function createProvider(config?: MiniMaxConfig): AIProvider;
18
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EACV,UAAU,EAOX,MAAM,kBAAkB,CAAA;AASzB,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAymB/C;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,UAAU,CAEjE"}
@@ -0,0 +1,576 @@
1
+ /**
2
+ * MiniMax implementation of AIProvider.
3
+ *
4
+ * Uses the MiniMax API (OpenAI-compatible) for streaming chat completions with tool use.
5
+ *
6
+ * @module
7
+ */
8
+ import { getLogger } from '@molecule/api-bond';
9
+ import { t } from '@molecule/api-i18n';
10
+ const logger = getLogger();
11
+ // Side-effect import: registers this bond's secret definitions so the
12
+ // runtime registry is populated even when provider.js is imported directly
13
+ // (not through the package barrel).
14
+ import './secrets.js';
15
+ /**
16
+ * Whether a model id is a MiniMax M3-family model. Only M3 accepts the
17
+ * `thinking: {type: "adaptive" | "disabled"}` control — M2.x thinking is
18
+ * always on and cannot be configured, and sending the param there is invalid.
19
+ *
20
+ * @param model - The model id (catalog `minimax-m3` or native `MiniMax-M3`).
21
+ * @returns `true` for M3-family model ids.
22
+ */
23
+ function isM3Family(model) {
24
+ return /^minimax-m3/i.test(model);
25
+ }
26
+ /**
27
+ * MiniMax AI provider that implements the `AIProvider` interface
28
+ * using MiniMax's OpenAI-compatible Chat Completions API with support
29
+ * for streaming, tool use, and reasoning.
30
+ */
31
+ class MiniMaxAIProvider {
32
+ name = 'minimax';
33
+ apiKey;
34
+ defaultModel;
35
+ maxTokens;
36
+ baseUrl;
37
+ completionsPath;
38
+ modelMap;
39
+ onRateLimit;
40
+ constructor(config = {}) {
41
+ this.apiKey = config.apiKey ?? process.env.MINIMAX_API_KEY ?? '';
42
+ this.defaultModel = config.defaultModel ?? 'minimax-m3';
43
+ this.maxTokens = config.maxTokens ?? 4096;
44
+ this.completionsPath =
45
+ config.completionsPath ?? process.env.MINIMAX_COMPLETIONS_PATH ?? '/v1/chat/completions';
46
+ this.modelMap = config.modelMap ?? {};
47
+ this.onRateLimit = config.onRateLimit;
48
+ // `api.minimax.io` is MiniMax's INTERNATIONAL host. The previous default,
49
+ // `api.minimax.chat`, rejected a valid international key with
50
+ // `invalid api key (2049)` (401) — MiniMax scopes keys per host, so a key
51
+ // minted on one region never authenticates against the other. That read as
52
+ // a bad key for as long as it was wrong; it was the URL. Mainland-China
53
+ // deployments point MINIMAX_BASE_URL at `https://api.minimaxi.com`.
54
+ this.baseUrl = config.baseUrl ?? process.env.MINIMAX_BASE_URL ?? 'https://api.minimax.io';
55
+ // Fail fast with an actionable local error rather than a cryptic 401 on the
56
+ // first request. The default `provider` export constructs lazily on first
57
+ // use (see index.ts), so this surfaces the moment the provider is actually
58
+ // used, not at bond/module-load time.
59
+ if (!this.apiKey) {
60
+ throw new Error('MINIMAX_API_KEY is not set. Add it to your environment to use the MiniMax AI provider.');
61
+ }
62
+ }
63
+ /**
64
+ * Sends a chat request and yields streamed events (text chunks, tool use, done/error).
65
+ *
66
+ * @param params - Chat parameters including messages, model, system prompt, and tools.
67
+ * @yields {ChatEvent} Chat events including text chunks, tool use requests, done signals, and errors.
68
+ */
69
+ async *chat(params) {
70
+ // Canonical catalog id (used everywhere else); translate to the upstream's
71
+ // id only for the outbound request body via `modelMap`.
72
+ const canonicalModel = params.model ?? this.defaultModel;
73
+ const model = this.modelMap[canonicalModel] ?? canonicalModel;
74
+ const maxTokens = params.maxTokens ?? this.maxTokens;
75
+ const messages = this.formatMessages(params.messages, params.system, params.cacheControl);
76
+ const body = {
77
+ // Abuse attribution (see ChatParams.endUserId): OpenAI-compatible APIs
78
+ // scope enforcement by `user`, so an abusive tenant can be actioned
79
+ // individually instead of the org key that serves everyone. The value is
80
+ // the caller's opaque hash — never derived or logged here.
81
+ ...(params.endUserId ? { user: params.endUserId } : {}),
82
+ model,
83
+ max_completion_tokens: maxTokens,
84
+ messages,
85
+ stream: params.stream !== false,
86
+ ...(params.stream !== false ? { stream_options: { include_usage: true } } : {}),
87
+ };
88
+ // Tools: merge custom tools (function format) and server tools
89
+ const functions = params.tools?.length ? this.formatTools(params.tools) : [];
90
+ const serverTools = (params.serverTools ?? []).map((st) => ({ ...st }));
91
+ const allTools = [...functions, ...serverTools];
92
+ if (allTools.length > 0) {
93
+ body.tools = allTools;
94
+ }
95
+ // MiniMax's native API has no reasoning_effort / thinking budget. M3 takes
96
+ // `thinking: {type: "adaptive" | "disabled"}` (the OpenAI-compatible
97
+ // endpoint defaults to adaptive when omitted); M2.x thinking is always on
98
+ // and takes no param. Synthase runs M3 as a non-thinking executor (like
99
+ // DeepSeek), so explicitly disable unless thinking was requested.
100
+ if (isM3Family(model)) {
101
+ body.thinking = { type: params.thinking ? 'adaptive' : 'disabled' };
102
+ }
103
+ // Keep thinking out of the visible message: with reasoning_split, thinking
104
+ // arrives in `reasoning_content` (parsed below) instead of inline
105
+ // <think>…</think> text inside `content`.
106
+ body.reasoning_split = true;
107
+ if (!params.thinking && params.temperature !== undefined) {
108
+ body.temperature = params.temperature;
109
+ }
110
+ const headers = {
111
+ 'Content-Type': 'application/json',
112
+ Authorization: `Bearer ${this.apiKey}`,
113
+ };
114
+ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
115
+ const signal = params.signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT_MS);
116
+ // Retry with exponential backoff for rate limits (429) and overloaded (503)
117
+ const MAX_RETRIES = 3;
118
+ let response = null;
119
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
120
+ response = await fetch(`${this.baseUrl}${this.completionsPath}`, {
121
+ method: 'POST',
122
+ headers,
123
+ body: JSON.stringify(body),
124
+ signal,
125
+ });
126
+ if (response.status === 429 || response.status === 503) {
127
+ const willRetry = attempt < MAX_RETRIES;
128
+ // Retry-After is equally-valid as delta-seconds or an HTTP-date;
129
+ // parseInt on the date form yields NaN, degrading the backoff to a
130
+ // ~0ms retry against an already rate-limiting API. Guard it.
131
+ const retryAfter = response.headers.get('retry-after');
132
+ const parsedRetryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : NaN;
133
+ const hasRetryAfter = Number.isFinite(parsedRetryAfterSeconds) && parsedRetryAfterSeconds >= 0;
134
+ // Additive jitter (<500ms): concurrent callers rejected together must
135
+ // not sleep identical delays and re-arrive as the same burst.
136
+ const delayMs = willRetry
137
+ ? (hasRetryAfter
138
+ ? Math.min(parsedRetryAfterSeconds * 1000, 60_000)
139
+ : Math.min(1000 * 2 ** attempt, 30_000)) + Math.floor(Math.random() * 500)
140
+ : 0;
141
+ try {
142
+ this.onRateLimit?.({
143
+ provider: this.name,
144
+ model,
145
+ status: response.status,
146
+ attempt: attempt + 1,
147
+ willRetry,
148
+ retryInMs: delayMs,
149
+ ...(hasRetryAfter ? { retryAfterSeconds: parsedRetryAfterSeconds } : {}),
150
+ });
151
+ }
152
+ catch (error) {
153
+ // Host-app telemetry; its failure must never break the request.
154
+ logger.warn('onRateLimit callback threw', { error });
155
+ }
156
+ if (willRetry) {
157
+ logger.warn('MiniMax API rate limited, retrying', {
158
+ status: response.status,
159
+ attempt: attempt + 1,
160
+ delayMs,
161
+ });
162
+ await new Promise((resolve) => {
163
+ const timer = setTimeout(resolve, delayMs);
164
+ signal.addEventListener('abort', () => {
165
+ clearTimeout(timer);
166
+ resolve();
167
+ }, { once: true });
168
+ });
169
+ if (signal.aborted)
170
+ break;
171
+ continue;
172
+ }
173
+ }
174
+ break;
175
+ }
176
+ if (!response.ok) {
177
+ const errorBody = await response.text();
178
+ let detail = `HTTP ${response.status}`;
179
+ try {
180
+ const parsed = JSON.parse(errorBody);
181
+ if (parsed.error?.message)
182
+ detail = parsed.error.message;
183
+ }
184
+ catch (_error) {
185
+ // JSON.parse of error body failed — fall back to raw text; parse failure is not actionable
186
+ if (errorBody.length > 0 && errorBody.length < 200)
187
+ detail = errorBody;
188
+ }
189
+ logger.error('MiniMax API error', { status: response.status, detail, errorBody });
190
+ const clientMessage = response.status === 429
191
+ ? 'AI rate limit exceeded. Please try again shortly.'
192
+ : response.status === 401
193
+ ? 'AI service configuration error.'
194
+ : response.status === 400 &&
195
+ /prompt is too long|too many tokens|token.*limit|context.*length/i.test(detail)
196
+ ? "Conversation too long for the model's context window. Use /compact to free space, or start a new conversation."
197
+ : response.status === 400
198
+ ? 'AI request was invalid — check the model and request parameters.'
199
+ : response.status === 503
200
+ ? 'AI service is temporarily overloaded. Please try again in a moment.'
201
+ : 'AI service error. Please try again.';
202
+ yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' };
203
+ return;
204
+ }
205
+ if (params.stream === false) {
206
+ const data = (await response.json());
207
+ yield* this.parseNonStreamingResponse(data);
208
+ return;
209
+ }
210
+ yield* this.parseStreamingResponse(response);
211
+ }
212
+ /**
213
+ * Converts internal `ChatMessage` objects to the OpenAI-compatible message format.
214
+ * System prompt is prepended as a system role message.
215
+ * MiniMax does not support vision/images, so image blocks are skipped.
216
+ *
217
+ * @param messages - The chat messages to format.
218
+ * @param system - Optional system prompt to prepend.
219
+ * @param cacheControl - Optional cache hint for the system prompt block.
220
+ * @param cacheControl.type - Ephemeral cache policy label expected by MiniMax.
221
+ * @returns The formatted messages array for the MiniMax API.
222
+ */
223
+ formatMessages(messages, system, cacheControl) {
224
+ const formatted = [];
225
+ if (system) {
226
+ if (cacheControl) {
227
+ formatted.push({
228
+ role: 'system',
229
+ content: [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }],
230
+ });
231
+ }
232
+ else {
233
+ formatted.push({ role: 'system', content: system });
234
+ }
235
+ }
236
+ for (const m of messages) {
237
+ if (m.role === 'system')
238
+ continue; // handled above
239
+ if (typeof m.content === 'string') {
240
+ formatted.push({ role: m.role, content: m.content });
241
+ continue;
242
+ }
243
+ // Content blocks — convert to OpenAI format
244
+ const blocks = m.content;
245
+ const parts = [];
246
+ const toolCalls = [];
247
+ const toolResults = [];
248
+ for (const block of blocks) {
249
+ switch (block.type) {
250
+ case 'text':
251
+ parts.push({ type: 'text', text: block.text });
252
+ break;
253
+ case 'image':
254
+ // MiniMax does not support vision/images — skip image blocks
255
+ break;
256
+ case 'tool_use':
257
+ toolCalls.push({
258
+ id: block.id,
259
+ type: 'function',
260
+ function: { name: block.name, arguments: JSON.stringify(block.input) },
261
+ });
262
+ break;
263
+ case 'tool_result':
264
+ toolResults.push({
265
+ role: 'tool',
266
+ tool_call_id: block.tool_use_id,
267
+ content: typeof block.content === 'string' ? block.content : JSON.stringify(block.content),
268
+ });
269
+ break;
270
+ default:
271
+ // document, audio, video — unsupported, skip
272
+ break;
273
+ }
274
+ }
275
+ if (toolResults.length > 0) {
276
+ // Tool results are separate messages in OpenAI format
277
+ for (const tr of toolResults) {
278
+ formatted.push(tr);
279
+ }
280
+ }
281
+ else if (toolCalls.length > 0) {
282
+ // Assistant message with tool calls
283
+ formatted.push({
284
+ role: 'assistant',
285
+ content: parts.length > 0 ? parts : null,
286
+ tool_calls: toolCalls,
287
+ });
288
+ }
289
+ else {
290
+ formatted.push({
291
+ role: m.role,
292
+ content: parts.length === 1 && parts[0].type === 'text' ? parts[0].text : parts,
293
+ });
294
+ }
295
+ }
296
+ return formatted;
297
+ }
298
+ /**
299
+ * Converts internal `AITool` definitions to the OpenAI function calling format.
300
+ *
301
+ * @param tools - The AI tool definitions to format.
302
+ * @returns The formatted tools array for the MiniMax API.
303
+ */
304
+ formatTools(tools) {
305
+ return tools.map((tool) => ({
306
+ type: 'function',
307
+ function: {
308
+ name: tool.name,
309
+ description: tool.description,
310
+ parameters: tool.parameters,
311
+ },
312
+ }));
313
+ }
314
+ /**
315
+ * Parses a non-streaming OpenAI-compatible response into `ChatEvent` objects.
316
+ *
317
+ * @param data - The raw API response data to parse.
318
+ * @yields {ChatEvent} Chat events parsed from the response.
319
+ */
320
+ *parseNonStreamingResponse(data) {
321
+ const choices = data.choices;
322
+ if (choices?.length) {
323
+ const message = choices[0].message;
324
+ if (message) {
325
+ // Reasoning/thinking content
326
+ if (message.reasoning_content && typeof message.reasoning_content === 'string') {
327
+ yield { type: 'thinking', content: message.reasoning_content };
328
+ }
329
+ if (message.content && typeof message.content === 'string') {
330
+ yield { type: 'text', content: message.content };
331
+ }
332
+ const toolCalls = message.tool_calls;
333
+ if (toolCalls) {
334
+ for (const tc of toolCalls) {
335
+ const fn = tc.function;
336
+ let input = {};
337
+ try {
338
+ input = JSON.parse(fn.arguments);
339
+ }
340
+ catch (_error) {
341
+ // Fall back to empty object — malformed tool arguments are non-fatal
342
+ }
343
+ yield {
344
+ type: 'tool_use',
345
+ id: tc.id,
346
+ name: fn.name,
347
+ input,
348
+ };
349
+ }
350
+ }
351
+ }
352
+ }
353
+ const usage = data.usage;
354
+ // prompt_tokens INCLUDES cached tokens on OpenAI-compatible APIs — report
355
+ // the cached portion separately (cacheReadPricePerMTok) and only the fresh
356
+ // remainder as inputTokens, matching the other bonds' semantics.
357
+ const cachedTokens = usage?.prompt_tokens_details?.cached_tokens ?? 0;
358
+ yield {
359
+ type: 'done',
360
+ usage: {
361
+ inputTokens: Math.max(0, (usage?.prompt_tokens ?? 0) - cachedTokens),
362
+ outputTokens: usage?.completion_tokens ?? 0,
363
+ ...(cachedTokens ? { cacheReadInputTokens: cachedTokens } : {}),
364
+ },
365
+ };
366
+ }
367
+ /**
368
+ * Parses a streaming SSE response from the MiniMax API (OpenAI-compatible format),
369
+ * yielding `ChatEvent` objects as they arrive.
370
+ *
371
+ * @param response - The fetch Response with an SSE body stream.
372
+ * @yields {ChatEvent} Chat events as they arrive from the SSE stream.
373
+ */
374
+ async *parseStreamingResponse(response) {
375
+ const reader = response.body?.getReader();
376
+ if (!reader) {
377
+ yield {
378
+ type: 'error',
379
+ message: t('ai.error.noResponseBody'),
380
+ errorKey: 'ai.error.noResponseBody',
381
+ };
382
+ return;
383
+ }
384
+ const decoder = new TextDecoder();
385
+ let buffer = '';
386
+ const state = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
387
+ // Track pending tool calls (accumulated across deltas)
388
+ const pendingTools = new Map();
389
+ try {
390
+ while (true) {
391
+ const { done, value } = await reader.read();
392
+ if (done)
393
+ break;
394
+ buffer += decoder.decode(value, { stream: true });
395
+ const lines = buffer.split('\n');
396
+ buffer = lines.pop() ?? '';
397
+ let yieldedContent = false;
398
+ for (const event of this.processSSELines(lines, pendingTools, state)) {
399
+ yieldedContent = true;
400
+ yield event;
401
+ // A mid-stream error (rate-limit/overload during high load, sent as a
402
+ // `data: {"error": {...}}` chunk) means the turn was truncated. Stop
403
+ // here and do NOT fall through to the trailing `done`, which would
404
+ // report the truncated turn as a successful completion and skip the
405
+ // consumer's overload/retry recovery.
406
+ if (event.type === 'error')
407
+ return;
408
+ }
409
+ // Signal liveness when the API sends data but no content events were produced
410
+ // (e.g., during extended reasoning with empty chunks or keepalive comments).
411
+ // This resets the consumer's stream timeout without forwarding to the client.
412
+ if (!yieldedContent) {
413
+ yield { type: 'keep_alive' };
414
+ }
415
+ }
416
+ // Flush any remaining data in the buffer after EOF
417
+ if (buffer.trim()) {
418
+ for (const event of this.processSSELines(buffer.split('\n'), pendingTools, state)) {
419
+ yield event;
420
+ if (event.type === 'error')
421
+ return;
422
+ }
423
+ }
424
+ // Emit any tool calls still pending after stream ends (safety net for missing finish_reason)
425
+ if (pendingTools.size > 0) {
426
+ for (const [, pending] of pendingTools) {
427
+ let input = {};
428
+ try {
429
+ input = JSON.parse(pending.args);
430
+ }
431
+ catch (_error) {
432
+ // Fall back to empty object — incomplete args at stream end are non-fatal
433
+ }
434
+ yield { type: 'tool_use', id: pending.id, name: pending.name, input };
435
+ }
436
+ pendingTools.clear();
437
+ }
438
+ }
439
+ finally {
440
+ reader.releaseLock();
441
+ }
442
+ // See the non-streaming path: cached tokens are reported separately and
443
+ // subtracted from inputTokens (prompt_tokens includes them).
444
+ yield {
445
+ type: 'done',
446
+ usage: {
447
+ inputTokens: Math.max(0, state.inputTokens - state.cacheReadTokens),
448
+ outputTokens: state.outputTokens,
449
+ ...(state.cacheReadTokens ? { cacheReadInputTokens: state.cacheReadTokens } : {}),
450
+ },
451
+ };
452
+ }
453
+ /**
454
+ * Processes an array of SSE lines from the MiniMax streaming response, yielding
455
+ * ChatEvent objects for text, thinking, tool use, and tool completion.
456
+ *
457
+ * @param lines - Raw SSE lines to process.
458
+ * @param pendingTools - Mutable map tracking tool call deltas accumulated across chunks.
459
+ * @param state - Mutable token usage counters.
460
+ * @yields {ChatEvent} Chat events extracted from the SSE lines.
461
+ */
462
+ *processSSELines(lines, pendingTools, state) {
463
+ for (const line of lines) {
464
+ if (!line.startsWith('data: '))
465
+ continue;
466
+ const json = line.slice(6).trim();
467
+ if (json === '[DONE]')
468
+ continue;
469
+ try {
470
+ const event = JSON.parse(json);
471
+ // A mid-stream error arrives as a `data: {"error": {...}}` chunk (no
472
+ // `choices`) — most importantly rate-limit/overload during high load.
473
+ // Without this it matches no branch below and is silently dropped, so the
474
+ // stream falls through to a misleading `done` and the truncated turn reads
475
+ // as a successful completion. Surface it as a real error event (also
476
+ // satisfies the no-silent-swallow rule).
477
+ const streamError = event.error;
478
+ if (streamError) {
479
+ const detail = `${streamError.code ?? streamError.type ?? ''} ${streamError.message ?? ''}`;
480
+ logger.error('MiniMax streaming error event', {
481
+ type: streamError.type,
482
+ code: streamError.code,
483
+ message: streamError.message,
484
+ });
485
+ const clientMessage = /overload|capacity|503|529/i.test(detail)
486
+ ? 'AI service is temporarily overloaded. Please try again in a moment.'
487
+ : /rate.?limit|429|quota/i.test(detail)
488
+ ? 'AI rate limit exceeded. Please try again shortly.'
489
+ : 'AI service error. Please try again.';
490
+ yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' };
491
+ continue;
492
+ }
493
+ // Usage info (may appear in the final chunk)
494
+ const usage = event.usage;
495
+ if (usage) {
496
+ if (usage.prompt_tokens)
497
+ state.inputTokens = usage.prompt_tokens;
498
+ if (usage.completion_tokens)
499
+ state.outputTokens = usage.completion_tokens;
500
+ if (usage.prompt_tokens_details?.cached_tokens)
501
+ state.cacheReadTokens = usage.prompt_tokens_details.cached_tokens;
502
+ }
503
+ const choices = event.choices;
504
+ if (!choices?.length)
505
+ continue;
506
+ const choice = choices[0];
507
+ const delta = choice.delta;
508
+ if (!delta)
509
+ continue;
510
+ // Reasoning/thinking content
511
+ if (delta.reasoning_content && typeof delta.reasoning_content === 'string') {
512
+ yield { type: 'thinking', content: delta.reasoning_content };
513
+ }
514
+ // Text content
515
+ if (delta.content && typeof delta.content === 'string') {
516
+ yield { type: 'text', content: delta.content };
517
+ }
518
+ // Tool calls (accumulated across deltas)
519
+ const toolCalls = delta.tool_calls;
520
+ if (toolCalls) {
521
+ for (const tc of toolCalls) {
522
+ const idx = tc.index;
523
+ const fn = tc.function;
524
+ if (!pendingTools.has(idx)) {
525
+ pendingTools.set(idx, {
526
+ id: tc.id ?? '',
527
+ name: fn?.name ? fn.name : '',
528
+ args: '',
529
+ });
530
+ }
531
+ const pending = pendingTools.get(idx);
532
+ if (tc.id)
533
+ pending.id = tc.id;
534
+ if (fn?.name)
535
+ pending.name = fn.name;
536
+ if (fn?.arguments)
537
+ pending.args += fn.arguments;
538
+ }
539
+ }
540
+ // finish_reason signals completion
541
+ const finishReason = choice.finish_reason;
542
+ if (finishReason === 'tool_calls' || finishReason === 'stop') {
543
+ // Emit any accumulated tool calls
544
+ for (const [, pending] of pendingTools) {
545
+ let input = {};
546
+ try {
547
+ input = JSON.parse(pending.args);
548
+ }
549
+ catch (_error) {
550
+ // Fall back to empty object — malformed tool arguments are non-fatal
551
+ }
552
+ yield {
553
+ type: 'tool_use',
554
+ id: pending.id,
555
+ name: pending.name,
556
+ input,
557
+ };
558
+ }
559
+ pendingTools.clear();
560
+ }
561
+ }
562
+ catch (error) {
563
+ logger.debug('Skipping malformed SSE JSON line', { json, error });
564
+ }
565
+ }
566
+ }
567
+ }
568
+ /**
569
+ * Creates a MiniMax AI provider instance.
570
+ *
571
+ * @param config - MiniMax-specific configuration (API key, model, max tokens, base URL).
572
+ * @returns An `AIProvider` backed by the MiniMax Chat Completions API.
573
+ */
574
+ export function createProvider(config) {
575
+ return new MiniMaxAIProvider(config);
576
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * MiniMax secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import type { SecretDefinition } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the MiniMax AI bond. */
15
+ export declare const aiMinimaxSecretDefinitions: SecretDefinition[];
16
+ //# sourceMappingURL=secrets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,0DAA0D;AAC1D,eAAO,MAAM,0BAA0B,EAAE,gBAAgB,EAOxD,CAAA"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * MiniMax secret definitions — self-registered at import time so the
3
+ * runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
4
+ * configuration reports and actionable "not configured" errors.
5
+ *
6
+ * Content is derived MECHANICALLY from this package's mlcl registry secrets
7
+ * entry (label/instructions/setupUrl/example) via the fleet formula, so
8
+ * packages sharing a key register byte-identical definitions and
9
+ * registration order never matters.
10
+ *
11
+ * @module
12
+ */
13
+ import { registerSecrets } from '@molecule/api-secrets';
14
+ /** Secret definitions required by the MiniMax AI bond. */
15
+ export const aiMinimaxSecretDefinitions = [
16
+ {
17
+ key: 'MINIMAX_API_KEY',
18
+ description: 'MiniMax API key — Create an interface key in the MiniMax platform user center.',
19
+ helpUrl: 'https://platform.minimax.io/',
20
+ required: true,
21
+ },
22
+ ];
23
+ registerSecrets(aiMinimaxSecretDefinitions);
@@ -0,0 +1,48 @@
1
+ /**
2
+ * MiniMax AI provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ import type { AiRateLimitCallback } from '@molecule/api-ai';
7
+ /**
8
+ * Configuration for MiniMax.
9
+ */
10
+ export interface MiniMaxConfig {
11
+ /** Called on each rate-limited/overloaded upstream response, before any retry sleep. */
12
+ onRateLimit?: AiRateLimitCallback;
13
+ /** API key. Defaults to MINIMAX_API_KEY env var. */
14
+ apiKey?: string;
15
+ /** Default model. Defaults to 'minimax-m3'. */
16
+ defaultModel?: string;
17
+ /** Maximum tokens for completions. */
18
+ maxTokens?: number;
19
+ /** Base URL override (for proxies). Defaults to 'https://api.minimax.io' (MiniMax's INTERNATIONAL host; use 'https://api.minimaxi.com' for mainland China — keys are scoped per host). */
20
+ baseUrl?: string;
21
+ /**
22
+ * Chat-completions path appended to {@link baseUrl}. Defaults to
23
+ * `/v1/chat/completions` (MiniMax-direct puts the version in the path). Set
24
+ * this when the same open-weight model is served by a US OpenAI-compatible
25
+ * host whose version prefix lives in the base URL instead — e.g. DeepInfra:
26
+ * `baseUrl='https://api.deepinfra.com/v1/openai'` + `completionsPath='/chat/completions'`.
27
+ */
28
+ completionsPath?: string;
29
+ /**
30
+ * Optional catalog-id → upstream-model-id map, applied to the outbound request
31
+ * ONLY. Lets a US OpenAI-compatible host (DeepInfra) receive its namespaced id
32
+ * (`MiniMaxAI/MiniMax-M3`) while the rest of the platform — pricing, cost
33
+ * ceilings, display — keeps using the canonical catalog id (`minimax-m3`). An
34
+ * id not in the map passes through unchanged.
35
+ */
36
+ modelMap?: Record<string, string>;
37
+ }
38
+ /**
39
+ * Process Env interface.
40
+ */
41
+ export interface ProcessEnv {
42
+ MINIMAX_API_KEY: string;
43
+ /** Base URL override (for credential brokers / gateways / US OpenAI-compatible hosts). */
44
+ MINIMAX_BASE_URL?: string;
45
+ /** Chat-completions path override (see {@link MiniMaxConfig.completionsPath}). */
46
+ MINIMAX_COMPLETIONS_PATH?: string;
47
+ }
48
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAA;AAE3D;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,wFAAwF;IACxF,WAAW,CAAC,EAAE,mBAAmB,CAAA;IACjC,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,sCAAsC;IACtC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,0LAA0L;IAC1L,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,eAAe,EAAE,MAAM,CAAA;IACvB,0FAA0F;IAC1F,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,kFAAkF;IAClF,wBAAwB,CAAC,EAAE,MAAM,CAAA;CAClC"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * MiniMax AI provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@molecule/api-ai-minimax",
3
+ "version": "1.0.0",
4
+ "description": "MiniMax AI provider for molecule.dev",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "ai",
25
+ "minimax"
26
+ ],
27
+ "license": "Apache-2.0",
28
+ "devDependencies": {
29
+ "@molecule/api-ai": "1.0.0",
30
+ "@molecule/api-bond": "1.0.0",
31
+ "@types/node": "26.1.2",
32
+ "typescript": "6.0.3",
33
+ "vitest": "4.1.10"
34
+ },
35
+ "peerDependencies": {
36
+ "@molecule/api-ai": "^1.0.0",
37
+ "@molecule/api-bond": "^1.0.0",
38
+ "@molecule/api-i18n": "^1.0.0",
39
+ "@molecule/api-secrets": "^1.0.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@molecule/api-ai": {
43
+ "optional": true
44
+ }
45
+ }
46
+ }