@providerprotocol/ai 0.0.37 → 0.0.39

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.
Files changed (85) hide show
  1. package/README.md +94 -3
  2. package/dist/anthropic/index.d.ts +3 -2
  3. package/dist/cerebras/index.d.ts +3 -2
  4. package/dist/chunk-3Q5VELKG.js +124 -0
  5. package/dist/chunk-3Q5VELKG.js.map +1 -0
  6. package/dist/{chunk-LTEMH3CI.js → chunk-5XPRVUOK.js} +6 -4
  7. package/dist/{chunk-LTEMH3CI.js.map → chunk-5XPRVUOK.js.map} +1 -1
  8. package/dist/chunk-7ULSRWDH.js +83 -0
  9. package/dist/chunk-7ULSRWDH.js.map +1 -0
  10. package/dist/{chunk-YQLR3XOA.js → chunk-BIBMNP7Y.js} +1 -75
  11. package/dist/chunk-BIBMNP7Y.js.map +1 -0
  12. package/dist/{chunk-7GTWHZY2.js → chunk-IDZR4ROP.js} +5 -3
  13. package/dist/{chunk-7GTWHZY2.js.map → chunk-IDZR4ROP.js.map} +1 -1
  14. package/dist/{chunk-4RX4VQCB.js → chunk-IIMTP3XC.js} +2 -2
  15. package/dist/{chunk-ZRVNAET3.js → chunk-KNBODIQU.js} +6 -3
  16. package/dist/chunk-KNBODIQU.js.map +1 -0
  17. package/dist/{chunk-FYSZFIZS.js → chunk-O32SBS6S.js} +5 -3
  18. package/dist/{chunk-FYSZFIZS.js.map → chunk-O32SBS6S.js.map} +1 -1
  19. package/dist/{chunk-IK6NRCW5.js → chunk-RDC5GYST.js} +7 -7
  20. package/dist/{chunk-5IWHCXKN.js → chunk-SAMIK4WZ.js} +2 -2
  21. package/dist/{chunk-EPB3GQNL.js → chunk-U6M3MXNI.js} +11 -2
  22. package/dist/chunk-U6M3MXNI.js.map +1 -0
  23. package/dist/{chunk-2YXFLRQ6.js → chunk-WNB5PSY6.js} +2 -2
  24. package/dist/{chunk-CRP6Y7NF.js → chunk-ZDYEDI2A.js} +2 -2
  25. package/dist/{embedding-CwZ1ZNWv.d.ts → embedding-iNQCeXfk.d.ts} +1 -1
  26. package/dist/google/index.d.ts +3 -2
  27. package/dist/groq/index.d.ts +3 -2
  28. package/dist/http/index.d.ts +4 -3
  29. package/dist/{image-stream-CeQHtjxS.d.ts → image-stream-ARno6XlS.d.ts} +1 -1
  30. package/dist/index.d.ts +8 -7
  31. package/dist/index.js +11 -2
  32. package/dist/index.js.map +1 -1
  33. package/dist/{llm-DS_-l71X.d.ts → llm-CZqlijjK.d.ts} +16 -9
  34. package/dist/middleware/logging/index.d.ts +3 -2
  35. package/dist/middleware/parsed-object/index.d.ts +3 -2
  36. package/dist/middleware/persistence/index.d.ts +3 -2
  37. package/dist/middleware/pubsub/index.d.ts +5 -4
  38. package/dist/middleware/pubsub/index.js +49 -3
  39. package/dist/middleware/pubsub/index.js.map +1 -1
  40. package/dist/middleware/pubsub/server/express/index.d.ts +3 -2
  41. package/dist/middleware/pubsub/server/express/index.js +2 -2
  42. package/dist/middleware/pubsub/server/fastify/index.d.ts +3 -2
  43. package/dist/middleware/pubsub/server/fastify/index.js +2 -2
  44. package/dist/middleware/pubsub/server/h3/index.d.ts +3 -2
  45. package/dist/middleware/pubsub/server/h3/index.js +2 -2
  46. package/dist/middleware/pubsub/server/index.d.ts +3 -2
  47. package/dist/middleware/pubsub/server/index.js +5 -5
  48. package/dist/middleware/pubsub/server/webapi/index.d.ts +3 -2
  49. package/dist/middleware/pubsub/server/webapi/index.js +2 -2
  50. package/dist/moonshot/index.d.ts +511 -0
  51. package/dist/moonshot/index.js +1090 -0
  52. package/dist/moonshot/index.js.map +1 -0
  53. package/dist/ollama/index.d.ts +3 -2
  54. package/dist/openai/index.d.ts +3 -2
  55. package/dist/openrouter/index.d.ts +3 -2
  56. package/dist/proxy/index.d.ts +5 -4
  57. package/dist/proxy/index.js +12 -10
  58. package/dist/proxy/index.js.map +1 -1
  59. package/dist/proxy/server/express/index.d.ts +5 -4
  60. package/dist/proxy/server/express/index.js +3 -2
  61. package/dist/proxy/server/fastify/index.d.ts +5 -4
  62. package/dist/proxy/server/fastify/index.js +3 -2
  63. package/dist/proxy/server/h3/index.d.ts +19 -17
  64. package/dist/proxy/server/h3/index.js +3 -2
  65. package/dist/proxy/server/index.d.ts +5 -4
  66. package/dist/proxy/server/index.js +9 -8
  67. package/dist/proxy/server/webapi/index.d.ts +5 -4
  68. package/dist/proxy/server/webapi/index.js +3 -2
  69. package/dist/responses/index.d.ts +3 -2
  70. package/dist/{retry-CgoBNa51.d.ts → retry-C1eJbEMV.d.ts} +1 -1
  71. package/dist/{stream-sXhBtWjl.d.ts → stream-DVVUIKpz.d.ts} +3 -416
  72. package/dist/tool-D22EhP5F.d.ts +507 -0
  73. package/dist/{types-Cr4F0tVy.d.ts → types-CyXF0J7C.d.ts} +16 -3
  74. package/dist/utils/index.d.ts +65 -1
  75. package/dist/utils/index.js +15 -1
  76. package/dist/xai/index.d.ts +3 -2
  77. package/package.json +22 -3
  78. package/dist/chunk-EPB3GQNL.js.map +0 -1
  79. package/dist/chunk-YQLR3XOA.js.map +0 -1
  80. package/dist/chunk-ZRVNAET3.js.map +0 -1
  81. /package/dist/{chunk-4RX4VQCB.js.map → chunk-IIMTP3XC.js.map} +0 -0
  82. /package/dist/{chunk-IK6NRCW5.js.map → chunk-RDC5GYST.js.map} +0 -0
  83. /package/dist/{chunk-5IWHCXKN.js.map → chunk-SAMIK4WZ.js.map} +0 -0
  84. /package/dist/{chunk-2YXFLRQ6.js.map → chunk-WNB5PSY6.js.map} +0 -0
  85. /package/dist/{chunk-CRP6Y7NF.js.map → chunk-ZDYEDI2A.js.map} +0 -0
@@ -0,0 +1,1090 @@
1
+ import {
2
+ parseSSEStream
3
+ } from "../chunk-PMK5LZ5Z.js";
4
+ import {
5
+ parseJsonResponse
6
+ } from "../chunk-TUTYMOBL.js";
7
+ import {
8
+ resolveApiKey
9
+ } from "../chunk-ARVM24K2.js";
10
+ import {
11
+ createProvider
12
+ } from "../chunk-JA3UZALR.js";
13
+ import {
14
+ doFetch,
15
+ doStreamFetch,
16
+ normalizeHttpError
17
+ } from "../chunk-SBGZJVTJ.js";
18
+ import {
19
+ StreamEventType,
20
+ objectDelta
21
+ } from "../chunk-MJI74VEJ.js";
22
+ import {
23
+ AssistantMessage,
24
+ generateId,
25
+ isAssistantMessage,
26
+ isToolResultMessage,
27
+ isUserMessage
28
+ } from "../chunk-WU4U6IHF.js";
29
+ import {
30
+ toError
31
+ } from "../chunk-GIDT7C6I.js";
32
+ import {
33
+ ErrorCode,
34
+ ModalityType,
35
+ UPPError
36
+ } from "../chunk-COS4ON4G.js";
37
+
38
+ // src/providers/moonshot/transform.ts
39
+ function normalizeSystem(system) {
40
+ if (system === void 0 || system === null) return void 0;
41
+ if (typeof system === "string") return system;
42
+ if (!Array.isArray(system)) {
43
+ throw new UPPError(
44
+ "System prompt must be a string or an array of text blocks",
45
+ ErrorCode.InvalidRequest,
46
+ "moonshot",
47
+ ModalityType.LLM
48
+ );
49
+ }
50
+ const texts = [];
51
+ for (const block of system) {
52
+ if (!block || typeof block !== "object" || !("text" in block)) {
53
+ throw new UPPError(
54
+ "System prompt array must contain objects with a text field",
55
+ ErrorCode.InvalidRequest,
56
+ "moonshot",
57
+ ModalityType.LLM
58
+ );
59
+ }
60
+ const textValue = block.text;
61
+ if (typeof textValue !== "string") {
62
+ throw new UPPError(
63
+ "System prompt text must be a string",
64
+ ErrorCode.InvalidRequest,
65
+ "moonshot",
66
+ ModalityType.LLM
67
+ );
68
+ }
69
+ if (textValue.length > 0) {
70
+ texts.push(textValue);
71
+ }
72
+ }
73
+ return texts.length > 0 ? texts.join("\n\n") : void 0;
74
+ }
75
+ function filterValidContent(content) {
76
+ return content.filter((c) => c && typeof c.type === "string");
77
+ }
78
+ function transformContentBlock(block) {
79
+ switch (block.type) {
80
+ case "text":
81
+ return { type: "text", text: block.text };
82
+ case "image": {
83
+ const imageBlock = block;
84
+ let url;
85
+ if (imageBlock.source.type === "base64") {
86
+ url = `data:${imageBlock.mimeType};base64,${imageBlock.source.data}`;
87
+ } else if (imageBlock.source.type === "url") {
88
+ url = imageBlock.source.url;
89
+ } else if (imageBlock.source.type === "bytes") {
90
+ const base64 = Buffer.from(imageBlock.source.data).toString("base64");
91
+ url = `data:${imageBlock.mimeType};base64,${base64}`;
92
+ } else {
93
+ throw new UPPError(
94
+ "Unknown image source type",
95
+ ErrorCode.InvalidRequest,
96
+ "moonshot",
97
+ ModalityType.LLM
98
+ );
99
+ }
100
+ return {
101
+ type: "image_url",
102
+ image_url: { url }
103
+ };
104
+ }
105
+ case "video": {
106
+ const videoBlock = block;
107
+ const base64 = Buffer.from(videoBlock.data).toString("base64");
108
+ const url = `data:${videoBlock.mimeType};base64,${base64}`;
109
+ return {
110
+ type: "video_url",
111
+ video_url: { url }
112
+ };
113
+ }
114
+ case "document":
115
+ throw new UPPError(
116
+ "Moonshot does not support inline document blocks. Use the /v1/files API to upload documents first.",
117
+ ErrorCode.InvalidRequest,
118
+ "moonshot",
119
+ ModalityType.LLM
120
+ );
121
+ case "audio":
122
+ throw new UPPError(
123
+ "Moonshot does not support audio input",
124
+ ErrorCode.InvalidRequest,
125
+ "moonshot",
126
+ ModalityType.LLM
127
+ );
128
+ default:
129
+ throw new UPPError(
130
+ `Unsupported content type: ${block.type}`,
131
+ ErrorCode.InvalidRequest,
132
+ "moonshot",
133
+ ModalityType.LLM
134
+ );
135
+ }
136
+ }
137
+ function transformMessage(message) {
138
+ if (isUserMessage(message)) {
139
+ const validContent = filterValidContent(message.content);
140
+ if (validContent.length === 1 && validContent[0]?.type === "text") {
141
+ return {
142
+ role: "user",
143
+ content: validContent[0].text
144
+ };
145
+ }
146
+ return {
147
+ role: "user",
148
+ content: validContent.map(transformContentBlock)
149
+ };
150
+ }
151
+ if (isAssistantMessage(message)) {
152
+ const validContent = filterValidContent(message.content);
153
+ const textContent = validContent.filter((c) => c.type === "text").map((c) => c.text).join("");
154
+ const moonshotMeta = message.metadata?.moonshot;
155
+ let reasoningContent = moonshotMeta?.reasoning_content;
156
+ if (!reasoningContent) {
157
+ const reasoningBlocks = validContent.filter(
158
+ (c) => c.type === "reasoning"
159
+ );
160
+ if (reasoningBlocks.length > 0) {
161
+ reasoningContent = reasoningBlocks.map((b) => b.text).join("\n");
162
+ }
163
+ }
164
+ const assistantMessage = {
165
+ role: "assistant",
166
+ content: textContent || null
167
+ };
168
+ if (reasoningContent) {
169
+ assistantMessage.reasoning_content = reasoningContent;
170
+ }
171
+ if (message.toolCalls && message.toolCalls.length > 0) {
172
+ assistantMessage.tool_calls = message.toolCalls.map((call) => ({
173
+ id: call.toolCallId,
174
+ type: "function",
175
+ function: {
176
+ name: call.toolName,
177
+ arguments: JSON.stringify(call.arguments)
178
+ }
179
+ }));
180
+ }
181
+ return assistantMessage;
182
+ }
183
+ if (isToolResultMessage(message)) {
184
+ const results = message.results.map((result) => ({
185
+ role: "tool",
186
+ tool_call_id: result.toolCallId,
187
+ content: typeof result.result === "string" ? result.result : JSON.stringify(result.result)
188
+ }));
189
+ return results[0] ?? null;
190
+ }
191
+ return null;
192
+ }
193
+ function transformToolResults(message) {
194
+ if (!isToolResultMessage(message)) {
195
+ const single = transformMessage(message);
196
+ return single ? [single] : [];
197
+ }
198
+ return message.results.map((result) => ({
199
+ role: "tool",
200
+ tool_call_id: result.toolCallId,
201
+ content: typeof result.result === "string" ? result.result : JSON.stringify(result.result)
202
+ }));
203
+ }
204
+ function transformMessages(messages, system) {
205
+ const result = [];
206
+ const normalizedSystem = normalizeSystem(system);
207
+ if (normalizedSystem) {
208
+ result.push({
209
+ role: "system",
210
+ content: normalizedSystem
211
+ });
212
+ }
213
+ for (const message of messages) {
214
+ if (isToolResultMessage(message)) {
215
+ const toolMessages = transformToolResults(message);
216
+ result.push(...toolMessages);
217
+ } else {
218
+ const transformed = transformMessage(message);
219
+ if (transformed) {
220
+ result.push(transformed);
221
+ }
222
+ }
223
+ }
224
+ return result;
225
+ }
226
+ function extractToolOptions(tool) {
227
+ const moonshotMeta = tool.metadata?.moonshot;
228
+ return { strict: moonshotMeta?.strict };
229
+ }
230
+ function transformTool(tool) {
231
+ const { strict } = extractToolOptions(tool);
232
+ return {
233
+ type: "function",
234
+ function: {
235
+ name: tool.name,
236
+ description: tool.description,
237
+ parameters: {
238
+ type: "object",
239
+ properties: tool.parameters.properties,
240
+ required: tool.parameters.required,
241
+ ...tool.parameters.additionalProperties !== void 0 ? { additionalProperties: tool.parameters.additionalProperties } : {}
242
+ },
243
+ ...strict !== void 0 ? { strict } : {}
244
+ }
245
+ };
246
+ }
247
+ function transformRequest(request, modelId) {
248
+ const params = request.params ?? {};
249
+ const { tools: paramsTools, ...restParams } = params;
250
+ const moonshotRequest = {
251
+ ...restParams,
252
+ model: modelId,
253
+ messages: transformMessages(request.messages, request.system)
254
+ };
255
+ const allTools = [];
256
+ if (paramsTools && paramsTools.length > 0) {
257
+ allTools.push(...paramsTools);
258
+ }
259
+ if (request.tools && request.tools.length > 0) {
260
+ allTools.push(...request.tools.map(transformTool));
261
+ }
262
+ if (allTools.length > 0) {
263
+ moonshotRequest.tools = allTools;
264
+ }
265
+ if (request.structure) {
266
+ const schema = {
267
+ type: "object",
268
+ properties: request.structure.properties,
269
+ required: request.structure.required,
270
+ ...request.structure.additionalProperties !== void 0 ? { additionalProperties: request.structure.additionalProperties } : { additionalProperties: false }
271
+ };
272
+ if (request.structure.description) {
273
+ schema.description = request.structure.description;
274
+ }
275
+ moonshotRequest.response_format = {
276
+ type: "json_schema",
277
+ json_schema: {
278
+ name: "json_response",
279
+ description: request.structure.description,
280
+ schema,
281
+ strict: true
282
+ }
283
+ };
284
+ }
285
+ return moonshotRequest;
286
+ }
287
+ function transformResponse(data) {
288
+ const choice = data.choices[0];
289
+ if (!choice) {
290
+ throw new UPPError(
291
+ "No choices in Moonshot response",
292
+ ErrorCode.InvalidResponse,
293
+ "moonshot",
294
+ ModalityType.LLM
295
+ );
296
+ }
297
+ const contentBlocks = [];
298
+ let structuredData;
299
+ if (choice.message.reasoning_content) {
300
+ contentBlocks.push({ type: "reasoning", text: choice.message.reasoning_content });
301
+ }
302
+ if (choice.message.content) {
303
+ contentBlocks.push({ type: "text", text: choice.message.content });
304
+ try {
305
+ structuredData = JSON.parse(choice.message.content);
306
+ } catch {
307
+ }
308
+ }
309
+ const toolCalls = [];
310
+ if (choice.message.tool_calls) {
311
+ for (const call of choice.message.tool_calls) {
312
+ let args = {};
313
+ try {
314
+ args = JSON.parse(call.function.arguments);
315
+ } catch {
316
+ }
317
+ toolCalls.push({
318
+ toolCallId: call.id,
319
+ toolName: call.function.name,
320
+ arguments: args
321
+ });
322
+ }
323
+ }
324
+ const message = new AssistantMessage(
325
+ contentBlocks,
326
+ toolCalls.length > 0 ? toolCalls : void 0,
327
+ {
328
+ id: data.id || generateId(),
329
+ metadata: {
330
+ moonshot: {
331
+ model: data.model,
332
+ finish_reason: choice.finish_reason,
333
+ system_fingerprint: data.system_fingerprint,
334
+ reasoning_content: choice.message.reasoning_content ?? void 0
335
+ }
336
+ }
337
+ }
338
+ );
339
+ const usage = {
340
+ inputTokens: data.usage.prompt_tokens,
341
+ outputTokens: data.usage.completion_tokens,
342
+ totalTokens: data.usage.total_tokens,
343
+ cacheReadTokens: data.usage.prompt_tokens_details?.cached_tokens ?? 0,
344
+ cacheWriteTokens: 0
345
+ };
346
+ let stopReason = "end_turn";
347
+ switch (choice.finish_reason) {
348
+ case "stop":
349
+ stopReason = "end_turn";
350
+ break;
351
+ case "length":
352
+ stopReason = "max_tokens";
353
+ break;
354
+ case "tool_calls":
355
+ stopReason = "tool_use";
356
+ break;
357
+ case "content_filter":
358
+ stopReason = "content_filter";
359
+ break;
360
+ }
361
+ return {
362
+ message,
363
+ usage,
364
+ stopReason,
365
+ data: structuredData
366
+ };
367
+ }
368
+ function createStreamState() {
369
+ return {
370
+ id: "",
371
+ model: "",
372
+ text: "",
373
+ reasoningText: "",
374
+ toolCalls: /* @__PURE__ */ new Map(),
375
+ finishReason: null,
376
+ inputTokens: 0,
377
+ outputTokens: 0,
378
+ cacheReadTokens: 0
379
+ };
380
+ }
381
+ function transformStreamEvent(chunk, state) {
382
+ const events = [];
383
+ if (chunk.id && !state.id) {
384
+ state.id = chunk.id;
385
+ events.push({ type: StreamEventType.MessageStart, index: 0, delta: {} });
386
+ }
387
+ if (chunk.model) {
388
+ state.model = chunk.model;
389
+ }
390
+ const choice = chunk.choices[0];
391
+ if (choice) {
392
+ if (choice.delta.reasoning_content) {
393
+ state.reasoningText += choice.delta.reasoning_content;
394
+ events.push({
395
+ type: StreamEventType.ReasoningDelta,
396
+ index: 0,
397
+ delta: { text: choice.delta.reasoning_content }
398
+ });
399
+ }
400
+ if (choice.delta.content) {
401
+ state.text += choice.delta.content;
402
+ events.push({
403
+ type: StreamEventType.TextDelta,
404
+ index: 0,
405
+ delta: { text: choice.delta.content }
406
+ });
407
+ }
408
+ if (choice.delta.tool_calls) {
409
+ for (const toolCallDelta of choice.delta.tool_calls) {
410
+ const index = toolCallDelta.index;
411
+ let toolCall = state.toolCalls.get(index);
412
+ if (!toolCall) {
413
+ toolCall = { id: "", name: "", arguments: "" };
414
+ state.toolCalls.set(index, toolCall);
415
+ }
416
+ if (toolCallDelta.id) {
417
+ toolCall.id = toolCallDelta.id;
418
+ }
419
+ if (toolCallDelta.function?.name) {
420
+ toolCall.name = toolCallDelta.function.name;
421
+ }
422
+ if (toolCallDelta.function?.arguments) {
423
+ toolCall.arguments += toolCallDelta.function.arguments;
424
+ events.push({
425
+ type: StreamEventType.ToolCallDelta,
426
+ index,
427
+ delta: {
428
+ toolCallId: toolCall.id,
429
+ toolName: toolCall.name,
430
+ argumentsJson: toolCallDelta.function.arguments
431
+ }
432
+ });
433
+ }
434
+ }
435
+ }
436
+ if (choice.finish_reason) {
437
+ state.finishReason = choice.finish_reason;
438
+ events.push({ type: StreamEventType.MessageStop, index: 0, delta: {} });
439
+ }
440
+ }
441
+ if (chunk.usage) {
442
+ state.inputTokens = chunk.usage.prompt_tokens;
443
+ state.outputTokens = chunk.usage.completion_tokens;
444
+ state.cacheReadTokens = chunk.usage.prompt_tokens_details?.cached_tokens ?? 0;
445
+ }
446
+ return events;
447
+ }
448
+ function buildResponseFromState(state) {
449
+ const contentBlocks = [];
450
+ let structuredData;
451
+ if (state.reasoningText) {
452
+ contentBlocks.push({ type: "reasoning", text: state.reasoningText });
453
+ }
454
+ if (state.text) {
455
+ contentBlocks.push({ type: "text", text: state.text });
456
+ try {
457
+ structuredData = JSON.parse(state.text);
458
+ } catch {
459
+ }
460
+ }
461
+ const toolCalls = [];
462
+ for (const [, toolCall] of state.toolCalls) {
463
+ let args = {};
464
+ if (toolCall.arguments) {
465
+ try {
466
+ args = JSON.parse(toolCall.arguments);
467
+ } catch {
468
+ }
469
+ }
470
+ toolCalls.push({
471
+ toolCallId: toolCall.id,
472
+ toolName: toolCall.name,
473
+ arguments: args
474
+ });
475
+ }
476
+ const messageId = state.id || generateId();
477
+ const message = new AssistantMessage(
478
+ contentBlocks,
479
+ toolCalls.length > 0 ? toolCalls : void 0,
480
+ {
481
+ id: messageId,
482
+ metadata: {
483
+ moonshot: {
484
+ model: state.model,
485
+ finish_reason: state.finishReason,
486
+ reasoning_content: state.reasoningText || void 0
487
+ }
488
+ }
489
+ }
490
+ );
491
+ const usage = {
492
+ inputTokens: state.inputTokens,
493
+ outputTokens: state.outputTokens,
494
+ totalTokens: state.inputTokens + state.outputTokens,
495
+ cacheReadTokens: state.cacheReadTokens,
496
+ cacheWriteTokens: 0
497
+ };
498
+ let stopReason = "end_turn";
499
+ switch (state.finishReason) {
500
+ case "stop":
501
+ stopReason = "end_turn";
502
+ break;
503
+ case "length":
504
+ stopReason = "max_tokens";
505
+ break;
506
+ case "tool_calls":
507
+ stopReason = "tool_use";
508
+ break;
509
+ case "content_filter":
510
+ stopReason = "content_filter";
511
+ break;
512
+ }
513
+ return {
514
+ message,
515
+ usage,
516
+ stopReason,
517
+ data: structuredData
518
+ };
519
+ }
520
+
521
+ // src/providers/moonshot/llm.ts
522
+ var MOONSHOT_API_URL = "https://api.moonshot.ai/v1/chat/completions";
523
+ var MOONSHOT_CAPABILITIES = {
524
+ streaming: true,
525
+ tools: true,
526
+ structuredOutput: true,
527
+ imageInput: true,
528
+ documentInput: false,
529
+ videoInput: true,
530
+ audioInput: false
531
+ };
532
+ async function resolveMoonshotApiKey(config) {
533
+ try {
534
+ return await resolveApiKey(config, "MOONSHOT_API_KEY", "moonshot", "llm");
535
+ } catch {
536
+ const kimiKey = process.env.KIMI_API_KEY;
537
+ if (kimiKey) {
538
+ return kimiKey;
539
+ }
540
+ throw new UPPError(
541
+ "API key not found. Set MOONSHOT_API_KEY or KIMI_API_KEY environment variable, or pass apiKey in config.",
542
+ ErrorCode.AuthenticationFailed,
543
+ "moonshot",
544
+ ModalityType.LLM
545
+ );
546
+ }
547
+ }
548
+ function createLLMHandler() {
549
+ let providerRef = null;
550
+ return {
551
+ _setProvider(provider) {
552
+ providerRef = provider;
553
+ },
554
+ bind(modelId) {
555
+ if (!providerRef) {
556
+ throw new UPPError(
557
+ "Provider reference not set. Handler must be used with createProvider() or have _setProvider called.",
558
+ ErrorCode.InvalidRequest,
559
+ "moonshot",
560
+ ModalityType.LLM
561
+ );
562
+ }
563
+ const model = {
564
+ modelId,
565
+ capabilities: MOONSHOT_CAPABILITIES,
566
+ get provider() {
567
+ return providerRef;
568
+ },
569
+ async complete(request) {
570
+ const apiKey = await resolveMoonshotApiKey(request.config);
571
+ const baseUrl = request.config.baseUrl ?? MOONSHOT_API_URL;
572
+ const body = transformRequest(request, modelId);
573
+ const headers = {
574
+ "Content-Type": "application/json",
575
+ Authorization: `Bearer ${apiKey}`
576
+ };
577
+ if (request.config.headers) {
578
+ for (const [key, value] of Object.entries(request.config.headers)) {
579
+ if (value !== void 0) {
580
+ headers[key] = value;
581
+ }
582
+ }
583
+ }
584
+ const response = await doFetch(
585
+ baseUrl,
586
+ {
587
+ method: "POST",
588
+ headers,
589
+ body: JSON.stringify(body),
590
+ signal: request.signal
591
+ },
592
+ request.config,
593
+ "moonshot",
594
+ "llm"
595
+ );
596
+ const data = await parseJsonResponse(response, "moonshot", "llm");
597
+ return transformResponse(data);
598
+ },
599
+ stream(request) {
600
+ const state = createStreamState();
601
+ let responseResolve;
602
+ let responseReject;
603
+ const responsePromise = new Promise((resolve, reject) => {
604
+ responseResolve = resolve;
605
+ responseReject = reject;
606
+ });
607
+ async function* generateEvents() {
608
+ try {
609
+ const apiKey = await resolveMoonshotApiKey(request.config);
610
+ const baseUrl = request.config.baseUrl ?? MOONSHOT_API_URL;
611
+ const body = transformRequest(request, modelId);
612
+ body.stream = true;
613
+ body.stream_options = { include_usage: true };
614
+ const headers = {
615
+ "Content-Type": "application/json",
616
+ Authorization: `Bearer ${apiKey}`,
617
+ Accept: "text/event-stream"
618
+ };
619
+ if (request.config.headers) {
620
+ for (const [key, value] of Object.entries(request.config.headers)) {
621
+ if (value !== void 0) {
622
+ headers[key] = value;
623
+ }
624
+ }
625
+ }
626
+ const response = await doStreamFetch(
627
+ baseUrl,
628
+ {
629
+ method: "POST",
630
+ headers,
631
+ body: JSON.stringify(body),
632
+ signal: request.signal
633
+ },
634
+ request.config,
635
+ "moonshot",
636
+ "llm"
637
+ );
638
+ if (!response.ok) {
639
+ const error = await normalizeHttpError(response, "moonshot", "llm");
640
+ responseReject(error);
641
+ throw error;
642
+ }
643
+ if (!response.body) {
644
+ const error = new UPPError(
645
+ "No response body for streaming request",
646
+ ErrorCode.ProviderError,
647
+ "moonshot",
648
+ ModalityType.LLM
649
+ );
650
+ responseReject(error);
651
+ throw error;
652
+ }
653
+ for await (const data of parseSSEStream(response.body)) {
654
+ if (data === "[DONE]") {
655
+ continue;
656
+ }
657
+ if (typeof data === "object" && data !== null) {
658
+ const chunk = data;
659
+ if ("error" in chunk && chunk.error) {
660
+ const errorData = chunk.error;
661
+ const error = new UPPError(
662
+ errorData.message ?? "Unknown error",
663
+ ErrorCode.ProviderError,
664
+ "moonshot",
665
+ ModalityType.LLM
666
+ );
667
+ responseReject(error);
668
+ throw error;
669
+ }
670
+ const uppEvents = transformStreamEvent(chunk, state);
671
+ for (const event of uppEvents) {
672
+ yield event;
673
+ if (request.structure && event.type === StreamEventType.TextDelta) {
674
+ yield objectDelta(event.delta.text ?? "", event.index);
675
+ }
676
+ }
677
+ }
678
+ }
679
+ responseResolve(buildResponseFromState(state));
680
+ } catch (error) {
681
+ const err = toError(error);
682
+ responseReject(err);
683
+ throw err;
684
+ }
685
+ }
686
+ return {
687
+ [Symbol.asyncIterator]() {
688
+ return generateEvents();
689
+ },
690
+ response: responsePromise
691
+ };
692
+ }
693
+ };
694
+ return model;
695
+ }
696
+ };
697
+ }
698
+
699
+ // src/providers/moonshot/types.ts
700
+ function webSearch() {
701
+ return {
702
+ type: "function",
703
+ function: {
704
+ name: "web_search",
705
+ description: "Search the web for information",
706
+ parameters: {
707
+ type: "object",
708
+ properties: {
709
+ query: {
710
+ description: "What to search for",
711
+ type: "string"
712
+ },
713
+ classes: {
714
+ description: 'Search domains to focus on. Defaults to "all" if not specified.',
715
+ type: "array",
716
+ items: {
717
+ type: "string",
718
+ enum: ["all", "academic", "social", "library", "finance", "code", "ecommerce", "medical"]
719
+ }
720
+ }
721
+ },
722
+ required: ["query"]
723
+ }
724
+ }
725
+ };
726
+ }
727
+ function codeRunner() {
728
+ return {
729
+ type: "function",
730
+ function: {
731
+ name: "code_runner",
732
+ description: "Safely executes Python code and returns the result, with print output, last-line evaluation, error handling, and timeout protection.",
733
+ parameters: {
734
+ type: "object",
735
+ properties: {
736
+ code: {
737
+ description: "The Python code to execute. Supports print(), matplotlib, pandas, and ctx.read_object() for file reading.",
738
+ type: "string"
739
+ }
740
+ },
741
+ required: ["code"]
742
+ }
743
+ }
744
+ };
745
+ }
746
+ function quickjs() {
747
+ return {
748
+ type: "function",
749
+ function: {
750
+ name: "quickjs",
751
+ description: "Safely executes JavaScript code using QuickJS engine",
752
+ parameters: {
753
+ type: "object",
754
+ properties: {
755
+ code: {
756
+ description: "The JavaScript code to execute. Supports console.log(), ES6+ features, and ctx.log() for logging.",
757
+ type: "string"
758
+ }
759
+ },
760
+ required: ["code"]
761
+ }
762
+ }
763
+ };
764
+ }
765
+ function fetch() {
766
+ return {
767
+ type: "function",
768
+ function: {
769
+ name: "fetch",
770
+ description: "Fetches a URL from the internet and optionally extracts its contents as markdown.",
771
+ parameters: {
772
+ type: "object",
773
+ properties: {
774
+ url: {
775
+ description: "URL to fetch",
776
+ type: "string",
777
+ format: "uri"
778
+ },
779
+ max_length: {
780
+ description: "Maximum number of characters to return (default: 5000)",
781
+ type: "integer",
782
+ default: 5e3
783
+ },
784
+ start_index: {
785
+ description: "Start at this character index, useful for pagination",
786
+ type: "integer",
787
+ default: 0
788
+ },
789
+ raw: {
790
+ description: "Get raw HTML without simplification",
791
+ type: "boolean",
792
+ default: false
793
+ }
794
+ },
795
+ required: ["url"]
796
+ }
797
+ }
798
+ };
799
+ }
800
+ function convert() {
801
+ return {
802
+ type: "function",
803
+ function: {
804
+ name: "convert",
805
+ description: "Convert between supported units of length, mass, volume, temperature, area, time, energy, pressure, speed, and currency.",
806
+ parameters: {
807
+ type: "object",
808
+ properties: {
809
+ value: {
810
+ description: "Value to convert",
811
+ type: "number"
812
+ },
813
+ from_unit: {
814
+ description: "Source unit (e.g., m, km, ft, kg, lb, \xB0C, \xB0F, USD, EUR)",
815
+ type: "string"
816
+ },
817
+ to_unit: {
818
+ description: "Target unit",
819
+ type: "string"
820
+ }
821
+ },
822
+ required: ["value", "from_unit", "to_unit"]
823
+ }
824
+ }
825
+ };
826
+ }
827
+ function date() {
828
+ return {
829
+ type: "function",
830
+ function: {
831
+ name: "date",
832
+ description: "Date and time processing tool, supports displaying current time, timezone conversion, date calculation, and more.",
833
+ parameters: {
834
+ type: "object",
835
+ properties: {
836
+ operation: {
837
+ description: "Operation type",
838
+ type: "string",
839
+ enum: ["time", "convert", "between", "add", "subtract"]
840
+ },
841
+ date: {
842
+ description: "Date string (YYYY-MM-DD or YYYY-MM-DD HH:MM:SS)",
843
+ type: "string"
844
+ },
845
+ date1: {
846
+ description: "First date (for difference calculation)",
847
+ type: "string"
848
+ },
849
+ date2: {
850
+ description: "Second date (for difference calculation)",
851
+ type: "string"
852
+ },
853
+ days: {
854
+ description: "Number of days (for add/subtract)",
855
+ type: "integer"
856
+ },
857
+ zone: {
858
+ description: "Timezone name (e.g., Asia/Shanghai, America/New_York, UTC)",
859
+ type: "string"
860
+ },
861
+ from_zone: {
862
+ description: "Source timezone (for conversion)",
863
+ type: "string"
864
+ },
865
+ to_zone: {
866
+ description: "Target timezone (for conversion)",
867
+ type: "string"
868
+ },
869
+ format: {
870
+ description: "Output format (Python strftime)",
871
+ type: "string",
872
+ default: "%Y-%m-%d %H:%M:%S"
873
+ }
874
+ },
875
+ required: ["operation"]
876
+ }
877
+ }
878
+ };
879
+ }
880
+ function base64Encode() {
881
+ return {
882
+ type: "function",
883
+ function: {
884
+ name: "base64_encode",
885
+ description: "Encode text to base64 format",
886
+ parameters: {
887
+ type: "object",
888
+ properties: {
889
+ data: {
890
+ description: "Text data to encode to base64",
891
+ type: "string"
892
+ },
893
+ encoding: {
894
+ description: "Character encoding to use (default: utf-8)",
895
+ type: "string",
896
+ default: "utf-8"
897
+ }
898
+ },
899
+ required: ["data"]
900
+ }
901
+ }
902
+ };
903
+ }
904
+ function base64Decode() {
905
+ return {
906
+ type: "function",
907
+ function: {
908
+ name: "base64_decode",
909
+ description: "Decode base64 text to original format",
910
+ parameters: {
911
+ type: "object",
912
+ properties: {
913
+ data: {
914
+ description: "Base64 encoded data to decode",
915
+ type: "string"
916
+ },
917
+ encoding: {
918
+ description: "Character encoding to use (default: utf-8)",
919
+ type: "string",
920
+ default: "utf-8"
921
+ }
922
+ },
923
+ required: ["data"]
924
+ }
925
+ }
926
+ };
927
+ }
928
+ function memory() {
929
+ return {
930
+ type: "function",
931
+ function: {
932
+ name: "memory",
933
+ description: "Memory storage and retrieval system, supporting persistence of conversation history, user preferences, and other data.",
934
+ parameters: {
935
+ type: "object",
936
+ properties: {
937
+ action: {
938
+ description: "Operation type",
939
+ type: "string",
940
+ enum: ["store", "retrieve", "delete", "list"]
941
+ },
942
+ key: {
943
+ description: "Storage key name",
944
+ type: "string"
945
+ },
946
+ data: {
947
+ description: "Data content to store",
948
+ type: "object"
949
+ },
950
+ prefix: {
951
+ description: "Key prefix for list operation",
952
+ type: "string"
953
+ },
954
+ ttl: {
955
+ description: "Data expiration time in seconds (default: 86400 = 24 hours)",
956
+ type: "integer",
957
+ default: 86400
958
+ }
959
+ },
960
+ required: ["action"]
961
+ }
962
+ }
963
+ };
964
+ }
965
+ function rethink() {
966
+ return {
967
+ type: "function",
968
+ function: {
969
+ name: "rethink",
970
+ description: "Tool for organizing thoughts, making plans, and thinking step by step. Does not return information, just for reflection.",
971
+ parameters: {
972
+ type: "object",
973
+ properties: {
974
+ thought: {
975
+ description: "The thought to consider for better solving the current task",
976
+ type: "string"
977
+ }
978
+ },
979
+ required: ["thought"]
980
+ }
981
+ }
982
+ };
983
+ }
984
+ function randomChoice() {
985
+ return {
986
+ type: "function",
987
+ function: {
988
+ name: "random_choice",
989
+ description: "Random selection tool that supports choosing items from candidates with optional weights.",
990
+ parameters: {
991
+ type: "object",
992
+ properties: {
993
+ candidates: {
994
+ description: "List of candidates to choose from",
995
+ type: "array",
996
+ items: { type: "string" }
997
+ },
998
+ count: {
999
+ description: "Number of items to select (default: 1)",
1000
+ type: "integer",
1001
+ default: 1
1002
+ },
1003
+ replace: {
1004
+ description: "Allow duplicates (default: false)",
1005
+ type: "boolean",
1006
+ default: false
1007
+ },
1008
+ weights: {
1009
+ description: "Optional weights for weighted selection",
1010
+ type: "array",
1011
+ items: { type: "number" }
1012
+ },
1013
+ seed: {
1014
+ description: "Random seed for reproducibility",
1015
+ type: "integer"
1016
+ },
1017
+ format: {
1018
+ description: "Output format",
1019
+ type: "string",
1020
+ enum: ["simple", "detailed", "json"],
1021
+ default: "simple"
1022
+ }
1023
+ },
1024
+ required: ["candidates"]
1025
+ }
1026
+ }
1027
+ };
1028
+ }
1029
+ function mew() {
1030
+ return {
1031
+ type: "function",
1032
+ function: {
1033
+ name: "mew_generator",
1034
+ description: "Randomly generates a cat's meow, accompanied by a blessing.",
1035
+ parameters: {
1036
+ type: "object",
1037
+ properties: {
1038
+ mood: {
1039
+ description: "The cat's mood",
1040
+ type: "string",
1041
+ enum: ["happy", "sleepy", "hungry", "playful", "grumpy"]
1042
+ }
1043
+ },
1044
+ required: []
1045
+ }
1046
+ }
1047
+ };
1048
+ }
1049
+ var tools = {
1050
+ /** Web search for real-time internet information */
1051
+ webSearch,
1052
+ /** Python code execution with matplotlib, pandas support */
1053
+ codeRunner,
1054
+ /** JavaScript execution via QuickJS engine */
1055
+ quickjs,
1056
+ /** URL content fetching with markdown extraction */
1057
+ fetch,
1058
+ /** Unit conversion (length, mass, temperature, currency, etc.) */
1059
+ convert,
1060
+ /** Date/time processing and timezone conversion */
1061
+ date,
1062
+ /** Base64 encoding */
1063
+ base64Encode,
1064
+ /** Base64 decoding */
1065
+ base64Decode,
1066
+ /** Alias for base64Encode */
1067
+ base64: base64Encode,
1068
+ /** Memory storage and retrieval system */
1069
+ memory,
1070
+ /** Intelligent reasoning/reflection tool */
1071
+ rethink,
1072
+ /** Random selection with optional weights */
1073
+ randomChoice,
1074
+ /** Cat meowing and blessings generator */
1075
+ mew
1076
+ };
1077
+
1078
+ // src/providers/moonshot/index.ts
1079
+ var moonshot = createProvider({
1080
+ name: "moonshot",
1081
+ version: "1.0.0",
1082
+ handlers: {
1083
+ llm: createLLMHandler()
1084
+ }
1085
+ });
1086
+ export {
1087
+ moonshot,
1088
+ tools
1089
+ };
1090
+ //# sourceMappingURL=index.js.map