@openclaw/ai 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +11 -8
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-DEKgalVg.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
  8. package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
  9. package/dist/assistant-output-CD4kY9gu.mjs +16 -0
  10. package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
  11. package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
  12. package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
  13. package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
  14. package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
  15. package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
  16. package/dist/diagnostics.d.mts +6 -7
  17. package/dist/diagnostics.mjs +4 -4
  18. package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
  19. package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
  20. package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
  21. package/dist/event-stream.d.mts +2 -2
  22. package/dist/event-stream.mjs +1 -2
  23. package/dist/expect-lbe3Hgrh.mjs +8 -0
  24. package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
  25. package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
  26. package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
  27. package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
  28. package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
  29. package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
  30. package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
  31. package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
  32. package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
  33. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  34. package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
  35. package/dist/index-Bczt0MnO.d.mts +17 -0
  36. package/dist/index.d.mts +8 -7
  37. package/dist/index.mjs +9 -7
  38. package/dist/internal/anthropic.d.mts +21 -26
  39. package/dist/internal/anthropic.mjs +6 -6
  40. package/dist/internal/google-model-family.mjs +1 -1
  41. package/dist/internal/google.d.mts +15 -0
  42. package/dist/internal/google.mjs +1 -0
  43. package/dist/internal/model-request-body.d.mts +37 -0
  44. package/dist/internal/model-request-body.mjs +106 -0
  45. package/dist/internal/openai-completions-compat.d.mts +1 -1
  46. package/dist/internal/openai-completions-compat.mjs +1 -1
  47. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  48. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  49. package/dist/internal/openai.d.mts +14 -12
  50. package/dist/internal/openai.mjs +11 -10
  51. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  52. package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
  53. package/dist/internal/retry-after.d.mts +2 -2
  54. package/dist/internal/retry-after.mjs +96 -32
  55. package/dist/internal/runtime.d.mts +15 -41
  56. package/dist/internal/runtime.mjs +9 -10
  57. package/dist/internal/shared.d.mts +21 -25
  58. package/dist/internal/shared.mjs +9 -98
  59. package/dist/internal/tool-schema.d.mts +10 -10
  60. package/dist/internal/tool-schema.mjs +4 -4
  61. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  62. package/dist/mistral-CjHkvsqR.mjs +3741 -0
  63. package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
  64. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  65. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  66. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  67. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  68. package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
  72. package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  76. package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  77. package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  78. package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  79. package/dist/openai-responses-ev_c6oTy.mjs +89 -0
  80. package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
  81. package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
  82. package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
  83. package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
  84. package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-Buswj0Mf.mjs +766 -0
  86. package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
  87. package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
  88. package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
  89. package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
  90. package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
  91. package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
  94. package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/providers.d.mts +2 -2
  97. package/dist/providers.mjs +26 -29
  98. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  99. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  100. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  101. package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
  102. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  103. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  104. package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
  105. package/dist/src-BUsVkrNt.mjs +105 -0
  106. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  107. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  108. package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
  109. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  110. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  111. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  112. package/dist/telemetry-CvK1yQg7.mjs +582 -0
  113. package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  114. package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  115. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  116. package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  117. package/dist/transports.d.mts +42 -39
  118. package/dist/transports.mjs +215 -296
  119. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  120. package/dist/types-Cb3-5WM9.d.mts +1 -0
  121. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  122. package/dist/types.d.mts +7 -6
  123. package/dist/types.mjs +7 -5
  124. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  125. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  126. package/dist/validation.d.mts +1 -1
  127. package/dist/validation.mjs +1 -2
  128. package/package.json +40 -6
  129. package/dist/anthropic-lueA8LUg.mjs +0 -221
  130. package/dist/assistant-output-BnQm3fov.mjs +0 -47
  131. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  132. package/dist/index-DSprYWaz.d.mts +0 -185
  133. package/dist/mistral-CQ7aoWg2.mjs +0 -512
  134. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  135. package/dist/openai-CiRi-nVE.mjs +0 -20077
  136. package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
  137. package/dist/openai-responses-DQsZKUoI.mjs +0 -87
  138. package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
  139. package/dist/types-CBJthzJX.d.mts +0 -1
  140. package/dist/ws.LICENSE +0 -20
@@ -0,0 +1,3741 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import "./src-CQ7nH2mL.mjs";
3
+ import { t as omitNullRequestHeaders } from "./request-headers-DO4Mqhw1.mjs";
4
+ import { r as appendAssistantThinking, t as AssistantMessageEventStream } from "./event-stream-X2gmsUWv.mjs";
5
+ import { N as isImageWithMediaPayload, O as calculateCost, k as clampThinkingLevel, r as getAiTransportHost } from "./host-DX7ORpeH.mjs";
6
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
7
+ import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-w-ICeyOI.mjs";
8
+ import { C as stripSystemPromptCacheBoundary, a as describeToolResultMediaPlaceholder, c as extractToolResultText, l as formatToolResultText, n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-tLSeECry.mjs";
9
+ import { A as parseStreamingJson, D as shortHash, O as createToolArgumentPreviewSchedule, h as notifyProviderHttpResponse, l as finalizeTerminalToolCallArguments, n as assignTransportErrorDetails, p as mergeTransportHeaders, u as finalizeTransportStream } from "./transport-stream-shared-D2uFMhMc.mjs";
10
+ import { t as getPublishedRuntimeToolInputSchema } from "./tool-schema-json-projection-BQpiJlXJ.mjs";
11
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
12
+ import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
13
+ import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
14
+ import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
15
+ import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
16
+ import { t as requireApiKey } from "./required-api-key-2zZTkmsi.mjs";
17
+ import { randomUUID } from "node:crypto";
18
+ import * as z$1 from "zod/v4";
19
+ import { z } from "zod/v4";
20
+ import * as z$2 from "zod/v4/core";
21
+ import { zodToJsonSchema } from "zod-to-json-schema";
22
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/extra/observability/provider.js
23
+ let registeredTracerProvider;
24
+ /**
25
+ * Route SDK tracing spans to a specific OpenTelemetry tracer provider.
26
+ */
27
+ function registerTracerProvider(tracerProvider) {
28
+ registeredTracerProvider = tracerProvider;
29
+ }
30
+ /**
31
+ * Returns the currently registered tracer provider, if any.
32
+ */
33
+ function getRegisteredTracerProvider() {
34
+ return registeredTracerProvider;
35
+ }
36
+ //#endregion
37
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/sdkvalidationerror.js
38
+ var SDKValidationError = class extends Error {
39
+ /**
40
+ * The raw value that failed validation.
41
+ */
42
+ rawValue;
43
+ /**
44
+ * The raw message that failed validation.
45
+ */
46
+ rawMessage;
47
+ static [Symbol.hasInstance](instance) {
48
+ if (!(instance instanceof Error)) return false;
49
+ if (!("rawValue" in instance)) return false;
50
+ if (!("rawMessage" in instance)) return false;
51
+ if (!("pretty" in instance)) return false;
52
+ if (typeof instance.pretty !== "function") return false;
53
+ return true;
54
+ }
55
+ constructor(message, cause, rawValue) {
56
+ super(`${message}: ${cause}`);
57
+ this.name = "SDKValidationError";
58
+ this.cause = cause;
59
+ this.rawValue = rawValue;
60
+ this.rawMessage = message;
61
+ }
62
+ /**
63
+ * Return a pretty-formatted error message if the underlying validation error
64
+ * is a ZodError or some other recognized error type, otherwise return the
65
+ * default error message.
66
+ */
67
+ pretty() {
68
+ if (this.cause instanceof z$2.$ZodError) return `${this.rawMessage}\n${formatZodError(this.cause)}`;
69
+ else return this.toString();
70
+ }
71
+ };
72
+ function formatZodError(err) {
73
+ return z$2.prettifyError(err);
74
+ }
75
+ //#endregion
76
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/fp.js
77
+ function OK(value) {
78
+ return {
79
+ ok: true,
80
+ value
81
+ };
82
+ }
83
+ function ERR(error) {
84
+ return {
85
+ ok: false,
86
+ error
87
+ };
88
+ }
89
+ /**
90
+ * unwrapAsync is a convenience function for resolving a value from a Promise
91
+ * of a result or rejecting if an error occurred.
92
+ */
93
+ async function unwrapAsync(pr) {
94
+ const r = await pr;
95
+ if (!r.ok) throw r.error;
96
+ return r.value;
97
+ }
98
+ //#endregion
99
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/schemas.js
100
+ /**
101
+ * Utility function that executes some code which may result in a ZodError. It
102
+ * intercepts this error and converts it to an SDKValidationError so as to not
103
+ * leak Zod implementation details to user code.
104
+ */
105
+ function safeParse(rawValue, fn, errorMessage) {
106
+ try {
107
+ return OK(fn(rawValue));
108
+ } catch (err) {
109
+ return ERR(new SDKValidationError(errorMessage, err, rawValue));
110
+ }
111
+ }
112
+ //#endregion
113
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/primitives.js
114
+ /**
115
+ * Converts or omits an object's keys according to a mapping.
116
+ *
117
+ * @param inp An object whose keys will be remapped
118
+ * @param mappings A mapping of original keys to new keys. If a key is not present in the mapping, it will be left as is. If a key is mapped to `null`, it will be removed in the resulting object.
119
+ * @returns A new object with keys remapped or omitted according to the mappings
120
+ */
121
+ function remap(inp, mappings) {
122
+ let out = {};
123
+ if (!Object.keys(mappings).length) {
124
+ out = inp;
125
+ return out;
126
+ }
127
+ for (const [k, v] of Object.entries(inp)) {
128
+ const j = mappings[k];
129
+ if (j === null) continue;
130
+ out[j ?? k] = v;
131
+ }
132
+ return out;
133
+ }
134
+ function compactMap(values) {
135
+ const out = {};
136
+ for (const [k, v] of Object.entries(values)) if (typeof v !== "undefined") out[k] = v;
137
+ return out;
138
+ }
139
+ //#endregion
140
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/unrecognized.js
141
+ function unrecognized(value) {
142
+ globalCount++;
143
+ return value;
144
+ }
145
+ let globalCount = 0;
146
+ let refCount = 0;
147
+ function startCountingUnrecognized() {
148
+ refCount++;
149
+ const start = globalCount;
150
+ return {
151
+ /**
152
+ * Ends counting and returns the delta.
153
+ * @param delta - If provided, only this amount is added to the parent counter
154
+ * (used for nested unions where we only want to record the winning option's count).
155
+ * If not provided, records all counts since start().
156
+ */
157
+ end: (delta) => {
158
+ const count = globalCount - start;
159
+ globalCount = start + (delta ?? count);
160
+ if (--refCount === 0) globalCount = 0;
161
+ return count;
162
+ } };
163
+ }
164
+ //#endregion
165
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/enums.js
166
+ function inboundSchema(enumObj) {
167
+ const options = Object.values(enumObj);
168
+ return z$1.union([...options.map((x) => z$1.literal(x)), z$1.string().transform((x) => unrecognized(x))]);
169
+ }
170
+ function outboundSchema(_) {
171
+ return z$1.string();
172
+ }
173
+ //#endregion
174
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/discriminatedUnion.js
175
+ const UNKNOWN = Symbol("UNKNOWN");
176
+ function isUnknown(value) {
177
+ return typeof value === "object" && value !== null && UNKNOWN in value;
178
+ }
179
+ /**
180
+ * Forward-compatible discriminated union parser.
181
+ *
182
+ * If the input does not match one of the predefined options, it will be
183
+ * captured and available as `{ raw: <original input>, [discriminator]: "UNKNOWN", isUnknown: true }`.
184
+ *
185
+ * @param inputPropertyName - The discriminator property name in the input payload
186
+ * @param options - Map of discriminator values to their corresponding schemas
187
+ * @param opts - Optional configuration object
188
+ * @param opts.unknownValue - The value to use for the discriminator when the input is unknown (default: "UNKNOWN")
189
+ * @param opts.outputPropertyName - Output property name if the sanitized (camelCase) property name differs from inputPropertyName
190
+ */
191
+ function discriminatedUnion(inputPropertyName, options, opts = {}) {
192
+ const { unknownValue = "UNKNOWN", outputPropertyName } = opts;
193
+ return z$1.unknown().transform((input) => {
194
+ const fallback = Object.defineProperties({
195
+ raw: input,
196
+ [outputPropertyName ?? inputPropertyName]: unknownValue,
197
+ isUnknown: true
198
+ }, { [UNKNOWN]: {
199
+ value: true,
200
+ enumerable: false,
201
+ configurable: false
202
+ } });
203
+ if (!(typeof input === "object" && input !== null)) return fallback;
204
+ const discriminator = input[inputPropertyName];
205
+ if (typeof discriminator !== "string") return fallback;
206
+ if (!(discriminator in options)) return fallback;
207
+ const schema = options[discriminator];
208
+ if (!schema) return fallback;
209
+ const unrecognizedCtr = startCountingUnrecognized();
210
+ const result = schema.safeParse(input);
211
+ if (!result.success) {
212
+ unrecognizedCtr.end(0);
213
+ return fallback;
214
+ }
215
+ unrecognizedCtr.end();
216
+ if (outputPropertyName) result.data[outputPropertyName] = discriminator;
217
+ return result.data;
218
+ });
219
+ }
220
+ //#endregion
221
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/rfcdate.js
222
+ const dateRE = /^\d{4}-\d{2}-\d{2}$/;
223
+ var RFCDate = class RFCDate {
224
+ serialized;
225
+ /**
226
+ * Creates a new RFCDate instance using today's date.
227
+ */
228
+ static today() {
229
+ return new RFCDate(/* @__PURE__ */ new Date());
230
+ }
231
+ /**
232
+ * Creates a new RFCDate instance using the provided input.
233
+ * If a string is used then in must be in the format YYYY-MM-DD.
234
+ *
235
+ * @param date A Date object or a date string in YYYY-MM-DD format
236
+ * @example
237
+ * new RFCDate("2022-01-01")
238
+ * @example
239
+ * new RFCDate(new Date())
240
+ */
241
+ constructor(date) {
242
+ if (typeof date === "string" && !dateRE.test(date)) throw new RangeError("RFCDate: date strings must be in the format YYYY-MM-DD: " + date);
243
+ const value = new Date(date);
244
+ if (isNaN(+value)) throw new RangeError("RFCDate: invalid date provided: " + date);
245
+ this.serialized = value.toISOString().slice(0, 10);
246
+ if (!dateRE.test(this.serialized)) throw new TypeError(`RFCDate: failed to build valid date with given value: ${date} serialized to ${this.serialized}`);
247
+ }
248
+ toJSON() {
249
+ return this.toString();
250
+ }
251
+ toString() {
252
+ return this.serialized;
253
+ }
254
+ };
255
+ //#endregion
256
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/smartUnion.js
257
+ /**
258
+ * Smart union parser that tries all schemas and returns the best match
259
+ * based on the number of populated fields.
260
+ */
261
+ function smartUnion(options) {
262
+ return z$1.unknown().transform((input, ctx) => {
263
+ const candidates = [];
264
+ const errors = options.map(() => []);
265
+ const parentUnrecognizedCtr = startCountingUnrecognized();
266
+ for (const [i, option] of options.entries()) {
267
+ const unrecognizedCtr = startCountingUnrecognized();
268
+ const result = option.safeParse(input);
269
+ const inexactCount = unrecognizedCtr.end();
270
+ const zeroDefaultCount = 0;
271
+ if (result.success) {
272
+ candidates.push({
273
+ data: result.data,
274
+ inexactCount,
275
+ zeroDefaultCount,
276
+ fieldCount: -1
277
+ });
278
+ continue;
279
+ }
280
+ errors[i].push(...result.error.issues);
281
+ }
282
+ if (candidates.length === 0) {
283
+ parentUnrecognizedCtr.end(0);
284
+ ctx.addIssue({
285
+ input,
286
+ code: "invalid_union",
287
+ errors
288
+ });
289
+ return z$1.NEVER;
290
+ }
291
+ let best = candidates[0];
292
+ for (const candidate of candidates) {
293
+ if (candidates.length > 1) candidate.fieldCount = countFieldsRecursive(candidate.data);
294
+ best = better(candidate, best);
295
+ }
296
+ parentUnrecognizedCtr.end(best.inexactCount);
297
+ return best.data;
298
+ });
299
+ }
300
+ function better(a, b) {
301
+ const aIsExact = a.inexactCount === 0;
302
+ if (aIsExact !== (b.inexactCount === 0)) return aIsExact ? a : b;
303
+ const actualFieldCountA = a.fieldCount - a.zeroDefaultCount;
304
+ const actualFieldCountB = b.fieldCount - b.zeroDefaultCount;
305
+ if (actualFieldCountA !== actualFieldCountB) return actualFieldCountA > actualFieldCountB ? a : b;
306
+ return a.inexactCount < b.inexactCount ? a : b;
307
+ }
308
+ /**
309
+ * Counts the number of fields in a parsed value recursively.
310
+ * @param `parsed` assumed to *not* contain cycles
311
+ * fieldCount: total number of fields found
312
+ * inexactCount: number of primitive values that are not unrecognized enum values
313
+ */
314
+ function countFieldsRecursive(parsed) {
315
+ let fieldCount = 0;
316
+ const queue = [parsed];
317
+ let index = 0;
318
+ while (index < queue.length) {
319
+ const value = queue[index++];
320
+ if (value === void 0 || isUnknown(value)) continue;
321
+ const type = typeof value;
322
+ if (value === null || type === "number" || type === "string" || type === "boolean" || type === "bigint" || value instanceof Date || value instanceof RFCDate) {
323
+ fieldCount++;
324
+ continue;
325
+ }
326
+ if (Array.isArray(value)) {
327
+ queue.push(...value);
328
+ continue;
329
+ }
330
+ if (type === "object") queue.push(...Object.values(value));
331
+ }
332
+ return fieldCount;
333
+ }
334
+ //#endregion
335
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/audiochunk.js
336
+ /** @internal */
337
+ const AudioChunk$inboundSchema = z$1.object({
338
+ type: z$1.literal("input_audio"),
339
+ input_audio: z$1.string()
340
+ }).transform((v) => {
341
+ return remap(v, { "input_audio": "inputAudio" });
342
+ });
343
+ /** @internal */
344
+ const AudioChunk$outboundSchema = z$1.object({
345
+ type: z$1.literal("input_audio"),
346
+ inputAudio: z$1.string()
347
+ }).transform((v) => {
348
+ return remap(v, { inputAudio: "input_audio" });
349
+ });
350
+ //#endregion
351
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/documenturlchunk.js
352
+ /** @internal */
353
+ const DocumentURLChunk$inboundSchema = z$1.object({
354
+ type: z$1.literal("document_url").default("document_url"),
355
+ document_url: z$1.string(),
356
+ document_name: z$1.nullable(z$1.string()).optional()
357
+ }).transform((v) => {
358
+ return remap(v, {
359
+ "document_url": "documentUrl",
360
+ "document_name": "documentName"
361
+ });
362
+ });
363
+ /** @internal */
364
+ const DocumentURLChunk$outboundSchema = z$1.object({
365
+ type: z$1.literal("document_url").default("document_url"),
366
+ documentUrl: z$1.string(),
367
+ documentName: z$1.nullable(z$1.string()).optional()
368
+ }).transform((v) => {
369
+ return remap(v, {
370
+ documentUrl: "document_url",
371
+ documentName: "document_name"
372
+ });
373
+ });
374
+ //#endregion
375
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/filechunk.js
376
+ /** @internal */
377
+ const FileChunk$inboundSchema = z$1.object({
378
+ type: z$1.literal("file").default("file"),
379
+ file_id: z$1.string()
380
+ }).transform((v) => {
381
+ return remap(v, { "file_id": "fileId" });
382
+ });
383
+ /** @internal */
384
+ const FileChunk$outboundSchema = z$1.object({
385
+ type: z$1.literal("file").default("file"),
386
+ fileId: z$1.string()
387
+ }).transform((v) => {
388
+ return remap(v, { fileId: "file_id" });
389
+ });
390
+ //#endregion
391
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/imagedetail.js
392
+ const ImageDetail = {
393
+ Low: "low",
394
+ Auto: "auto",
395
+ High: "high"
396
+ };
397
+ /** @internal */
398
+ const ImageDetail$inboundSchema = inboundSchema(ImageDetail);
399
+ /** @internal */
400
+ const ImageDetail$outboundSchema = outboundSchema(ImageDetail);
401
+ //#endregion
402
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/imageurl.js
403
+ /** @internal */
404
+ const ImageURL$inboundSchema = z$1.object({
405
+ url: z$1.string(),
406
+ detail: z$1.nullable(ImageDetail$inboundSchema).optional()
407
+ });
408
+ /** @internal */
409
+ const ImageURL$outboundSchema = z$1.object({
410
+ url: z$1.string(),
411
+ detail: z$1.nullable(ImageDetail$outboundSchema).optional()
412
+ });
413
+ smartUnion([ImageURL$inboundSchema, z$1.string()]);
414
+ smartUnion([ImageURL$outboundSchema, z$1.string()]);
415
+ /** @internal */
416
+ const ImageURLChunk$inboundSchema = z$1.object({
417
+ type: z$1.literal("image_url").default("image_url"),
418
+ image_url: smartUnion([ImageURL$inboundSchema, z$1.string()])
419
+ }).transform((v) => {
420
+ return remap(v, { "image_url": "imageUrl" });
421
+ });
422
+ /** @internal */
423
+ const ImageURLChunk$outboundSchema = z$1.object({
424
+ type: z$1.literal("image_url").default("image_url"),
425
+ imageUrl: smartUnion([ImageURL$outboundSchema, z$1.string()])
426
+ }).transform((v) => {
427
+ return remap(v, { imageUrl: "image_url" });
428
+ });
429
+ smartUnion([z$1.int(), z$1.string()]);
430
+ smartUnion([z$1.int(), z$1.string()]);
431
+ /** @internal */
432
+ const ReferenceChunk$inboundSchema = z$1.object({
433
+ type: z$1.literal("reference").default("reference"),
434
+ reference_ids: z$1.array(smartUnion([z$1.int(), z$1.string()]))
435
+ }).transform((v) => {
436
+ return remap(v, { "reference_ids": "referenceIds" });
437
+ });
438
+ /** @internal */
439
+ const ReferenceChunk$outboundSchema = z$1.object({
440
+ type: z$1.literal("reference").default("reference"),
441
+ referenceIds: z$1.array(smartUnion([z$1.int(), z$1.string()]))
442
+ }).transform((v) => {
443
+ return remap(v, { referenceIds: "reference_ids" });
444
+ });
445
+ //#endregion
446
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/textchunk.js
447
+ /** @internal */
448
+ const TextChunk$inboundSchema = z$1.object({
449
+ type: z$1.literal("text").default("text"),
450
+ text: z$1.string()
451
+ });
452
+ /** @internal */
453
+ const TextChunk$outboundSchema = z$1.object({
454
+ type: z$1.literal("text").default("text"),
455
+ text: z$1.string()
456
+ });
457
+ //#endregion
458
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/builtinconnectors.js
459
+ const BuiltInConnectors = {
460
+ WebSearch: "web_search",
461
+ WebSearchPremium: "web_search_premium",
462
+ CodeInterpreter: "code_interpreter",
463
+ ImageGeneration: "image_generation",
464
+ DocumentLibrary: "document_library"
465
+ };
466
+ /** @internal */
467
+ const BuiltInConnectors$inboundSchema = inboundSchema(BuiltInConnectors);
468
+ /** @internal */
469
+ const BuiltInConnectors$outboundSchema = outboundSchema(BuiltInConnectors);
470
+ smartUnion([BuiltInConnectors$inboundSchema, z$1.string()]);
471
+ smartUnion([BuiltInConnectors$outboundSchema, z$1.string()]);
472
+ /** @internal */
473
+ const ToolReferenceChunk$inboundSchema = z$1.object({
474
+ type: z$1.literal("tool_reference").default("tool_reference"),
475
+ tool: smartUnion([BuiltInConnectors$inboundSchema, z$1.string()]),
476
+ title: z$1.string(),
477
+ url: z$1.nullable(z$1.string()).optional(),
478
+ favicon: z$1.nullable(z$1.string()).optional(),
479
+ description: z$1.nullable(z$1.string()).optional()
480
+ });
481
+ /** @internal */
482
+ const ToolReferenceChunk$outboundSchema = z$1.object({
483
+ type: z$1.literal("tool_reference").default("tool_reference"),
484
+ tool: smartUnion([BuiltInConnectors$outboundSchema, z$1.string()]),
485
+ title: z$1.string(),
486
+ url: z$1.nullable(z$1.string()).optional(),
487
+ favicon: z$1.nullable(z$1.string()).optional(),
488
+ description: z$1.nullable(z$1.string()).optional()
489
+ });
490
+ smartUnion([
491
+ ToolReferenceChunk$inboundSchema,
492
+ TextChunk$inboundSchema,
493
+ ReferenceChunk$inboundSchema
494
+ ]);
495
+ smartUnion([
496
+ ToolReferenceChunk$outboundSchema,
497
+ TextChunk$outboundSchema,
498
+ ReferenceChunk$outboundSchema
499
+ ]);
500
+ /** @internal */
501
+ const ThinkChunk$inboundSchema = z$1.object({
502
+ type: z$1.literal("thinking").default("thinking"),
503
+ thinking: z$1.array(smartUnion([
504
+ ToolReferenceChunk$inboundSchema,
505
+ TextChunk$inboundSchema,
506
+ ReferenceChunk$inboundSchema
507
+ ])),
508
+ signature: z$1.nullable(z$1.string()).optional(),
509
+ closed: z$1.boolean().optional()
510
+ });
511
+ /** @internal */
512
+ const ThinkChunk$outboundSchema = z$1.object({
513
+ type: z$1.literal("thinking").default("thinking"),
514
+ thinking: z$1.array(smartUnion([
515
+ ToolReferenceChunk$outboundSchema,
516
+ TextChunk$outboundSchema,
517
+ ReferenceChunk$outboundSchema
518
+ ])),
519
+ signature: z$1.nullable(z$1.string()).optional(),
520
+ closed: z$1.boolean().optional()
521
+ });
522
+ //#endregion
523
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/contentchunk.js
524
+ /** @internal */
525
+ const ContentChunk$inboundSchema = discriminatedUnion("type", {
526
+ image_url: ImageURLChunk$inboundSchema.and(z$1.object({ type: z$1.literal("image_url") })),
527
+ document_url: DocumentURLChunk$inboundSchema.and(z$1.object({ type: z$1.literal("document_url") })),
528
+ text: TextChunk$inboundSchema.and(z$1.object({ type: z$1.literal("text") })),
529
+ reference: ReferenceChunk$inboundSchema.and(z$1.object({ type: z$1.literal("reference") })),
530
+ file: FileChunk$inboundSchema.and(z$1.object({ type: z$1.literal("file") })),
531
+ thinking: ThinkChunk$inboundSchema.and(z$1.object({ type: z$1.literal("thinking") })),
532
+ input_audio: AudioChunk$inboundSchema
533
+ });
534
+ /** @internal */
535
+ const ContentChunk$outboundSchema = z$1.union([
536
+ ImageURLChunk$outboundSchema.and(z$1.object({ type: z$1.literal("image_url") })),
537
+ DocumentURLChunk$outboundSchema.and(z$1.object({ type: z$1.literal("document_url") })),
538
+ TextChunk$outboundSchema.and(z$1.object({ type: z$1.literal("text") })),
539
+ ReferenceChunk$outboundSchema.and(z$1.object({ type: z$1.literal("reference") })),
540
+ FileChunk$outboundSchema.and(z$1.object({ type: z$1.literal("file") })),
541
+ ThinkChunk$outboundSchema.and(z$1.object({ type: z$1.literal("thinking") })),
542
+ AudioChunk$outboundSchema
543
+ ]);
544
+ smartUnion([z$1.record(z$1.string(), z$1.any()), z$1.string()]);
545
+ smartUnion([z$1.record(z$1.string(), z$1.any()), z$1.string()]);
546
+ /** @internal */
547
+ const FunctionCall$inboundSchema = z$1.object({
548
+ name: z$1.string(),
549
+ arguments: smartUnion([z$1.record(z$1.string(), z$1.any()), z$1.string()])
550
+ });
551
+ /** @internal */
552
+ const FunctionCall$outboundSchema = z$1.object({
553
+ name: z$1.string(),
554
+ arguments: smartUnion([z$1.record(z$1.string(), z$1.any()), z$1.string()])
555
+ });
556
+ //#endregion
557
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/tooltypes.js
558
+ const ToolTypes = { Function: "function" };
559
+ /** @internal */
560
+ const ToolTypes$inboundSchema = inboundSchema(ToolTypes);
561
+ /** @internal */
562
+ const ToolTypes$outboundSchema = outboundSchema(ToolTypes);
563
+ //#endregion
564
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/toolcall.js
565
+ /** @internal */
566
+ const ToolCall$inboundSchema = z$1.object({
567
+ id: z$1.string().default("null"),
568
+ type: ToolTypes$inboundSchema.default("function"),
569
+ function: FunctionCall$inboundSchema,
570
+ index: z$1.int().default(0)
571
+ });
572
+ /** @internal */
573
+ const ToolCall$outboundSchema = z$1.object({
574
+ id: z$1.string().default("null"),
575
+ type: ToolTypes$outboundSchema.default("function"),
576
+ function: FunctionCall$outboundSchema,
577
+ index: z$1.int().default(0)
578
+ });
579
+ smartUnion([z$1.string(), z$1.array(ContentChunk$inboundSchema)]);
580
+ /** @internal */
581
+ const DeltaMessage$inboundSchema = z$1.object({
582
+ role: z$1.nullable(z$1.string()).optional(),
583
+ content: z$1.nullable(smartUnion([z$1.string(), z$1.array(ContentChunk$inboundSchema)])).optional(),
584
+ tool_calls: z$1.nullable(z$1.array(ToolCall$inboundSchema)).optional(),
585
+ tool_call_id: z$1.nullable(z$1.string()).optional(),
586
+ index: z$1.nullable(z$1.int()).optional(),
587
+ metadata: z$1.nullable(z$1.record(z$1.string(), z$1.any())).optional()
588
+ }).transform((v) => {
589
+ return remap(v, {
590
+ "tool_calls": "toolCalls",
591
+ "tool_call_id": "toolCallId"
592
+ });
593
+ });
594
+ /** @internal */
595
+ const CompletionResponseStreamChoiceFinishReason$inboundSchema = inboundSchema({
596
+ Stop: "stop",
597
+ Length: "length",
598
+ Error: "error",
599
+ ToolCalls: "tool_calls"
600
+ });
601
+ /** @internal */
602
+ const CompletionResponseStreamChoice$inboundSchema = z$1.object({
603
+ index: z$1.int(),
604
+ delta: DeltaMessage$inboundSchema,
605
+ finish_reason: z$1.nullable(CompletionResponseStreamChoiceFinishReason$inboundSchema)
606
+ }).transform((v) => {
607
+ return remap(v, { "finish_reason": "finishReason" });
608
+ });
609
+ //#endregion
610
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/usageinfo.js
611
+ /** @internal */
612
+ const UsageInfo$inboundSchema = z$1.object({
613
+ prompt_tokens: z$1.int().default(0),
614
+ completion_tokens: z$1.int().default(0),
615
+ total_tokens: z$1.int().default(0),
616
+ prompt_audio_seconds: z$1.nullable(z$1.int()).optional(),
617
+ service_tier: z$1.nullable(z$1.string()).optional()
618
+ }).catchall(z$1.any()).transform((v) => {
619
+ return remap(v, {
620
+ "prompt_tokens": "promptTokens",
621
+ "completion_tokens": "completionTokens",
622
+ "total_tokens": "totalTokens",
623
+ "prompt_audio_seconds": "promptAudioSeconds",
624
+ "service_tier": "serviceTier"
625
+ });
626
+ });
627
+ /** @internal */
628
+ const UsageInfo$outboundSchema = z$1.object({
629
+ promptTokens: z$1.int().default(0),
630
+ completionTokens: z$1.int().default(0),
631
+ totalTokens: z$1.int().default(0),
632
+ promptAudioSeconds: z$1.nullable(z$1.int()).optional(),
633
+ serviceTier: z$1.nullable(z$1.string()).optional()
634
+ }).catchall(z$1.any()).transform((v) => {
635
+ return { ...remap(v, {
636
+ promptTokens: "prompt_tokens",
637
+ completionTokens: "completion_tokens",
638
+ totalTokens: "total_tokens",
639
+ promptAudioSeconds: "prompt_audio_seconds",
640
+ serviceTier: "service_tier"
641
+ }) };
642
+ });
643
+ //#endregion
644
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/completionchunk.js
645
+ /** @internal */
646
+ const CompletionChunk$inboundSchema = z$1.object({
647
+ id: z$1.string(),
648
+ object: z$1.string().optional(),
649
+ created: z$1.int().optional(),
650
+ model: z$1.string(),
651
+ usage: UsageInfo$inboundSchema.optional(),
652
+ choices: z$1.array(CompletionResponseStreamChoice$inboundSchema)
653
+ });
654
+ function completionChunkFromJSON(jsonString) {
655
+ return safeParse(jsonString, (x) => CompletionChunk$inboundSchema.parse(JSON.parse(x)), `Failed to parse 'CompletionChunk' from JSON`);
656
+ }
657
+ //#endregion
658
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/http.js
659
+ const DEFAULT_FETCHER = (input, init) => {
660
+ if (init == null) return fetch(input);
661
+ else return fetch(input, init);
662
+ };
663
+ var HTTPClient = class HTTPClient {
664
+ options;
665
+ fetcher;
666
+ requestHooks = [];
667
+ requestErrorHooks = [];
668
+ responseHooks = [];
669
+ constructor(options = {}) {
670
+ this.options = options;
671
+ this.fetcher = options.fetcher || DEFAULT_FETCHER;
672
+ }
673
+ async request(request) {
674
+ let req = request;
675
+ for (const hook of this.requestHooks) {
676
+ const nextRequest = await hook(req);
677
+ if (nextRequest) req = nextRequest;
678
+ }
679
+ try {
680
+ const res = await this.fetcher(req);
681
+ for (const hook of this.responseHooks) await hook(res, req);
682
+ return res;
683
+ } catch (err) {
684
+ for (const hook of this.requestErrorHooks) await hook(err, req);
685
+ throw err;
686
+ }
687
+ }
688
+ addHook(...args) {
689
+ if (args[0] === "beforeRequest") this.requestHooks.push(args[1]);
690
+ else if (args[0] === "requestError") this.requestErrorHooks.push(args[1]);
691
+ else if (args[0] === "response") this.responseHooks.push(args[1]);
692
+ else throw new Error(`Invalid hook type: ${args[0]}`);
693
+ return this;
694
+ }
695
+ removeHook(...args) {
696
+ let target;
697
+ if (args[0] === "beforeRequest") target = this.requestHooks;
698
+ else if (args[0] === "requestError") target = this.requestErrorHooks;
699
+ else if (args[0] === "response") target = this.responseHooks;
700
+ else throw new Error(`Invalid hook type: ${args[0]}`);
701
+ const index = target.findIndex((v) => v === args[1]);
702
+ if (index >= 0) target.splice(index, 1);
703
+ return this;
704
+ }
705
+ clone() {
706
+ const child = new HTTPClient(this.options);
707
+ child.requestHooks = this.requestHooks.slice();
708
+ child.requestErrorHooks = this.requestErrorHooks.slice();
709
+ child.responseHooks = this.responseHooks.slice();
710
+ return child;
711
+ }
712
+ };
713
+ const mediaParamSeparator = /\s*;\s*/g;
714
+ function matchContentType(response, pattern) {
715
+ if (pattern === "*") return true;
716
+ let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream";
717
+ contentType = contentType.toLowerCase();
718
+ const [wantType = "", ...wantParams] = pattern.toLowerCase().trim().split(mediaParamSeparator);
719
+ if (wantType.split("/").length !== 2) return false;
720
+ const [gotType = "", ...gotParams] = contentType.split(mediaParamSeparator);
721
+ const [type = "", subtype = ""] = gotType.split("/");
722
+ if (!type || !subtype) return false;
723
+ if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) return false;
724
+ if (gotParams.length < wantParams.length) return false;
725
+ const params = new Set(gotParams);
726
+ for (const wantParam of wantParams) if (!params.has(wantParam)) return false;
727
+ return true;
728
+ }
729
+ const codeRangeRE$1 = /* @__PURE__ */ new RegExp("^[0-9]xx$", "i");
730
+ function matchStatusCode(response, codes) {
731
+ const actual = `${response.status}`;
732
+ const expectedCodes = Array.isArray(codes) ? codes : [codes];
733
+ if (!expectedCodes.length) return false;
734
+ return expectedCodes.some((ec) => {
735
+ const code = `${ec}`;
736
+ if (code === "default") return true;
737
+ if (!codeRangeRE$1.test(`${code}`)) return code === actual;
738
+ const expectFamily = code.charAt(0);
739
+ if (!expectFamily) throw new Error("Invalid status code range");
740
+ const actualFamily = actual.charAt(0);
741
+ if (!actualFamily) throw new Error(`Invalid response status code: ${actual}`);
742
+ return actualFamily === expectFamily;
743
+ });
744
+ }
745
+ function matchResponse(response, code, contentTypePattern) {
746
+ return matchStatusCode(response, code) && matchContentType(response, contentTypePattern);
747
+ }
748
+ /**
749
+ * Uses various heurisitics to determine if an error is a connection error.
750
+ */
751
+ function isConnectionError(err) {
752
+ if (typeof err !== "object" || err == null) return false;
753
+ const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch");
754
+ const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed");
755
+ const isBunErr = "name" in err && err.name === "ConnectionError";
756
+ const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset";
757
+ return isBrowserErr || isNodeErr || isGenericErr || isBunErr;
758
+ }
759
+ /**
760
+ * Uses various heurisitics to determine if an error is a timeout error.
761
+ */
762
+ function isTimeoutError(err) {
763
+ if (typeof err !== "object" || err == null) return false;
764
+ const isNative = "name" in err && err.name === "TimeoutError";
765
+ const isLegacyNative = "code" in err && err.code === 23;
766
+ const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
767
+ return isNative || isLegacyNative || isGenericErr;
768
+ }
769
+ /**
770
+ * Uses various heurisitics to determine if an error is a abort error.
771
+ */
772
+ function isAbortError(err) {
773
+ if (typeof err !== "object" || err == null) return false;
774
+ const isNative = "name" in err && err.name === "AbortError";
775
+ const isLegacyNative = "code" in err && err.code === 20;
776
+ const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
777
+ return isNative || isLegacyNative || isGenericErr;
778
+ }
779
+ //#endregion
780
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/reasoningeffort.js
781
+ const ReasoningEffort = {
782
+ None: "none",
783
+ Minimal: "minimal",
784
+ Low: "low",
785
+ Medium: "medium",
786
+ High: "high",
787
+ Xhigh: "xhigh"
788
+ };
789
+ /** @internal */
790
+ const ReasoningEffort$inboundSchema = inboundSchema(ReasoningEffort);
791
+ /** @internal */
792
+ const ReasoningEffort$outboundSchema = outboundSchema(ReasoningEffort);
793
+ //#endregion
794
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/base64.js
795
+ function bytesToBase64(u8arr) {
796
+ return btoa(String.fromCodePoint(...u8arr));
797
+ }
798
+ function bytesFromBase64(encoded) {
799
+ return Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0));
800
+ }
801
+ function stringToBytes(str) {
802
+ return new TextEncoder().encode(str);
803
+ }
804
+ function stringToBase64(str) {
805
+ return bytesToBase64(stringToBytes(str));
806
+ }
807
+ z$1.custom((x) => x instanceof Uint8Array).or(z$1.string().transform(stringToBytes));
808
+ z$1.custom((x) => x instanceof Uint8Array).or(z$1.string().transform(bytesFromBase64));
809
+ //#endregion
810
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/is-plain-object.js
811
+ function isPlainObject(value) {
812
+ if (typeof value !== "object" || value === null) return false;
813
+ const prototype = Object.getPrototypeOf(value);
814
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
815
+ }
816
+ function formEncoder(sep) {
817
+ return (key, value, options) => {
818
+ let out = "";
819
+ const pairs = options?.explode ? explode(key, value) : [[key, value]];
820
+ if (pairs.every(([_, v]) => v == null)) return;
821
+ const encodeString = (v) => {
822
+ return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
823
+ };
824
+ const encodeValue = (v) => encodeString(serializeValue(v));
825
+ const encodedSep = encodeString(sep);
826
+ pairs.forEach(([pk, pv]) => {
827
+ let tmp = "";
828
+ let encValue = null;
829
+ if (pv == null) return;
830
+ else if (Array.isArray(pv)) encValue = mapDefined(pv, (v) => `${encodeValue(v)}`)?.join(encodedSep);
831
+ else if (isPlainObject(pv)) encValue = mapDefinedEntries(Object.entries(pv), ([k, v]) => {
832
+ return `${encodeString(k)}${encodedSep}${encodeValue(v)}`;
833
+ })?.join(encodedSep);
834
+ else encValue = `${encodeValue(pv)}`;
835
+ if (encValue == null) return;
836
+ tmp = `${encodeString(pk)}=${encValue}`;
837
+ if (!tmp || tmp === "=") return;
838
+ out += `&${tmp}`;
839
+ });
840
+ return out.slice(1);
841
+ };
842
+ }
843
+ const encodeForm = formEncoder(",");
844
+ function encodeJSON(key, value, options) {
845
+ if (typeof value === "undefined") return;
846
+ const encodeString = (v) => {
847
+ return options?.charEncoding === "percent" ? encodeURIComponent(v) : v;
848
+ };
849
+ const encVal = encodeString(JSON.stringify(value, jsonReplacer));
850
+ return options?.explode ? encVal : `${encodeString(key)}=${encVal}`;
851
+ }
852
+ function explode(key, value) {
853
+ if (Array.isArray(value)) return value.map((v) => [key, v]);
854
+ else if (isPlainObject(value)) return Object.entries(value ?? {}).map(([k, v]) => [k, v]);
855
+ else return [[key, value]];
856
+ }
857
+ function serializeValue(value) {
858
+ if (value == null) return "";
859
+ else if (value instanceof Date) return value.toISOString();
860
+ else if (value instanceof Uint8Array) return bytesToBase64(value);
861
+ else if (typeof value === "object") return JSON.stringify(value, jsonReplacer);
862
+ return `${value}`;
863
+ }
864
+ function jsonReplacer(_, value) {
865
+ if (value instanceof Uint8Array) return bytesToBase64(value);
866
+ else return value;
867
+ }
868
+ function mapDefined(inp, mapper) {
869
+ const res = inp.reduce((acc, v) => {
870
+ if (v == null) return acc;
871
+ const m = mapper(v);
872
+ if (m == null) return acc;
873
+ acc.push(m);
874
+ return acc;
875
+ }, []);
876
+ return res.length ? res : null;
877
+ }
878
+ function mapDefinedEntries(inp, mapper) {
879
+ const acc = [];
880
+ for (const [k, v] of inp) {
881
+ if (v == null) continue;
882
+ const m = mapper([k, v]);
883
+ if (m == null) continue;
884
+ acc.push(m);
885
+ }
886
+ return acc.length ? acc : null;
887
+ }
888
+ //#endregion
889
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/mistralerror.js
890
+ /** The base class for all HTTP error responses */
891
+ var MistralError = class extends Error {
892
+ /** HTTP status code */
893
+ statusCode;
894
+ /** HTTP body */
895
+ body;
896
+ /** HTTP headers */
897
+ headers;
898
+ /** HTTP content type */
899
+ contentType;
900
+ /** Raw response */
901
+ rawResponse;
902
+ constructor(message, httpMeta) {
903
+ super(message);
904
+ this.statusCode = httpMeta.response.status;
905
+ this.body = httpMeta.body;
906
+ this.headers = httpMeta.response.headers;
907
+ this.contentType = httpMeta.response.headers.get("content-type") || "";
908
+ this.rawResponse = httpMeta.response;
909
+ this.name = "MistralError";
910
+ }
911
+ };
912
+ //#endregion
913
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/responsevalidationerror.js
914
+ var ResponseValidationError = class extends MistralError {
915
+ /**
916
+ * The raw value that failed validation.
917
+ */
918
+ rawValue;
919
+ /**
920
+ * The raw message that failed validation.
921
+ */
922
+ rawMessage;
923
+ constructor(message, extra) {
924
+ super(message, extra);
925
+ this.name = "ResponseValidationError";
926
+ this.cause = extra.cause;
927
+ this.rawValue = extra.rawValue;
928
+ this.rawMessage = extra.rawMessage;
929
+ }
930
+ /**
931
+ * Return a pretty-formatted error message if the underlying validation error
932
+ * is a ZodError or some other recognized error type, otherwise return the
933
+ * default error message.
934
+ */
935
+ pretty() {
936
+ if (this.cause instanceof z$2.$ZodError) return `${this.rawMessage}\n${formatZodError(this.cause)}`;
937
+ else return this.toString();
938
+ }
939
+ };
940
+ //#endregion
941
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/sdkerror.js
942
+ /** The fallback error class if no more specific error class is matched */
943
+ var SDKError = class extends MistralError {
944
+ constructor(message, httpMeta) {
945
+ if (message) message += `: `;
946
+ message += `Status ${httpMeta.response.status}`;
947
+ const contentType = httpMeta.response.headers.get("content-type") || `""`;
948
+ if (contentType !== "application/json") message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
949
+ const body = httpMeta.body || `""`;
950
+ message += body.length > 100 ? "\n" : ". ";
951
+ let bodyDisplay = body;
952
+ if (body.length > 1e4) bodyDisplay = `${body.substring(0, 1e4)}...and ${body.length - 1e4} more chars`;
953
+ message += `Body: ${bodyDisplay}`;
954
+ message = message.trim();
955
+ super(message, httpMeta);
956
+ this.name = "SDKError";
957
+ }
958
+ };
959
+ //#endregion
960
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/matchers.js
961
+ const DEFAULT_CONTENT_TYPES = {
962
+ jsonl: "application/jsonl",
963
+ json: "application/json",
964
+ text: "text/plain",
965
+ bytes: "application/octet-stream",
966
+ stream: "application/octet-stream",
967
+ sse: "text/event-stream",
968
+ nil: "*",
969
+ fail: "*"
970
+ };
971
+ function jsonErr(codes, schema, options) {
972
+ return {
973
+ ...options,
974
+ err: true,
975
+ enc: "json",
976
+ codes,
977
+ schema
978
+ };
979
+ }
980
+ function json(codes, schema, options) {
981
+ return {
982
+ ...options,
983
+ enc: "json",
984
+ codes,
985
+ schema
986
+ };
987
+ }
988
+ function sse(codes, schema, options) {
989
+ return {
990
+ ...options,
991
+ enc: "sse",
992
+ codes,
993
+ schema
994
+ };
995
+ }
996
+ function fail(codes) {
997
+ return {
998
+ enc: "fail",
999
+ codes
1000
+ };
1001
+ }
1002
+ function match(...matchers) {
1003
+ return async function matchFunc(response, request, options) {
1004
+ let raw;
1005
+ let matcher;
1006
+ for (const match of matchers) {
1007
+ const { codes } = match;
1008
+ const ctpattern = "ctype" in match ? match.ctype : DEFAULT_CONTENT_TYPES[match.enc];
1009
+ if (ctpattern && matchResponse(response, codes, ctpattern)) {
1010
+ matcher = match;
1011
+ break;
1012
+ } else if (!ctpattern && matchStatusCode(response, codes)) {
1013
+ matcher = match;
1014
+ break;
1015
+ }
1016
+ }
1017
+ if (!matcher) return [{
1018
+ ok: false,
1019
+ error: new SDKError("Unexpected Status or Content-Type", {
1020
+ response,
1021
+ request,
1022
+ body: await response.text().catch(() => "")
1023
+ })
1024
+ }, raw];
1025
+ const encoding = matcher.enc;
1026
+ let body = "";
1027
+ switch (encoding) {
1028
+ case "json":
1029
+ body = await response.text();
1030
+ raw = JSON.parse(body);
1031
+ break;
1032
+ case "jsonl":
1033
+ raw = response.body;
1034
+ break;
1035
+ case "bytes":
1036
+ raw = new Uint8Array(await response.arrayBuffer());
1037
+ break;
1038
+ case "stream":
1039
+ raw = response.body;
1040
+ break;
1041
+ case "text":
1042
+ body = await response.text();
1043
+ raw = body;
1044
+ break;
1045
+ case "sse":
1046
+ raw = response.body;
1047
+ break;
1048
+ case "nil":
1049
+ body = await response.text();
1050
+ raw = void 0;
1051
+ break;
1052
+ case "fail":
1053
+ body = await response.text();
1054
+ raw = body;
1055
+ break;
1056
+ default: throw new Error(`Unsupported response type: ${encoding}`);
1057
+ }
1058
+ if (matcher.enc === "fail") return [{
1059
+ ok: false,
1060
+ error: new SDKError("API error occurred", {
1061
+ request,
1062
+ response,
1063
+ body
1064
+ })
1065
+ }, raw];
1066
+ const resultKey = matcher.key || options?.resultKey;
1067
+ let data;
1068
+ if ("err" in matcher) data = {
1069
+ ...options?.extraFields,
1070
+ ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
1071
+ ...isPlainObject(raw) ? raw : null,
1072
+ request$: request,
1073
+ response$: response,
1074
+ body$: body
1075
+ };
1076
+ else if (resultKey) data = {
1077
+ ...options?.extraFields,
1078
+ ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
1079
+ [resultKey]: raw
1080
+ };
1081
+ else if (matcher.hdrs) data = {
1082
+ ...options?.extraFields,
1083
+ ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null,
1084
+ ...isPlainObject(raw) ? raw : null
1085
+ };
1086
+ else data = raw;
1087
+ if ("err" in matcher) {
1088
+ const result = safeParseResponse(data, (v) => matcher.schema.parse(v), "Response validation failed", {
1089
+ request,
1090
+ response,
1091
+ body
1092
+ });
1093
+ return [result.ok ? {
1094
+ ok: false,
1095
+ error: result.value
1096
+ } : result, raw];
1097
+ } else return [safeParseResponse(data, (v) => matcher.schema.parse(v), "Response validation failed", {
1098
+ request,
1099
+ response,
1100
+ body
1101
+ }), raw];
1102
+ };
1103
+ }
1104
+ const headerValRE = /, */;
1105
+ /**
1106
+ * Iterates over a Headers object and returns an object with all the header
1107
+ * entries. Values are represented as an array to account for repeated headers.
1108
+ */
1109
+ function unpackHeaders(headers) {
1110
+ const out = {};
1111
+ for (const [k, v] of headers.entries()) out[k] = v.split(headerValRE);
1112
+ return out;
1113
+ }
1114
+ function safeParseResponse(rawValue, fn, errorMessage, httpMeta) {
1115
+ try {
1116
+ return OK(fn(rawValue));
1117
+ } catch (err) {
1118
+ return ERR(new ResponseValidationError(errorMessage, {
1119
+ cause: err,
1120
+ rawValue,
1121
+ rawMessage: errorMessage,
1122
+ ...httpMeta
1123
+ }));
1124
+ }
1125
+ }
1126
+ //#endregion
1127
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/dlv.js
1128
+ /**
1129
+ * @param obj The object to walk
1130
+ * @param key The key path to walk the object with
1131
+ * @param def A default value to return if the result is undefined
1132
+ *
1133
+ * @example
1134
+ * dlv(obj, "a.b.c.d")
1135
+ * @example
1136
+ * dlv(object, ["a", "b", "c", "d"])
1137
+ * @example
1138
+ * dlv(object, "foo.bar.baz", "Hello, default value!")
1139
+ */
1140
+ function dlv(obj, key, def, p, undef) {
1141
+ key = Array.isArray(key) ? key : key.split(".");
1142
+ for (p = 0; p < key.length; p++) {
1143
+ const k = key[p];
1144
+ obj = k != null && obj ? obj[k] : undef;
1145
+ }
1146
+ return obj === undef ? def : obj;
1147
+ }
1148
+ //#endregion
1149
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/env.js
1150
+ const envSchema = z$1.object({
1151
+ MISTRAL_API_KEY: z$1.string().optional(),
1152
+ MISTRAL_DEBUG: z$1.coerce.boolean().optional()
1153
+ });
1154
+ /**
1155
+ * Checks for the existence of the Deno global object to determine the environment.
1156
+ * @returns {boolean} True if the runtime is Deno, false otherwise.
1157
+ */
1158
+ function isDeno() {
1159
+ if ("Deno" in globalThis) return true;
1160
+ return false;
1161
+ }
1162
+ let envMemo = void 0;
1163
+ /**
1164
+ * Reads and validates environment variables.
1165
+ */
1166
+ function env() {
1167
+ if (envMemo) return envMemo;
1168
+ let envObject = {};
1169
+ if (isDeno()) envObject = globalThis.Deno?.env?.toObject?.() ?? {};
1170
+ else envObject = dlv(globalThis, "process.env") ?? {};
1171
+ envMemo = envSchema.parse(envObject);
1172
+ return envMemo;
1173
+ }
1174
+ //#endregion
1175
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/security.js
1176
+ var SecurityErrorCode;
1177
+ (function(SecurityErrorCode) {
1178
+ SecurityErrorCode["Incomplete"] = "incomplete";
1179
+ SecurityErrorCode["UnrecognisedSecurityType"] = "unrecognized_security_type";
1180
+ })(SecurityErrorCode || (SecurityErrorCode = {}));
1181
+ var SecurityError = class SecurityError extends Error {
1182
+ code;
1183
+ constructor(code, message) {
1184
+ super(message);
1185
+ this.code = code;
1186
+ this.name = "SecurityError";
1187
+ }
1188
+ static incomplete() {
1189
+ return new SecurityError(SecurityErrorCode.Incomplete, "Security requirements not met in order to perform the operation");
1190
+ }
1191
+ static unrecognizedType(type) {
1192
+ return new SecurityError(SecurityErrorCode.UnrecognisedSecurityType, `Unrecognised security type: ${type}`);
1193
+ }
1194
+ };
1195
+ function resolveSecurity(...options) {
1196
+ const state = {
1197
+ basic: {},
1198
+ headers: {},
1199
+ queryParams: {},
1200
+ cookies: {},
1201
+ oauth2: { type: "none" }
1202
+ };
1203
+ const option = options.find((opts) => {
1204
+ return opts.every((o) => {
1205
+ if (o.value == null) return false;
1206
+ else if (o.type === "http:basic") return o.value.username != null || o.value.password != null;
1207
+ else if (o.type === "http:custom") return null;
1208
+ else if (o.type === "oauth2:password") return typeof o.value === "string" && !!o.value;
1209
+ else if (o.type === "oauth2:client_credentials") {
1210
+ if (typeof o.value == "string") return !!o.value;
1211
+ return o.value.clientID != null || o.value.clientSecret != null;
1212
+ } else if (typeof o.value === "string") return !!o.value;
1213
+ else throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`);
1214
+ });
1215
+ });
1216
+ if (option == null) return null;
1217
+ option.forEach((spec) => {
1218
+ if (spec.value == null) return;
1219
+ const { type } = spec;
1220
+ switch (type) {
1221
+ case "apiKey:header":
1222
+ state.headers[spec.fieldName] = spec.value;
1223
+ break;
1224
+ case "apiKey:query":
1225
+ state.queryParams[spec.fieldName] = spec.value;
1226
+ break;
1227
+ case "apiKey:cookie":
1228
+ state.cookies[spec.fieldName] = spec.value;
1229
+ break;
1230
+ case "http:basic":
1231
+ applyBasic(state, spec);
1232
+ break;
1233
+ case "http:custom": break;
1234
+ case "http:bearer":
1235
+ applyBearer(state, spec);
1236
+ break;
1237
+ case "oauth2":
1238
+ applyBearer(state, spec);
1239
+ break;
1240
+ case "oauth2:password":
1241
+ applyBearer(state, spec);
1242
+ break;
1243
+ case "oauth2:client_credentials": break;
1244
+ case "openIdConnect":
1245
+ applyBearer(state, spec);
1246
+ break;
1247
+ default: throw SecurityError.unrecognizedType(type);
1248
+ }
1249
+ });
1250
+ return state;
1251
+ }
1252
+ function applyBasic(state, spec) {
1253
+ if (spec.value == null) return;
1254
+ state.basic = spec.value;
1255
+ }
1256
+ function applyBearer(state, spec) {
1257
+ if (typeof spec.value !== "string" || !spec.value) return;
1258
+ let value = spec.value;
1259
+ if (value.slice(0, 7).toLowerCase() !== "bearer ") value = `Bearer ${value}`;
1260
+ if (spec.fieldName !== void 0) state.headers[spec.fieldName] = value;
1261
+ }
1262
+ function resolveGlobalSecurity(security, allowedFields) {
1263
+ let inputs = [[{
1264
+ fieldName: "Authorization",
1265
+ type: "http:bearer",
1266
+ value: security?.apiKey ?? env().MISTRAL_API_KEY
1267
+ }]];
1268
+ if (allowedFields) inputs = allowedFields.map((i) => {
1269
+ if (i < 0 || i >= inputs.length) throw new RangeError(`invalid allowedFields index ${i}`);
1270
+ return inputs[i];
1271
+ });
1272
+ return resolveSecurity(...inputs);
1273
+ }
1274
+ async function extractSecurity(sec) {
1275
+ if (sec == null) return;
1276
+ return typeof sec === "function" ? sec() : sec;
1277
+ }
1278
+ //#endregion
1279
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/url.js
1280
+ const hasOwn = Object.prototype.hasOwnProperty;
1281
+ function pathToFunc(pathPattern, options) {
1282
+ const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;
1283
+ return function buildURLPath(params = {}) {
1284
+ return pathPattern.replace(paramRE, function(_, placeholder) {
1285
+ if (!hasOwn.call(params, placeholder)) throw new Error(`Parameter '${placeholder}' is required`);
1286
+ const value = params[placeholder];
1287
+ if (typeof value !== "string" && typeof value !== "number") throw new Error(`Parameter '${placeholder}' must be a string or number`);
1288
+ return options?.charEncoding === "percent" ? encodeURIComponent(`${value}`) : `${value}`;
1289
+ }).replace(/^\/+/, "");
1290
+ };
1291
+ }
1292
+ //#endregion
1293
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/toolconfiguration.js
1294
+ /** @internal */
1295
+ const ToolConfiguration$inboundSchema = z$1.object({
1296
+ exclude: z$1.nullable(z$1.array(z$1.string())).optional(),
1297
+ include: z$1.nullable(z$1.array(z$1.string())).optional(),
1298
+ requires_confirmation: z$1.nullable(z$1.array(z$1.string())).optional()
1299
+ }).transform((v) => {
1300
+ return remap(v, { "requires_confirmation": "requiresConfirmation" });
1301
+ });
1302
+ /** @internal */
1303
+ const ToolConfiguration$outboundSchema = z$1.object({
1304
+ exclude: z$1.nullable(z$1.array(z$1.string())).optional(),
1305
+ include: z$1.nullable(z$1.array(z$1.string())).optional(),
1306
+ requiresConfirmation: z$1.nullable(z$1.array(z$1.string())).optional()
1307
+ }).transform((v) => {
1308
+ return remap(v, { requiresConfirmation: "requires_confirmation" });
1309
+ });
1310
+ z$1.object({
1311
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional(),
1312
+ type: z$1.literal("code_interpreter")
1313
+ }).transform((v) => {
1314
+ return remap(v, { "tool_configuration": "toolConfiguration" });
1315
+ });
1316
+ /** @internal */
1317
+ const CodeInterpreterTool$outboundSchema = z$1.object({
1318
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional(),
1319
+ type: z$1.literal("code_interpreter")
1320
+ }).transform((v) => {
1321
+ return remap(v, { toolConfiguration: "tool_configuration" });
1322
+ });
1323
+ z$1.object({
1324
+ type: z$1.literal("content").default("content"),
1325
+ content: z$1.string().default("")
1326
+ });
1327
+ /** @internal */
1328
+ const Prediction$outboundSchema = z$1.object({
1329
+ type: z$1.literal("content").default("content"),
1330
+ content: z$1.string().default("")
1331
+ });
1332
+ //#endregion
1333
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/jsonschema.js
1334
+ /** @internal */
1335
+ const JsonSchema$inboundSchema = z$1.object({
1336
+ name: z$1.string(),
1337
+ description: z$1.nullable(z$1.string()).optional(),
1338
+ schema: z$1.record(z$1.string(), z$1.any()),
1339
+ strict: z$1.boolean().optional()
1340
+ }).transform((v) => {
1341
+ return remap(v, { "schema": "schemaDefinition" });
1342
+ });
1343
+ /** @internal */
1344
+ const JsonSchema$outboundSchema = z$1.object({
1345
+ name: z$1.string(),
1346
+ description: z$1.nullable(z$1.string()).optional(),
1347
+ schemaDefinition: z$1.record(z$1.string(), z$1.any()),
1348
+ strict: z$1.boolean().optional()
1349
+ }).transform((v) => {
1350
+ return remap(v, { schemaDefinition: "schema" });
1351
+ });
1352
+ //#endregion
1353
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/responseformats.js
1354
+ const ResponseFormats = {
1355
+ Text: "text",
1356
+ JsonObject: "json_object",
1357
+ JsonSchema: "json_schema"
1358
+ };
1359
+ /** @internal */
1360
+ const ResponseFormats$inboundSchema = inboundSchema(ResponseFormats);
1361
+ /** @internal */
1362
+ const ResponseFormats$outboundSchema = outboundSchema(ResponseFormats);
1363
+ z$1.object({
1364
+ type: ResponseFormats$inboundSchema.optional(),
1365
+ json_schema: z$1.nullable(JsonSchema$inboundSchema).optional()
1366
+ }).transform((v) => {
1367
+ return remap(v, { "json_schema": "jsonSchema" });
1368
+ });
1369
+ /** @internal */
1370
+ const ResponseFormat$outboundSchema = z$1.object({
1371
+ type: ResponseFormats$outboundSchema.optional(),
1372
+ jsonSchema: z$1.nullable(JsonSchema$outboundSchema).optional()
1373
+ }).transform((v) => {
1374
+ return remap(v, { jsonSchema: "json_schema" });
1375
+ });
1376
+ //#endregion
1377
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/toolchoiceenum.js
1378
+ const ToolChoiceEnum = {
1379
+ Auto: "auto",
1380
+ None: "none",
1381
+ Any: "any",
1382
+ Required: "required"
1383
+ };
1384
+ inboundSchema(ToolChoiceEnum);
1385
+ /** @internal */
1386
+ const ToolChoiceEnum$outboundSchema = outboundSchema(ToolChoiceEnum);
1387
+ //#endregion
1388
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/apikeyauth.js
1389
+ /** @internal */
1390
+ const APIKeyAuth$inboundSchema = z$1.object({
1391
+ type: z$1.literal("api-key"),
1392
+ value: z$1.string()
1393
+ });
1394
+ /** @internal */
1395
+ const APIKeyAuth$outboundSchema = z$1.object({
1396
+ type: z$1.literal("api-key"),
1397
+ value: z$1.string()
1398
+ });
1399
+ //#endregion
1400
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/oauth2tokenauth.js
1401
+ /** @internal */
1402
+ const OAuth2TokenAuth$inboundSchema = z$1.object({
1403
+ type: z$1.literal("oauth2-token"),
1404
+ value: z$1.string()
1405
+ });
1406
+ /** @internal */
1407
+ const OAuth2TokenAuth$outboundSchema = z$1.object({
1408
+ type: z$1.literal("oauth2-token"),
1409
+ value: z$1.string()
1410
+ });
1411
+ discriminatedUnion("type", {
1412
+ ["api-key"]: APIKeyAuth$inboundSchema,
1413
+ ["oauth2-token"]: OAuth2TokenAuth$inboundSchema
1414
+ });
1415
+ z$1.union([APIKeyAuth$outboundSchema, OAuth2TokenAuth$outboundSchema]);
1416
+ z$1.object({
1417
+ type: z$1.literal("connector"),
1418
+ connector_id: z$1.string(),
1419
+ authorization: z$1.nullable(discriminatedUnion("type", {
1420
+ ["api-key"]: APIKeyAuth$inboundSchema,
1421
+ ["oauth2-token"]: OAuth2TokenAuth$inboundSchema
1422
+ })).optional(),
1423
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional()
1424
+ }).transform((v) => {
1425
+ return remap(v, {
1426
+ "connector_id": "connectorId",
1427
+ "tool_configuration": "toolConfiguration"
1428
+ });
1429
+ });
1430
+ /** @internal */
1431
+ const CustomConnector$outboundSchema = z$1.object({
1432
+ type: z$1.literal("connector"),
1433
+ connectorId: z$1.string(),
1434
+ authorization: z$1.nullable(z$1.union([APIKeyAuth$outboundSchema, OAuth2TokenAuth$outboundSchema])).optional(),
1435
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional()
1436
+ }).transform((v) => {
1437
+ return remap(v, {
1438
+ connectorId: "connector_id",
1439
+ toolConfiguration: "tool_configuration"
1440
+ });
1441
+ });
1442
+ z$1.object({
1443
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional(),
1444
+ type: z$1.literal("document_library"),
1445
+ library_ids: z$1.array(z$1.string())
1446
+ }).transform((v) => {
1447
+ return remap(v, {
1448
+ "tool_configuration": "toolConfiguration",
1449
+ "library_ids": "libraryIds"
1450
+ });
1451
+ });
1452
+ /** @internal */
1453
+ const DocumentLibraryTool$outboundSchema = z$1.object({
1454
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional(),
1455
+ type: z$1.literal("document_library"),
1456
+ libraryIds: z$1.array(z$1.string())
1457
+ }).transform((v) => {
1458
+ return remap(v, {
1459
+ toolConfiguration: "tool_configuration",
1460
+ libraryIds: "library_ids"
1461
+ });
1462
+ });
1463
+ //#endregion
1464
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/function.js
1465
+ /** @internal */
1466
+ const FunctionT$inboundSchema = z$1.object({
1467
+ name: z$1.string(),
1468
+ description: z$1.string().optional(),
1469
+ strict: z$1.boolean().optional(),
1470
+ parameters: z$1.record(z$1.string(), z$1.any())
1471
+ });
1472
+ /** @internal */
1473
+ const FunctionT$outboundSchema = z$1.object({
1474
+ name: z$1.string(),
1475
+ description: z$1.string().optional(),
1476
+ strict: z$1.boolean().optional(),
1477
+ parameters: z$1.record(z$1.string(), z$1.any())
1478
+ });
1479
+ //#endregion
1480
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/moderationllmaction.js
1481
+ const ModerationLLMAction = {
1482
+ None: "none",
1483
+ Block: "block"
1484
+ };
1485
+ /** @internal */
1486
+ const ModerationLLMAction$inboundSchema = inboundSchema(ModerationLLMAction);
1487
+ /** @internal */
1488
+ const ModerationLLMAction$outboundSchema = outboundSchema(ModerationLLMAction);
1489
+ //#endregion
1490
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/moderationllmv1categorythresholds.js
1491
+ /** @internal */
1492
+ const ModerationLlmv1CategoryThresholds$inboundSchema = z$1.object({
1493
+ sexual: z$1.nullable(z$1.number()).optional(),
1494
+ hate_and_discrimination: z$1.nullable(z$1.number()).optional(),
1495
+ violence_and_threats: z$1.nullable(z$1.number()).optional(),
1496
+ dangerous_and_criminal_content: z$1.nullable(z$1.number()).optional(),
1497
+ selfharm: z$1.nullable(z$1.number()).optional(),
1498
+ health: z$1.nullable(z$1.number()).optional(),
1499
+ financial: z$1.nullable(z$1.number()).optional(),
1500
+ law: z$1.nullable(z$1.number()).optional(),
1501
+ pii: z$1.nullable(z$1.number()).optional()
1502
+ }).transform((v) => {
1503
+ return remap(v, {
1504
+ "hate_and_discrimination": "hateAndDiscrimination",
1505
+ "violence_and_threats": "violenceAndThreats",
1506
+ "dangerous_and_criminal_content": "dangerousAndCriminalContent"
1507
+ });
1508
+ });
1509
+ /** @internal */
1510
+ const ModerationLlmv1CategoryThresholds$outboundSchema = z$1.object({
1511
+ sexual: z$1.nullable(z$1.number()).optional(),
1512
+ hateAndDiscrimination: z$1.nullable(z$1.number()).optional(),
1513
+ violenceAndThreats: z$1.nullable(z$1.number()).optional(),
1514
+ dangerousAndCriminalContent: z$1.nullable(z$1.number()).optional(),
1515
+ selfharm: z$1.nullable(z$1.number()).optional(),
1516
+ health: z$1.nullable(z$1.number()).optional(),
1517
+ financial: z$1.nullable(z$1.number()).optional(),
1518
+ law: z$1.nullable(z$1.number()).optional(),
1519
+ pii: z$1.nullable(z$1.number()).optional()
1520
+ }).transform((v) => {
1521
+ return remap(v, {
1522
+ hateAndDiscrimination: "hate_and_discrimination",
1523
+ violenceAndThreats: "violence_and_threats",
1524
+ dangerousAndCriminalContent: "dangerous_and_criminal_content"
1525
+ });
1526
+ });
1527
+ //#endregion
1528
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/moderationllmv1config.js
1529
+ /** @internal */
1530
+ const ModerationLlmv1Config$inboundSchema = z$1.object({
1531
+ model_name: z$1.string().default("mistral-moderation-2411"),
1532
+ custom_category_thresholds: z$1.nullable(ModerationLlmv1CategoryThresholds$inboundSchema).optional(),
1533
+ ignore_other_categories: z$1.boolean().default(false),
1534
+ action: ModerationLLMAction$inboundSchema.optional()
1535
+ }).transform((v) => {
1536
+ return remap(v, {
1537
+ "model_name": "modelName",
1538
+ "custom_category_thresholds": "customCategoryThresholds",
1539
+ "ignore_other_categories": "ignoreOtherCategories"
1540
+ });
1541
+ });
1542
+ /** @internal */
1543
+ const ModerationLlmv1Config$outboundSchema = z$1.object({
1544
+ modelName: z$1.string().default("mistral-moderation-2411"),
1545
+ customCategoryThresholds: z$1.nullable(ModerationLlmv1CategoryThresholds$outboundSchema).optional(),
1546
+ ignoreOtherCategories: z$1.boolean().default(false),
1547
+ action: ModerationLLMAction$outboundSchema.optional()
1548
+ }).transform((v) => {
1549
+ return remap(v, {
1550
+ modelName: "model_name",
1551
+ customCategoryThresholds: "custom_category_thresholds",
1552
+ ignoreOtherCategories: "ignore_other_categories"
1553
+ });
1554
+ });
1555
+ //#endregion
1556
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/moderationllmv2categorythresholds.js
1557
+ /** @internal */
1558
+ const ModerationLlmv2CategoryThresholds$inboundSchema = z$1.object({
1559
+ sexual: z$1.nullable(z$1.number()).optional(),
1560
+ hate_and_discrimination: z$1.nullable(z$1.number()).optional(),
1561
+ violence_and_threats: z$1.nullable(z$1.number()).optional(),
1562
+ dangerous: z$1.nullable(z$1.number()).optional(),
1563
+ criminal: z$1.nullable(z$1.number()).optional(),
1564
+ selfharm: z$1.nullable(z$1.number()).optional(),
1565
+ health: z$1.nullable(z$1.number()).optional(),
1566
+ financial: z$1.nullable(z$1.number()).optional(),
1567
+ law: z$1.nullable(z$1.number()).optional(),
1568
+ pii: z$1.nullable(z$1.number()).optional(),
1569
+ jailbreaking: z$1.nullable(z$1.number()).optional()
1570
+ }).transform((v) => {
1571
+ return remap(v, {
1572
+ "hate_and_discrimination": "hateAndDiscrimination",
1573
+ "violence_and_threats": "violenceAndThreats"
1574
+ });
1575
+ });
1576
+ /** @internal */
1577
+ const ModerationLlmv2CategoryThresholds$outboundSchema = z$1.object({
1578
+ sexual: z$1.nullable(z$1.number()).optional(),
1579
+ hateAndDiscrimination: z$1.nullable(z$1.number()).optional(),
1580
+ violenceAndThreats: z$1.nullable(z$1.number()).optional(),
1581
+ dangerous: z$1.nullable(z$1.number()).optional(),
1582
+ criminal: z$1.nullable(z$1.number()).optional(),
1583
+ selfharm: z$1.nullable(z$1.number()).optional(),
1584
+ health: z$1.nullable(z$1.number()).optional(),
1585
+ financial: z$1.nullable(z$1.number()).optional(),
1586
+ law: z$1.nullable(z$1.number()).optional(),
1587
+ pii: z$1.nullable(z$1.number()).optional(),
1588
+ jailbreaking: z$1.nullable(z$1.number()).optional()
1589
+ }).transform((v) => {
1590
+ return remap(v, {
1591
+ hateAndDiscrimination: "hate_and_discrimination",
1592
+ violenceAndThreats: "violence_and_threats"
1593
+ });
1594
+ });
1595
+ //#endregion
1596
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/moderationllmv2config.js
1597
+ /** @internal */
1598
+ const ModerationLlmv2Config$inboundSchema = z$1.object({
1599
+ model_name: z$1.string().default("mistral-moderation-2603"),
1600
+ custom_category_thresholds: z$1.nullable(ModerationLlmv2CategoryThresholds$inboundSchema).optional(),
1601
+ ignore_other_categories: z$1.boolean().default(false),
1602
+ action: ModerationLLMAction$inboundSchema.optional()
1603
+ }).transform((v) => {
1604
+ return remap(v, {
1605
+ "model_name": "modelName",
1606
+ "custom_category_thresholds": "customCategoryThresholds",
1607
+ "ignore_other_categories": "ignoreOtherCategories"
1608
+ });
1609
+ });
1610
+ /** @internal */
1611
+ const ModerationLlmv2Config$outboundSchema = z$1.object({
1612
+ modelName: z$1.string().default("mistral-moderation-2603"),
1613
+ customCategoryThresholds: z$1.nullable(ModerationLlmv2CategoryThresholds$outboundSchema).optional(),
1614
+ ignoreOtherCategories: z$1.boolean().default(false),
1615
+ action: ModerationLLMAction$outboundSchema.optional()
1616
+ }).transform((v) => {
1617
+ return remap(v, {
1618
+ modelName: "model_name",
1619
+ customCategoryThresholds: "custom_category_thresholds",
1620
+ ignoreOtherCategories: "ignore_other_categories"
1621
+ });
1622
+ });
1623
+ z$1.object({
1624
+ block_on_error: z$1.boolean().default(false),
1625
+ moderation_llm_v1: z$1.nullable(ModerationLlmv1Config$inboundSchema).optional(),
1626
+ moderation_llm_v2: z$1.nullable(ModerationLlmv2Config$inboundSchema).optional()
1627
+ }).transform((v) => {
1628
+ return remap(v, {
1629
+ "block_on_error": "blockOnError",
1630
+ "moderation_llm_v1": "moderationLlmV1",
1631
+ "moderation_llm_v2": "moderationLlmV2"
1632
+ });
1633
+ });
1634
+ /** @internal */
1635
+ const GuardrailConfig$outboundSchema = z$1.object({
1636
+ blockOnError: z$1.boolean().default(false),
1637
+ moderationLlmV1: z$1.nullable(ModerationLlmv1Config$outboundSchema).optional(),
1638
+ moderationLlmV2: z$1.nullable(ModerationLlmv2Config$outboundSchema).optional()
1639
+ }).transform((v) => {
1640
+ return remap(v, {
1641
+ blockOnError: "block_on_error",
1642
+ moderationLlmV1: "moderation_llm_v1",
1643
+ moderationLlmV2: "moderation_llm_v2"
1644
+ });
1645
+ });
1646
+ z$1.object({
1647
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional(),
1648
+ type: z$1.literal("image_generation")
1649
+ }).transform((v) => {
1650
+ return remap(v, { "tool_configuration": "toolConfiguration" });
1651
+ });
1652
+ /** @internal */
1653
+ const ImageGenerationTool$outboundSchema = z$1.object({
1654
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional(),
1655
+ type: z$1.literal("image_generation")
1656
+ }).transform((v) => {
1657
+ return remap(v, { toolConfiguration: "tool_configuration" });
1658
+ });
1659
+ z$1.object({
1660
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional(),
1661
+ type: z$1.literal("web_search_premium")
1662
+ }).transform((v) => {
1663
+ return remap(v, { "tool_configuration": "toolConfiguration" });
1664
+ });
1665
+ /** @internal */
1666
+ const WebSearchPremiumTool$outboundSchema = z$1.object({
1667
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional(),
1668
+ type: z$1.literal("web_search_premium")
1669
+ }).transform((v) => {
1670
+ return remap(v, { toolConfiguration: "tool_configuration" });
1671
+ });
1672
+ z$1.object({
1673
+ tool_configuration: z$1.nullable(ToolConfiguration$inboundSchema).optional(),
1674
+ type: z$1.literal("web_search")
1675
+ }).transform((v) => {
1676
+ return remap(v, { "tool_configuration": "toolConfiguration" });
1677
+ });
1678
+ /** @internal */
1679
+ const WebSearchTool$outboundSchema = z$1.object({
1680
+ toolConfiguration: z$1.nullable(ToolConfiguration$outboundSchema).optional(),
1681
+ type: z$1.literal("web_search")
1682
+ }).transform((v) => {
1683
+ return remap(v, { toolConfiguration: "tool_configuration" });
1684
+ });
1685
+ smartUnion([z$1.string(), z$1.array(ContentChunk$inboundSchema)]);
1686
+ smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)]);
1687
+ /** @internal */
1688
+ const AssistantMessage$inboundSchema = z$1.object({
1689
+ role: z$1.literal("assistant").default("assistant"),
1690
+ content: z$1.nullable(smartUnion([z$1.string(), z$1.array(ContentChunk$inboundSchema)])).optional(),
1691
+ tool_calls: z$1.nullable(z$1.array(ToolCall$inboundSchema)).optional(),
1692
+ prefix: z$1.boolean().default(false)
1693
+ }).transform((v) => {
1694
+ return remap(v, { "tool_calls": "toolCalls" });
1695
+ });
1696
+ /** @internal */
1697
+ const AssistantMessage$outboundSchema = z$1.object({
1698
+ role: z$1.literal("assistant").default("assistant"),
1699
+ content: z$1.nullable(smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)])).optional(),
1700
+ toolCalls: z$1.nullable(z$1.array(ToolCall$outboundSchema)).optional(),
1701
+ prefix: z$1.boolean().default(false)
1702
+ }).transform((v) => {
1703
+ return remap(v, { toolCalls: "tool_calls" });
1704
+ });
1705
+ /** @internal */
1706
+ const MistralPromptMode$outboundSchema = outboundSchema({ Reasoning: "reasoning" });
1707
+ /** @internal */
1708
+ const RequestedServiceTier$outboundSchema = z$1.enum({
1709
+ Auto: "auto",
1710
+ StandardOnly: "standard_only"
1711
+ });
1712
+ //#endregion
1713
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/systemmessagecontentchunks.js
1714
+ /** @internal */
1715
+ const SystemMessageContentChunks$outboundSchema = z$1.union([TextChunk$outboundSchema.and(z$1.object({ type: z$1.literal("text") })), ThinkChunk$outboundSchema.and(z$1.object({ type: z$1.literal("thinking") }))]);
1716
+ smartUnion([z$1.string(), z$1.array(SystemMessageContentChunks$outboundSchema)]);
1717
+ /** @internal */
1718
+ const SystemMessage$outboundSchema = z$1.object({
1719
+ role: z$1.literal("system"),
1720
+ content: smartUnion([z$1.string(), z$1.array(SystemMessageContentChunks$outboundSchema)])
1721
+ });
1722
+ z$1.object({
1723
+ type: ToolTypes$inboundSchema.default("function"),
1724
+ function: FunctionT$inboundSchema
1725
+ });
1726
+ /** @internal */
1727
+ const Tool$outboundSchema = z$1.object({
1728
+ type: ToolTypes$outboundSchema.default("function"),
1729
+ function: FunctionT$outboundSchema
1730
+ });
1731
+ //#endregion
1732
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/functionname.js
1733
+ /** @internal */
1734
+ const FunctionName$outboundSchema = z$1.object({ name: z$1.string() });
1735
+ //#endregion
1736
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/toolchoice.js
1737
+ /** @internal */
1738
+ const ToolChoice$outboundSchema = z$1.object({
1739
+ type: ToolTypes$outboundSchema.default("function"),
1740
+ function: FunctionName$outboundSchema
1741
+ });
1742
+ smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)]);
1743
+ /** @internal */
1744
+ const ToolMessage$outboundSchema = z$1.object({
1745
+ role: z$1.literal("tool"),
1746
+ content: z$1.nullable(smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)])),
1747
+ toolCallId: z$1.nullable(z$1.string()).optional(),
1748
+ name: z$1.nullable(z$1.string()).optional()
1749
+ }).transform((v) => {
1750
+ return remap(v, { toolCallId: "tool_call_id" });
1751
+ });
1752
+ smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)]);
1753
+ /** @internal */
1754
+ const UserMessage$outboundSchema = z$1.object({
1755
+ role: z$1.literal("user"),
1756
+ content: z$1.nullable(smartUnion([z$1.string(), z$1.array(ContentChunk$outboundSchema)]))
1757
+ });
1758
+ /** @internal */
1759
+ const ChatCompletionChoiceFinishReason$inboundSchema = inboundSchema({
1760
+ Stop: "stop",
1761
+ Length: "length",
1762
+ ModelLength: "model_length",
1763
+ Error: "error",
1764
+ ToolCalls: "tool_calls"
1765
+ });
1766
+ /** @internal */
1767
+ const ChatCompletionChoice$inboundSchema = z$1.object({
1768
+ index: z$1.int(),
1769
+ message: AssistantMessage$inboundSchema.optional(),
1770
+ messages: z$1.array(DeltaMessage$inboundSchema).optional(),
1771
+ finish_reason: ChatCompletionChoiceFinishReason$inboundSchema
1772
+ }).transform((v) => {
1773
+ return remap(v, { "finish_reason": "finishReason" });
1774
+ });
1775
+ smartUnion([z$1.string(), z$1.array(z$1.string())]);
1776
+ z$1.union([
1777
+ AssistantMessage$outboundSchema.and(z$1.object({ role: z$1.literal("assistant") })),
1778
+ SystemMessage$outboundSchema,
1779
+ ToolMessage$outboundSchema,
1780
+ UserMessage$outboundSchema
1781
+ ]);
1782
+ z$1.union([
1783
+ Tool$outboundSchema.and(z$1.object({ type: z$1.literal("function") })),
1784
+ WebSearchTool$outboundSchema,
1785
+ WebSearchPremiumTool$outboundSchema,
1786
+ CodeInterpreterTool$outboundSchema,
1787
+ ImageGenerationTool$outboundSchema,
1788
+ DocumentLibraryTool$outboundSchema,
1789
+ CustomConnector$outboundSchema
1790
+ ]);
1791
+ smartUnion([ToolChoice$outboundSchema, ToolChoiceEnum$outboundSchema]);
1792
+ /** @internal */
1793
+ const ChatCompletionRequest$outboundSchema = z$1.object({
1794
+ model: z$1.string(),
1795
+ temperature: z$1.nullable(z$1.number()).optional(),
1796
+ topP: z$1.nullable(z$1.number()).optional(),
1797
+ maxTokens: z$1.nullable(z$1.int()).optional(),
1798
+ stream: z$1.boolean().default(false),
1799
+ stop: z$1.nullable(smartUnion([z$1.string(), z$1.array(z$1.string())])).optional(),
1800
+ randomSeed: z$1.nullable(z$1.int()).optional(),
1801
+ metadata: z$1.nullable(z$1.record(z$1.string(), z$1.any())).optional(),
1802
+ messages: z$1.array(z$1.union([
1803
+ AssistantMessage$outboundSchema.and(z$1.object({ role: z$1.literal("assistant") })),
1804
+ SystemMessage$outboundSchema,
1805
+ ToolMessage$outboundSchema,
1806
+ UserMessage$outboundSchema
1807
+ ])),
1808
+ responseFormat: ResponseFormat$outboundSchema.optional(),
1809
+ tools: z$1.nullable(z$1.array(z$1.union([
1810
+ Tool$outboundSchema.and(z$1.object({ type: z$1.literal("function") })),
1811
+ WebSearchTool$outboundSchema,
1812
+ WebSearchPremiumTool$outboundSchema,
1813
+ CodeInterpreterTool$outboundSchema,
1814
+ ImageGenerationTool$outboundSchema,
1815
+ DocumentLibraryTool$outboundSchema,
1816
+ CustomConnector$outboundSchema
1817
+ ]))).optional(),
1818
+ toolChoice: smartUnion([ToolChoice$outboundSchema, ToolChoiceEnum$outboundSchema]).optional(),
1819
+ presencePenalty: z$1.nullable(z$1.number()).optional(),
1820
+ frequencyPenalty: z$1.nullable(z$1.number()).optional(),
1821
+ n: z$1.nullable(z$1.int()).optional(),
1822
+ prediction: Prediction$outboundSchema.optional(),
1823
+ parallelToolCalls: z$1.boolean().optional(),
1824
+ reasoningEffort: z$1.nullable(ReasoningEffort$outboundSchema).optional(),
1825
+ promptMode: z$1.nullable(MistralPromptMode$outboundSchema).optional(),
1826
+ guardrails: z$1.nullable(z$1.array(GuardrailConfig$outboundSchema)).optional(),
1827
+ promptCacheKey: z$1.nullable(z$1.string()).optional(),
1828
+ serviceTier: z$1.nullable(RequestedServiceTier$outboundSchema).optional(),
1829
+ safePrompt: z$1.boolean().optional()
1830
+ }).transform((v) => {
1831
+ return remap(v, {
1832
+ topP: "top_p",
1833
+ maxTokens: "max_tokens",
1834
+ randomSeed: "random_seed",
1835
+ responseFormat: "response_format",
1836
+ toolChoice: "tool_choice",
1837
+ presencePenalty: "presence_penalty",
1838
+ frequencyPenalty: "frequency_penalty",
1839
+ parallelToolCalls: "parallel_tool_calls",
1840
+ reasoningEffort: "reasoning_effort",
1841
+ promptMode: "prompt_mode",
1842
+ promptCacheKey: "prompt_cache_key",
1843
+ serviceTier: "service_tier",
1844
+ safePrompt: "safe_prompt"
1845
+ });
1846
+ });
1847
+ //#endregion
1848
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/chatcompletionresponse.js
1849
+ /** @internal */
1850
+ const ChatCompletionResponse$inboundSchema = z$1.object({
1851
+ id: z$1.string(),
1852
+ object: z$1.string(),
1853
+ model: z$1.string(),
1854
+ usage: UsageInfo$inboundSchema,
1855
+ created: z$1.int(),
1856
+ choices: z$1.array(ChatCompletionChoice$inboundSchema)
1857
+ });
1858
+ smartUnion([z$1.string(), z$1.array(z$1.string())]);
1859
+ z$1.union([
1860
+ AssistantMessage$outboundSchema.and(z$1.object({ role: z$1.literal("assistant") })),
1861
+ SystemMessage$outboundSchema,
1862
+ ToolMessage$outboundSchema,
1863
+ UserMessage$outboundSchema
1864
+ ]);
1865
+ z$1.union([
1866
+ Tool$outboundSchema.and(z$1.object({ type: z$1.literal("function") })),
1867
+ WebSearchTool$outboundSchema,
1868
+ WebSearchPremiumTool$outboundSchema,
1869
+ CodeInterpreterTool$outboundSchema,
1870
+ ImageGenerationTool$outboundSchema,
1871
+ DocumentLibraryTool$outboundSchema,
1872
+ CustomConnector$outboundSchema
1873
+ ]);
1874
+ smartUnion([ToolChoice$outboundSchema, ToolChoiceEnum$outboundSchema]);
1875
+ /** @internal */
1876
+ const ChatCompletionStreamRequest$outboundSchema = z$1.object({
1877
+ model: z$1.string(),
1878
+ temperature: z$1.nullable(z$1.number()).optional(),
1879
+ topP: z$1.nullable(z$1.number()).optional(),
1880
+ maxTokens: z$1.nullable(z$1.int()).optional(),
1881
+ stream: z$1.boolean().default(true),
1882
+ stop: z$1.nullable(smartUnion([z$1.string(), z$1.array(z$1.string())])).optional(),
1883
+ randomSeed: z$1.nullable(z$1.int()).optional(),
1884
+ metadata: z$1.nullable(z$1.record(z$1.string(), z$1.any())).optional(),
1885
+ messages: z$1.array(z$1.union([
1886
+ AssistantMessage$outboundSchema.and(z$1.object({ role: z$1.literal("assistant") })),
1887
+ SystemMessage$outboundSchema,
1888
+ ToolMessage$outboundSchema,
1889
+ UserMessage$outboundSchema
1890
+ ])),
1891
+ responseFormat: ResponseFormat$outboundSchema.optional(),
1892
+ tools: z$1.nullable(z$1.array(z$1.union([
1893
+ Tool$outboundSchema.and(z$1.object({ type: z$1.literal("function") })),
1894
+ WebSearchTool$outboundSchema,
1895
+ WebSearchPremiumTool$outboundSchema,
1896
+ CodeInterpreterTool$outboundSchema,
1897
+ ImageGenerationTool$outboundSchema,
1898
+ DocumentLibraryTool$outboundSchema,
1899
+ CustomConnector$outboundSchema
1900
+ ]))).optional(),
1901
+ toolChoice: smartUnion([ToolChoice$outboundSchema, ToolChoiceEnum$outboundSchema]).optional(),
1902
+ presencePenalty: z$1.nullable(z$1.number()).optional(),
1903
+ frequencyPenalty: z$1.nullable(z$1.number()).optional(),
1904
+ n: z$1.nullable(z$1.int()).optional(),
1905
+ prediction: Prediction$outboundSchema.optional(),
1906
+ parallelToolCalls: z$1.boolean().optional(),
1907
+ reasoningEffort: z$1.nullable(ReasoningEffort$outboundSchema).optional(),
1908
+ promptMode: z$1.nullable(MistralPromptMode$outboundSchema).optional(),
1909
+ guardrails: z$1.nullable(z$1.array(GuardrailConfig$outboundSchema)).optional(),
1910
+ promptCacheKey: z$1.nullable(z$1.string()).optional(),
1911
+ serviceTier: z$1.nullable(RequestedServiceTier$outboundSchema).optional(),
1912
+ safePrompt: z$1.boolean().optional()
1913
+ }).transform((v) => {
1914
+ return remap(v, {
1915
+ topP: "top_p",
1916
+ maxTokens: "max_tokens",
1917
+ randomSeed: "random_seed",
1918
+ responseFormat: "response_format",
1919
+ toolChoice: "tool_choice",
1920
+ presencePenalty: "presence_penalty",
1921
+ frequencyPenalty: "frequency_penalty",
1922
+ parallelToolCalls: "parallel_tool_calls",
1923
+ reasoningEffort: "reasoning_effort",
1924
+ promptMode: "prompt_mode",
1925
+ promptCacheKey: "prompt_cache_key",
1926
+ serviceTier: "service_tier",
1927
+ safePrompt: "safe_prompt"
1928
+ });
1929
+ });
1930
+ //#endregion
1931
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/components/completionevent.js
1932
+ /** @internal */
1933
+ const CompletionEvent$inboundSchema = z$1.object({ data: z$1.string().transform((v, ctx) => {
1934
+ try {
1935
+ return JSON.parse(v);
1936
+ } catch (err) {
1937
+ ctx.addIssue({
1938
+ input: v,
1939
+ code: "custom",
1940
+ message: `malformed json: ${err}`
1941
+ });
1942
+ return z$1.NEVER;
1943
+ }
1944
+ }).pipe(CompletionChunk$inboundSchema) });
1945
+ smartUnion([z$1.string(), z$1.int()]);
1946
+ /** @internal */
1947
+ const Context$inboundSchema = z$1.object({});
1948
+ /** @internal */
1949
+ const ValidationError$inboundSchema = z$1.object({
1950
+ loc: z$1.array(smartUnion([z$1.string(), z$1.int()])),
1951
+ msg: z$1.string(),
1952
+ type: z$1.string(),
1953
+ input: z$1.any().optional(),
1954
+ ctx: z$1.lazy(() => Context$inboundSchema).optional()
1955
+ });
1956
+ //#endregion
1957
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/httpclienterrors.js
1958
+ /**
1959
+ * Base class for all HTTP errors.
1960
+ */
1961
+ var HTTPClientError = class extends Error {
1962
+ /** The underlying cause of the error. */
1963
+ cause;
1964
+ name = "HTTPClientError";
1965
+ constructor(message, opts) {
1966
+ let msg = message;
1967
+ if (opts?.cause) msg += `: ${opts.cause}`;
1968
+ super(msg, opts);
1969
+ if (typeof this.cause === "undefined") this.cause = opts?.cause;
1970
+ }
1971
+ };
1972
+ /**
1973
+ * An error to capture unrecognised or unexpected errors when making HTTP calls.
1974
+ */
1975
+ var UnexpectedClientError = class extends HTTPClientError {
1976
+ name = "UnexpectedClientError";
1977
+ };
1978
+ /**
1979
+ * An error that is raised when any inputs used to create a request are invalid.
1980
+ */
1981
+ var InvalidRequestError = class extends HTTPClientError {
1982
+ name = "InvalidRequestError";
1983
+ };
1984
+ /**
1985
+ * An error that is raised when a HTTP request was aborted by the client error.
1986
+ */
1987
+ var RequestAbortedError = class extends HTTPClientError {
1988
+ name = "RequestAbortedError";
1989
+ };
1990
+ /**
1991
+ * An error that is raised when a HTTP request timed out due to an AbortSignal
1992
+ * signal timeout.
1993
+ */
1994
+ var RequestTimeoutError = class extends HTTPClientError {
1995
+ name = "RequestTimeoutError";
1996
+ };
1997
+ /**
1998
+ * An error that is raised when a HTTP client is unable to make a request to
1999
+ * a server.
2000
+ */
2001
+ var ConnectionError = class extends HTTPClientError {
2002
+ name = "ConnectionError";
2003
+ };
2004
+ //#endregion
2005
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/models/errors/httpvalidationerror.js
2006
+ var HTTPValidationError = class extends MistralError {
2007
+ detail;
2008
+ /** The original data that was passed to this error instance. */
2009
+ data$;
2010
+ constructor(err, httpMeta) {
2011
+ const message = "message" in err && typeof err.message === "string" ? err.message : `API error occurred: ${JSON.stringify(err)}`;
2012
+ super(message, httpMeta);
2013
+ this.data$ = err;
2014
+ if (err.detail != null) this.detail = err.detail;
2015
+ this.name = "HTTPValidationError";
2016
+ }
2017
+ };
2018
+ /** @internal */
2019
+ const HTTPValidationError$inboundSchema = z$1.object({
2020
+ detail: z$1.array(ValidationError$inboundSchema).optional(),
2021
+ request$: z$1.custom((x) => x instanceof Request),
2022
+ response$: z$1.custom((x) => x instanceof Response),
2023
+ body$: z$1.string()
2024
+ }).transform((v) => {
2025
+ return new HTTPValidationError(v, {
2026
+ request: v.request$,
2027
+ response: v.response$,
2028
+ body: v.body$
2029
+ });
2030
+ });
2031
+ //#endregion
2032
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/types/async.js
2033
+ var APIPromise = class {
2034
+ #promise;
2035
+ #unwrapped;
2036
+ [Symbol.toStringTag] = "APIPromise";
2037
+ constructor(p) {
2038
+ this.#promise = p instanceof Promise ? p : Promise.resolve(p);
2039
+ this.#unwrapped = p instanceof Promise ? null : Promise.resolve(p[0]);
2040
+ }
2041
+ #getUnwrapped() {
2042
+ return this.#unwrapped ?? (this.#unwrapped = this.#promise.then(([value]) => value));
2043
+ }
2044
+ then(onfulfilled, onrejected) {
2045
+ return this.#promise.then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected);
2046
+ }
2047
+ catch(onrejected) {
2048
+ return this.#getUnwrapped().catch(onrejected);
2049
+ }
2050
+ finally(onfinally) {
2051
+ return this.#getUnwrapped().finally(onfinally);
2052
+ }
2053
+ $inspect() {
2054
+ return this.#promise;
2055
+ }
2056
+ };
2057
+ //#endregion
2058
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/funcs/chatComplete.js
2059
+ /**
2060
+ * Chat Completion
2061
+ */
2062
+ function chatComplete(client, request, options) {
2063
+ return new APIPromise($do$1(client, request, options));
2064
+ }
2065
+ async function $do$1(client, request, options) {
2066
+ const parsed = safeParse(request, (value) => ChatCompletionRequest$outboundSchema.parse(value), "Input validation failed");
2067
+ if (!parsed.ok) return [parsed, { status: "invalid" }];
2068
+ const payload = parsed.value;
2069
+ const body = encodeJSON("body", payload, { explode: true });
2070
+ const path = pathToFunc("/v1/chat/completions")();
2071
+ const headers = new Headers(compactMap({
2072
+ "Content-Type": "application/json",
2073
+ Accept: "application/json"
2074
+ }));
2075
+ const secConfig = await extractSecurity(client._options.apiKey);
2076
+ const requestSecurity = resolveGlobalSecurity(secConfig == null ? {} : { apiKey: secConfig });
2077
+ const context = {
2078
+ options: client._options,
2079
+ baseURL: options?.serverURL ?? client._baseURL ?? "",
2080
+ operationID: "chat_completion_v1_chat_completions_post",
2081
+ oAuth2Scopes: null,
2082
+ resolvedSecurity: requestSecurity,
2083
+ securitySource: client._options.apiKey,
2084
+ retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
2085
+ retryCodes: options?.retryCodes || [
2086
+ "429",
2087
+ "500",
2088
+ "502",
2089
+ "503",
2090
+ "504"
2091
+ ]
2092
+ };
2093
+ const requestRes = client._createRequest(context, {
2094
+ security: requestSecurity,
2095
+ method: "POST",
2096
+ baseURL: options?.serverURL,
2097
+ path,
2098
+ headers,
2099
+ body,
2100
+ userAgent: client._options.userAgent,
2101
+ timeoutMs: options?.timeoutMs || client._options.timeoutMs || 3e5
2102
+ }, options);
2103
+ if (!requestRes.ok) return [requestRes, { status: "invalid" }];
2104
+ const req = requestRes.value;
2105
+ const doResult = await client._do(req, {
2106
+ context,
2107
+ isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]),
2108
+ retryConfig: context.retryConfig,
2109
+ retryCodes: context.retryCodes
2110
+ });
2111
+ if (!doResult.ok) return [doResult, {
2112
+ status: "request-error",
2113
+ request: req
2114
+ }];
2115
+ const response = doResult.value;
2116
+ const responseFields = { HttpMeta: {
2117
+ Response: response,
2118
+ Request: req
2119
+ } };
2120
+ const [result] = await match(json(200, ChatCompletionResponse$inboundSchema), jsonErr(422, HTTPValidationError$inboundSchema), fail("4XX"), fail("5XX"))(response, req, { extraFields: responseFields });
2121
+ if (!result.ok) return [result, {
2122
+ status: "complete",
2123
+ request: req,
2124
+ response
2125
+ }];
2126
+ return [result, {
2127
+ status: "complete",
2128
+ request: req,
2129
+ response
2130
+ }];
2131
+ }
2132
+ //#endregion
2133
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/event-streams.js
2134
+ var EventStream = class extends ReadableStream {
2135
+ constructor(responseBody, parse, opts) {
2136
+ const upstream = responseBody.getReader();
2137
+ let buffer = /* @__PURE__ */ new Uint8Array();
2138
+ const state = { eventId: void 0 };
2139
+ const dataRequired = opts?.dataRequired ?? true;
2140
+ super({
2141
+ async pull(downstream) {
2142
+ try {
2143
+ while (true) {
2144
+ const match = findBoundary$1(buffer);
2145
+ if (!match) {
2146
+ const chunk = await upstream.read();
2147
+ if (chunk.done) return downstream.close();
2148
+ buffer = concatBuffer$1(buffer, chunk.value);
2149
+ continue;
2150
+ }
2151
+ const message = buffer.slice(0, match.index);
2152
+ buffer = buffer.slice(match.index + match.length);
2153
+ const item = parseMessage(message, parse, state, dataRequired);
2154
+ if (item && !item.done) return downstream.enqueue(item.value);
2155
+ if (item?.done) {
2156
+ await upstream.cancel("done");
2157
+ return downstream.close();
2158
+ }
2159
+ }
2160
+ } catch (e) {
2161
+ downstream.error(e);
2162
+ await upstream.cancel(e);
2163
+ }
2164
+ },
2165
+ cancel: (reason) => upstream.cancel(reason)
2166
+ });
2167
+ }
2168
+ [Symbol.asyncIterator]() {
2169
+ const fn = ReadableStream.prototype[Symbol.asyncIterator];
2170
+ if (typeof fn === "function") return fn.call(this);
2171
+ const reader = this.getReader();
2172
+ return {
2173
+ next: async () => {
2174
+ const r = await reader.read();
2175
+ if (r.done) {
2176
+ reader.releaseLock();
2177
+ return {
2178
+ done: true,
2179
+ value: void 0
2180
+ };
2181
+ }
2182
+ return {
2183
+ done: false,
2184
+ value: r.value
2185
+ };
2186
+ },
2187
+ throw: async (e) => {
2188
+ await reader.cancel(e);
2189
+ reader.releaseLock();
2190
+ return {
2191
+ done: true,
2192
+ value: void 0
2193
+ };
2194
+ },
2195
+ return: async () => {
2196
+ await reader.cancel("done");
2197
+ reader.releaseLock();
2198
+ return {
2199
+ done: true,
2200
+ value: void 0
2201
+ };
2202
+ },
2203
+ [Symbol.asyncIterator]() {
2204
+ return this;
2205
+ }
2206
+ };
2207
+ }
2208
+ };
2209
+ function concatBuffer$1(a, b) {
2210
+ const c = new Uint8Array(a.length + b.length);
2211
+ c.set(a, 0);
2212
+ c.set(b, a.length);
2213
+ return c;
2214
+ }
2215
+ const CR$1 = 13;
2216
+ const LF$1 = 10;
2217
+ const BOUNDARIES$1 = [
2218
+ [
2219
+ CR$1,
2220
+ LF$1,
2221
+ CR$1,
2222
+ LF$1
2223
+ ],
2224
+ [
2225
+ CR$1,
2226
+ LF$1,
2227
+ CR$1
2228
+ ],
2229
+ [
2230
+ CR$1,
2231
+ LF$1,
2232
+ LF$1
2233
+ ],
2234
+ [
2235
+ CR$1,
2236
+ CR$1,
2237
+ LF$1
2238
+ ],
2239
+ [
2240
+ LF$1,
2241
+ CR$1,
2242
+ LF$1
2243
+ ],
2244
+ [CR$1, CR$1],
2245
+ [LF$1, CR$1],
2246
+ [LF$1, LF$1]
2247
+ ];
2248
+ function findBoundary$1(buf) {
2249
+ const len = buf.length;
2250
+ for (let i = 0; i < len; i++) {
2251
+ if (buf[i] !== CR$1 && buf[i] !== LF$1) continue;
2252
+ for (const boundary of BOUNDARIES$1) {
2253
+ if (i + boundary.length > len) continue;
2254
+ let match = true;
2255
+ for (let j = 0; j < boundary.length; j++) if (buf[i + j] !== boundary[j]) {
2256
+ match = false;
2257
+ break;
2258
+ }
2259
+ if (match) return {
2260
+ index: i,
2261
+ length: boundary.length
2262
+ };
2263
+ }
2264
+ }
2265
+ return null;
2266
+ }
2267
+ function parseMessage(chunk, parse, state, dataRequired) {
2268
+ const lines = new TextDecoder().decode(chunk).split(/\r\n|\r|\n/);
2269
+ const dataLines = [];
2270
+ const ret = {};
2271
+ let ignore = true;
2272
+ for (const line of lines) {
2273
+ if (!line || line.startsWith(":")) continue;
2274
+ ignore = false;
2275
+ const i = line.indexOf(":");
2276
+ let field = line;
2277
+ let value = "";
2278
+ if (i > 0) {
2279
+ field = line.slice(0, i);
2280
+ value = line[i + 1] === " " ? line.slice(i + 2) : line.slice(i + 1);
2281
+ }
2282
+ if (field === "data") dataLines.push(value);
2283
+ else if (field === "event") ret.event = value;
2284
+ else if (field === "id" && !value.includes("\0")) state.eventId = value;
2285
+ else if (field === "retry" && /^\d+$/.test(value)) ret.retry = Number(value);
2286
+ }
2287
+ if (ignore) return;
2288
+ ret.id = state.eventId;
2289
+ if (dataLines.length) ret.data = dataLines.join("\n");
2290
+ else if (dataRequired) return;
2291
+ return parse(ret);
2292
+ }
2293
+ //#endregion
2294
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/funcs/chatStream.js
2295
+ /**
2296
+ * Stream chat completion
2297
+ *
2298
+ * @remarks
2299
+ * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
2300
+ */
2301
+ function chatStream(client, request, options) {
2302
+ return new APIPromise($do(client, request, options));
2303
+ }
2304
+ async function $do(client, request, options) {
2305
+ const parsed = safeParse(request, (value) => ChatCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed");
2306
+ if (!parsed.ok) return [parsed, { status: "invalid" }];
2307
+ const payload = parsed.value;
2308
+ const body = encodeJSON("body", payload, { explode: true });
2309
+ const path = pathToFunc("/v1/chat/completions#stream")();
2310
+ const headers = new Headers(compactMap({
2311
+ "Content-Type": "application/json",
2312
+ Accept: "text/event-stream"
2313
+ }));
2314
+ const secConfig = await extractSecurity(client._options.apiKey);
2315
+ const requestSecurity = resolveGlobalSecurity(secConfig == null ? {} : { apiKey: secConfig });
2316
+ const context = {
2317
+ options: client._options,
2318
+ baseURL: options?.serverURL ?? client._baseURL ?? "",
2319
+ operationID: "stream_chat",
2320
+ oAuth2Scopes: null,
2321
+ resolvedSecurity: requestSecurity,
2322
+ securitySource: client._options.apiKey,
2323
+ retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" },
2324
+ retryCodes: options?.retryCodes || [
2325
+ "429",
2326
+ "500",
2327
+ "502",
2328
+ "503",
2329
+ "504"
2330
+ ]
2331
+ };
2332
+ const requestRes = client._createRequest(context, {
2333
+ security: requestSecurity,
2334
+ method: "POST",
2335
+ baseURL: options?.serverURL,
2336
+ path,
2337
+ headers,
2338
+ body,
2339
+ userAgent: client._options.userAgent,
2340
+ timeoutMs: options?.timeoutMs || client._options.timeoutMs || 3e5
2341
+ }, options);
2342
+ if (!requestRes.ok) return [requestRes, { status: "invalid" }];
2343
+ const req = requestRes.value;
2344
+ const doResult = await client._do(req, {
2345
+ context,
2346
+ isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]),
2347
+ retryConfig: context.retryConfig,
2348
+ retryCodes: context.retryCodes
2349
+ });
2350
+ if (!doResult.ok) return [doResult, {
2351
+ status: "request-error",
2352
+ request: req
2353
+ }];
2354
+ const response = doResult.value;
2355
+ const responseFields = { HttpMeta: {
2356
+ Response: response,
2357
+ Request: req
2358
+ } };
2359
+ const [result] = await match(sse(200, z$1.custom((x) => x instanceof ReadableStream).transform((stream) => {
2360
+ return new EventStream(stream, (rawEvent) => {
2361
+ if (rawEvent.data === "[DONE]") return {
2362
+ done: true,
2363
+ value: void 0
2364
+ };
2365
+ return {
2366
+ done: false,
2367
+ value: CompletionEvent$inboundSchema.parse(rawEvent)
2368
+ };
2369
+ });
2370
+ })), jsonErr(422, HTTPValidationError$inboundSchema), fail("4XX"), fail("5XX"))(response, req, { extraFields: responseFields });
2371
+ if (!result.ok) return [result, {
2372
+ status: "complete",
2373
+ request: req,
2374
+ response
2375
+ }];
2376
+ return [result, {
2377
+ status: "complete",
2378
+ request: req,
2379
+ response
2380
+ }];
2381
+ }
2382
+ /**
2383
+ * Contains the list of servers available to the SDK
2384
+ */
2385
+ const ServerList = {
2386
+ ["global"]: "https://api.mistral.ai",
2387
+ ["eu"]: "https://api.eu.mistral.ai",
2388
+ ["us"]: "https://api.us.mistral.ai"
2389
+ };
2390
+ function serverURLFromOptions(options) {
2391
+ let serverURL = options.serverURL;
2392
+ const params = {};
2393
+ if (!serverURL) {
2394
+ const server = options.server ?? "global";
2395
+ serverURL = ServerList[server] || "";
2396
+ }
2397
+ const u = pathToFunc(serverURL)(params);
2398
+ return new URL(u);
2399
+ }
2400
+ const SDK_METADATA = {
2401
+ language: "typescript",
2402
+ openapiDocVersion: "1.0.0",
2403
+ sdkVersion: "2.7.0",
2404
+ genVersion: "2.884.13",
2405
+ userAgent: "speakeasy-sdk/typescript 2.7.0 2.884.13 1.0.0 @mistralai/mistralai"
2406
+ };
2407
+ //#endregion
2408
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/custom_user_agent.js
2409
+ var CustomUserAgentHook = class {
2410
+ beforeRequest(_, request) {
2411
+ const ua = `mistral-client-typescript/${SDK_METADATA.sdkVersion}`;
2412
+ request.headers.set("user-agent", ua);
2413
+ if (!request.headers.get("user-agent")) request.headers.set("x-mistral-user-agent", ua);
2414
+ return request;
2415
+ }
2416
+ };
2417
+ //#endregion
2418
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/deprecation_warning.js
2419
+ const HEADER_MODEL_DEPRECATION_TIMESTAMP = "x-model-deprecation-timestamp";
2420
+ var DeprecationWarningHook = class {
2421
+ afterSuccess(_, response) {
2422
+ if (response.headers.has(HEADER_MODEL_DEPRECATION_TIMESTAMP)) response.clone().json().then((body) => {
2423
+ const model = body.model;
2424
+ console.warn(`WARNING: The model ${model} is deprecated and will be removed on ${response.headers.get(HEADER_MODEL_DEPRECATION_TIMESTAMP)}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`);
2425
+ }).catch(() => {});
2426
+ return response;
2427
+ }
2428
+ };
2429
+ //#endregion
2430
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/tracing.js
2431
+ let observabilityModule;
2432
+ let telemetryModule;
2433
+ async function getObservabilityModule() {
2434
+ if (observabilityModule !== void 0) return observabilityModule;
2435
+ try {
2436
+ observabilityModule = await import("./otel-Buswj0Mf.mjs");
2437
+ } catch {
2438
+ observabilityModule = null;
2439
+ }
2440
+ return observabilityModule;
2441
+ }
2442
+ async function getTelemetryModule() {
2443
+ if (telemetryModule !== void 0) return telemetryModule;
2444
+ try {
2445
+ telemetryModule = await import("./telemetry-CvK1yQg7.mjs");
2446
+ } catch {
2447
+ telemetryModule = null;
2448
+ }
2449
+ return telemetryModule;
2450
+ }
2451
+ const TRACING_SPAN_KEY = "_tracingSpan";
2452
+ const TRACING_BODY_KEY = "_tracingBody";
2453
+ const TRACING_TRACER_KEY = "_tracingTracer";
2454
+ function clearTracingContext(ctx) {
2455
+ delete ctx[TRACING_TRACER_KEY];
2456
+ delete ctx[TRACING_SPAN_KEY];
2457
+ delete ctx[TRACING_BODY_KEY];
2458
+ }
2459
+ var TracingHTTPClient = class TracingHTTPClient extends HTTPClient {
2460
+ wrappedClient;
2461
+ requestContexts;
2462
+ constructor(wrappedClient, requestContexts) {
2463
+ super();
2464
+ this.wrappedClient = wrappedClient;
2465
+ this.requestContexts = requestContexts;
2466
+ }
2467
+ async request(request) {
2468
+ const activeContext = this.requestContexts.get(request);
2469
+ if (!activeContext) return this.wrappedClient.request(request);
2470
+ let observability = null;
2471
+ try {
2472
+ observability = await getObservabilityModule();
2473
+ if (!observability) return await this.wrappedClient.request(request);
2474
+ return await observability.runWithContext(activeContext, () => this.wrappedClient.request(request));
2475
+ } catch (error) {
2476
+ if (observability) await observability.recordRequestError(activeContext, error);
2477
+ throw error;
2478
+ } finally {
2479
+ this.requestContexts.delete(request);
2480
+ }
2481
+ }
2482
+ clone() {
2483
+ return new TracingHTTPClient(this.wrappedClient.clone(), this.requestContexts);
2484
+ }
2485
+ };
2486
+ var TracingHook = class {
2487
+ #requestContexts = /* @__PURE__ */ new WeakMap();
2488
+ _mistralTracingHook = true;
2489
+ tracerProvider = void 0;
2490
+ _autoTelemetryProvider = void 0;
2491
+ _telemetryInitialization = void 0;
2492
+ _telemetryConfigurationVersion = 0;
2493
+ _telemetryAutoDisabled = false;
2494
+ _telemetryUseGlobalProvider = false;
2495
+ sdkInit(opts) {
2496
+ return {
2497
+ ...opts,
2498
+ client: new TracingHTTPClient(opts.client, this.#requestContexts)
2499
+ };
2500
+ }
2501
+ async beforeRequest(hookCtx, request) {
2502
+ const ctx = hookCtx;
2503
+ const observability = await getObservabilityModule();
2504
+ if (!observability) return request;
2505
+ const telemetry = await getTelemetryModule();
2506
+ if (!((telemetry ? await telemetry.configureTelemetryForHook(this, hookCtx) : false) || this.tracerProvider !== void 0 || this._telemetryUseGlobalProvider || getRegisteredTracerProvider() !== void 0)) {
2507
+ clearTracingContext(ctx);
2508
+ return request;
2509
+ }
2510
+ const tracer = observability.getOrCreateOtelTracer(this.tracerProvider, { useRegisteredProvider: !this._telemetryUseGlobalProvider });
2511
+ const { request: tracedRequest, span, body } = await observability.getTracedRequestAndSpan(tracer, hookCtx.operationID, request);
2512
+ ctx[TRACING_TRACER_KEY] = tracer;
2513
+ ctx[TRACING_SPAN_KEY] = span;
2514
+ ctx[TRACING_BODY_KEY] = body;
2515
+ this.#requestContexts.set(tracedRequest, observability.getSpanContext(span));
2516
+ return tracedRequest;
2517
+ }
2518
+ async afterSuccess(hookCtx, response) {
2519
+ const ctx = hookCtx;
2520
+ const span = ctx[TRACING_SPAN_KEY];
2521
+ const tracer = ctx[TRACING_TRACER_KEY];
2522
+ if (!span || !tracer) return response;
2523
+ const observability = await getObservabilityModule();
2524
+ if (!observability) return response;
2525
+ return observability.getTracedResponse(tracer, span, hookCtx.operationID, response);
2526
+ }
2527
+ async afterError(hookCtx, response, error) {
2528
+ const span = hookCtx[TRACING_SPAN_KEY];
2529
+ if (!span) return {
2530
+ response,
2531
+ error
2532
+ };
2533
+ const observability = await getObservabilityModule();
2534
+ if (!observability) return {
2535
+ response,
2536
+ error
2537
+ };
2538
+ return observability.getResponseAndError(span, response, error);
2539
+ }
2540
+ };
2541
+ //#endregion
2542
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/workflow_stream_error.js
2543
+ const STREAM_OPERATIONS_WITH_ERROR_EVENT = /* @__PURE__ */ new Set([
2544
+ "get_stream_events_v1_workflows_events_stream_get",
2545
+ "stream_v1_workflows_executions__execution_id__stream_get",
2546
+ "stream_deployment_logs",
2547
+ "stream_workflow_execution_logs"
2548
+ ]);
2549
+ const ERROR_EVENT = "error";
2550
+ const VALID_REASONS = [
2551
+ "read_error",
2552
+ "stream_error",
2553
+ "internal_error"
2554
+ ];
2555
+ const DEFAULT_REASON = "stream_error";
2556
+ var StreamDisconnectedError = class extends Error {
2557
+ reason;
2558
+ error;
2559
+ constructor(options) {
2560
+ super("Workflow stream disconnected by server");
2561
+ this.name = "StreamDisconnectedError";
2562
+ this.reason = options.reason;
2563
+ this.error = options.error;
2564
+ }
2565
+ };
2566
+ const CR = 13;
2567
+ const LF = 10;
2568
+ const BOUNDARIES = [
2569
+ [
2570
+ CR,
2571
+ LF,
2572
+ CR,
2573
+ LF
2574
+ ],
2575
+ [
2576
+ CR,
2577
+ LF,
2578
+ CR
2579
+ ],
2580
+ [
2581
+ CR,
2582
+ LF,
2583
+ LF
2584
+ ],
2585
+ [
2586
+ CR,
2587
+ CR,
2588
+ LF
2589
+ ],
2590
+ [
2591
+ LF,
2592
+ CR,
2593
+ LF
2594
+ ],
2595
+ [CR, CR],
2596
+ [LF, CR],
2597
+ [LF, LF]
2598
+ ];
2599
+ function findBoundary(buf) {
2600
+ const len = buf.length;
2601
+ for (let i = 0; i < len; i++) {
2602
+ if (buf[i] !== CR && buf[i] !== LF) continue;
2603
+ for (const boundary of BOUNDARIES) {
2604
+ if (i + boundary.length > len) continue;
2605
+ let match = true;
2606
+ for (let j = 0; j < boundary.length; j++) if (buf[i + j] !== boundary[j]) {
2607
+ match = false;
2608
+ break;
2609
+ }
2610
+ if (match) return {
2611
+ index: i,
2612
+ length: boundary.length
2613
+ };
2614
+ }
2615
+ }
2616
+ return null;
2617
+ }
2618
+ function concatBuffer(a, b) {
2619
+ const c = new Uint8Array(a.length + b.length);
2620
+ c.set(a, 0);
2621
+ c.set(b, a.length);
2622
+ return c;
2623
+ }
2624
+ function parseErrorPayload(data) {
2625
+ const raw = data.trim();
2626
+ let payload = {};
2627
+ for (const candidate of [raw, raw.replace(/\r?\n/g, "\\n")]) try {
2628
+ const parsed = JSON.parse(candidate);
2629
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2630
+ payload = parsed;
2631
+ break;
2632
+ }
2633
+ } catch {
2634
+ continue;
2635
+ }
2636
+ const error = "error" in payload ? String(payload["error"]) : raw;
2637
+ const reason = payload["reason"];
2638
+ return {
2639
+ error,
2640
+ reason: VALID_REASONS.includes(reason) ? reason : DEFAULT_REASON
2641
+ };
2642
+ }
2643
+ function errorFromFrame(block) {
2644
+ const text = new TextDecoder().decode(block);
2645
+ let eventName;
2646
+ const dataLines = [];
2647
+ for (const line of text.split(/\r\n|\r|\n/)) {
2648
+ if (!line || line.startsWith(":")) continue;
2649
+ const i = line.indexOf(":");
2650
+ let field = line;
2651
+ let value = "";
2652
+ if (i > 0) {
2653
+ field = line.slice(0, i);
2654
+ value = line[i + 1] === " " ? line.slice(i + 2) : line.slice(i + 1);
2655
+ }
2656
+ if (field === "event") eventName = value;
2657
+ else if (field === "data") dataLines.push(value);
2658
+ }
2659
+ if (eventName !== ERROR_EVENT) return null;
2660
+ return new StreamDisconnectedError(parseErrorPayload(dataLines.join("\n")));
2661
+ }
2662
+ var FrameScanner = class {
2663
+ buffer = /* @__PURE__ */ new Uint8Array();
2664
+ error = null;
2665
+ feed(chunk) {
2666
+ if (this.error) return [];
2667
+ this.buffer = concatBuffer(this.buffer, chunk);
2668
+ const frames = [];
2669
+ for (;;) {
2670
+ const match = findBoundary(this.buffer);
2671
+ if (!match) return frames;
2672
+ const block = this.buffer.slice(0, match.index);
2673
+ const frame = this.buffer.slice(0, match.index + match.length);
2674
+ this.buffer = this.buffer.slice(match.index + match.length);
2675
+ this.error = errorFromFrame(block);
2676
+ if (this.error) return frames;
2677
+ frames.push(frame);
2678
+ }
2679
+ }
2680
+ flush() {
2681
+ if (this.error || !this.buffer.length) return [];
2682
+ const block = this.buffer;
2683
+ this.buffer = /* @__PURE__ */ new Uint8Array();
2684
+ this.error = errorFromFrame(block);
2685
+ return this.error ? [] : [block];
2686
+ }
2687
+ };
2688
+ function createErrorDetectingResponse(response) {
2689
+ const reader = response.body.getReader();
2690
+ const scanner = new FrameScanner();
2691
+ const stream = new ReadableStream({
2692
+ async pull(controller) {
2693
+ const fail = async (err) => {
2694
+ controller.error(err);
2695
+ try {
2696
+ await reader.cancel(err);
2697
+ } catch {}
2698
+ };
2699
+ if (scanner.error) return fail(scanner.error);
2700
+ try {
2701
+ for (;;) {
2702
+ const result = await reader.read();
2703
+ const frames = result.done ? scanner.flush() : scanner.feed(result.value);
2704
+ for (const frame of frames) controller.enqueue(frame);
2705
+ if (frames.length) return;
2706
+ if (scanner.error) return fail(scanner.error);
2707
+ if (result.done) {
2708
+ controller.close();
2709
+ return;
2710
+ }
2711
+ }
2712
+ } catch (err) {
2713
+ await fail(err);
2714
+ }
2715
+ },
2716
+ async cancel(reason) {
2717
+ await reader.cancel(reason);
2718
+ }
2719
+ }, { highWaterMark: 0 });
2720
+ return new Response(stream, {
2721
+ status: response.status,
2722
+ statusText: response.statusText,
2723
+ headers: response.headers
2724
+ });
2725
+ }
2726
+ var WorkflowStreamErrorHook = class {
2727
+ afterSuccess(hookCtx, response) {
2728
+ if (!STREAM_OPERATIONS_WITH_ERROR_EVENT.has(hookCtx.operationID)) return response;
2729
+ if (!(response.headers.get("content-type") ?? "").toLowerCase().includes("text/event-stream")) return response;
2730
+ if (!response.body || response.bodyUsed) return response;
2731
+ return createErrorDetectingResponse(response);
2732
+ }
2733
+ };
2734
+ //#endregion
2735
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/registration.js
2736
+ function initHooks(hooks) {
2737
+ const customUserAgentHook = new CustomUserAgentHook();
2738
+ hooks.registerBeforeRequestHook(customUserAgentHook);
2739
+ const deprecationWarningHook = new DeprecationWarningHook();
2740
+ hooks.registerAfterSuccessHook(deprecationWarningHook);
2741
+ const workflowStreamErrorHook = new WorkflowStreamErrorHook();
2742
+ hooks.registerAfterSuccessHook(workflowStreamErrorHook);
2743
+ const tracingHook = new TracingHook();
2744
+ hooks.registerBeforeRequestHook(tracingHook);
2745
+ hooks.registerAfterSuccessHook(tracingHook);
2746
+ hooks.registerAfterErrorHook(tracingHook);
2747
+ hooks.registerSDKInitHook(tracingHook);
2748
+ }
2749
+ //#endregion
2750
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/hooks/hooks.js
2751
+ var SDKHooks = class {
2752
+ sdkInitHooks = [];
2753
+ beforeCreateRequestHooks = [];
2754
+ beforeRequestHooks = [];
2755
+ afterSuccessHooks = [];
2756
+ afterErrorHooks = [];
2757
+ constructor() {
2758
+ for (const hook of []) {
2759
+ if ("sdkInit" in hook) this.registerSDKInitHook(hook);
2760
+ if ("beforeCreateRequest" in hook) this.registerBeforeCreateRequestHook(hook);
2761
+ if ("beforeRequest" in hook) this.registerBeforeRequestHook(hook);
2762
+ if ("afterSuccess" in hook) this.registerAfterSuccessHook(hook);
2763
+ if ("afterError" in hook) this.registerAfterErrorHook(hook);
2764
+ }
2765
+ initHooks(this);
2766
+ }
2767
+ registerSDKInitHook(hook) {
2768
+ this.sdkInitHooks.push(hook);
2769
+ }
2770
+ registerBeforeCreateRequestHook(hook) {
2771
+ this.beforeCreateRequestHooks.push(hook);
2772
+ }
2773
+ registerBeforeRequestHook(hook) {
2774
+ this.beforeRequestHooks.push(hook);
2775
+ }
2776
+ registerAfterSuccessHook(hook) {
2777
+ this.afterSuccessHooks.push(hook);
2778
+ }
2779
+ registerAfterErrorHook(hook) {
2780
+ this.afterErrorHooks.push(hook);
2781
+ }
2782
+ sdkInit(opts) {
2783
+ return this.sdkInitHooks.reduce((opts, hook) => hook.sdkInit(opts), opts);
2784
+ }
2785
+ beforeCreateRequest(hookCtx, input) {
2786
+ let inp = input;
2787
+ for (const hook of this.beforeCreateRequestHooks) inp = hook.beforeCreateRequest(hookCtx, inp);
2788
+ return inp;
2789
+ }
2790
+ async beforeRequest(hookCtx, request) {
2791
+ let req = request;
2792
+ for (const hook of this.beforeRequestHooks) req = await hook.beforeRequest(hookCtx, req);
2793
+ return req;
2794
+ }
2795
+ async afterSuccess(hookCtx, response) {
2796
+ let res = response;
2797
+ for (const hook of this.afterSuccessHooks) res = await hook.afterSuccess(hookCtx, res);
2798
+ return res;
2799
+ }
2800
+ async afterError(hookCtx, response, error) {
2801
+ let res = response;
2802
+ let err = error;
2803
+ for (const hook of this.afterErrorHooks) {
2804
+ const result = await hook.afterError(hookCtx, res, err);
2805
+ res = result.response;
2806
+ err = result.error;
2807
+ }
2808
+ return {
2809
+ response: res,
2810
+ error: err
2811
+ };
2812
+ }
2813
+ };
2814
+ //#endregion
2815
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/retries.js
2816
+ const defaultBackoff = {
2817
+ initialInterval: 500,
2818
+ maxInterval: 6e4,
2819
+ exponent: 1.5,
2820
+ maxElapsedTime: 36e5
2821
+ };
2822
+ /**
2823
+ * PermanentError is an error that is not recoverable. Throwing this error will
2824
+ * cause a retry loop to terminate.
2825
+ */
2826
+ var PermanentError = class PermanentError extends Error {
2827
+ /** The underlying cause of the error. */
2828
+ cause;
2829
+ constructor(message, options) {
2830
+ let msg = message;
2831
+ if (options?.cause) msg += `: ${options.cause}`;
2832
+ super(msg, options);
2833
+ this.name = "PermanentError";
2834
+ if (typeof this.cause === "undefined") this.cause = options?.cause;
2835
+ Object.setPrototypeOf(this, PermanentError.prototype);
2836
+ }
2837
+ };
2838
+ /**
2839
+ * TemporaryError is an error is used to signal that an HTTP request can be
2840
+ * retried as part of a retry loop. If retry attempts are exhausted and this
2841
+ * error is thrown, the response will be returned to the caller.
2842
+ */
2843
+ var TemporaryError = class TemporaryError extends Error {
2844
+ response;
2845
+ constructor(message, response) {
2846
+ super(message);
2847
+ this.response = response;
2848
+ this.name = "TemporaryError";
2849
+ Object.setPrototypeOf(this, TemporaryError.prototype);
2850
+ }
2851
+ };
2852
+ async function retry(fetchFn, options) {
2853
+ switch (options.config.strategy) {
2854
+ case "backoff": return retryBackoff(wrapFetcher(fetchFn, {
2855
+ statusCodes: options.statusCodes,
2856
+ retryConnectionErrors: !!options.config.retryConnectionErrors
2857
+ }), options.config.backoff ?? defaultBackoff);
2858
+ default: return await fetchFn();
2859
+ }
2860
+ }
2861
+ function wrapFetcher(fn, options) {
2862
+ return async () => {
2863
+ try {
2864
+ const res = await fn();
2865
+ if (isRetryableResponse(res, options.statusCodes)) throw new TemporaryError("Response failed with retryable status code", res);
2866
+ return res;
2867
+ } catch (err) {
2868
+ if (err instanceof TemporaryError) throw err;
2869
+ if (options.retryConnectionErrors && (isTimeoutError(err) || isConnectionError(err))) throw err;
2870
+ throw new PermanentError("Permanent error", { cause: err });
2871
+ }
2872
+ };
2873
+ }
2874
+ const codeRangeRE = /* @__PURE__ */ new RegExp("^[0-9]xx$", "i");
2875
+ function isRetryableResponse(res, statusCodes) {
2876
+ const actual = `${res.status}`;
2877
+ return statusCodes.some((code) => {
2878
+ if (!codeRangeRE.test(code)) return code === actual;
2879
+ const expectFamily = code.charAt(0);
2880
+ if (!expectFamily) throw new Error("Invalid status code range");
2881
+ const actualFamily = actual.charAt(0);
2882
+ if (!actualFamily) throw new Error(`Invalid response status code: ${actual}`);
2883
+ return actualFamily === expectFamily;
2884
+ });
2885
+ }
2886
+ async function retryBackoff(fn, strategy) {
2887
+ const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy;
2888
+ const start = Date.now();
2889
+ let x = 0;
2890
+ while (true) try {
2891
+ return await fn();
2892
+ } catch (err) {
2893
+ if (err instanceof PermanentError) throw err.cause;
2894
+ if (Date.now() - start > maxElapsedTime) {
2895
+ if (err instanceof TemporaryError) return err.response;
2896
+ throw err;
2897
+ }
2898
+ let retryInterval = 0;
2899
+ if (err instanceof TemporaryError) retryInterval = retryIntervalFromResponse(err.response);
2900
+ if (retryInterval <= 0) retryInterval = initialInterval * Math.pow(x, exponent) + Math.random() * 1e3;
2901
+ await delay(Math.min(retryInterval, maxInterval));
2902
+ x++;
2903
+ }
2904
+ }
2905
+ function retryIntervalFromResponse(res) {
2906
+ const retryVal = res.headers.get("retry-after") || "";
2907
+ if (!retryVal) return 0;
2908
+ const parsedNumber = Number(retryVal);
2909
+ if (Number.isInteger(parsedNumber)) return parsedNumber * 1e3;
2910
+ const parsedDate = Date.parse(retryVal);
2911
+ if (Number.isInteger(parsedDate)) {
2912
+ const deltaMS = parsedDate - Date.now();
2913
+ return deltaMS > 0 ? Math.ceil(deltaMS) : 0;
2914
+ }
2915
+ return 0;
2916
+ }
2917
+ async function delay(delay) {
2918
+ return new Promise((resolve) => setTimeout(resolve, delay));
2919
+ }
2920
+ //#endregion
2921
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/lib/sdks.js
2922
+ const gt = typeof globalThis === "undefined" ? null : globalThis;
2923
+ const isBrowserLike = typeof gt === "object" && gt != null && "importScripts" in gt && typeof gt["importScripts"] === "function" || typeof navigator !== "undefined" && "serviceWorker" in navigator || typeof window === "object" && typeof window.document !== "undefined";
2924
+ var ClientSDK = class {
2925
+ #httpClient;
2926
+ #hooks;
2927
+ #logger;
2928
+ _baseURL;
2929
+ _options;
2930
+ constructor(options = {}) {
2931
+ const opt = options;
2932
+ if (typeof opt === "object" && opt != null && "hooks" in opt && opt.hooks instanceof SDKHooks) this.#hooks = opt.hooks;
2933
+ else this.#hooks = new SDKHooks();
2934
+ const url = serverURLFromOptions(options);
2935
+ if (url) url.pathname = url.pathname.replace(/\/+$/, "") + "/";
2936
+ const { baseURL, client } = this.#hooks.sdkInit({
2937
+ baseURL: url,
2938
+ client: options.httpClient || new HTTPClient()
2939
+ });
2940
+ this._baseURL = baseURL;
2941
+ this.#httpClient = client;
2942
+ this._options = {
2943
+ ...options,
2944
+ hooks: this.#hooks
2945
+ };
2946
+ this.#logger = this._options.debugLogger;
2947
+ if (!this.#logger && env().MISTRAL_DEBUG) this.#logger = console;
2948
+ }
2949
+ _createRequest(context, conf, options) {
2950
+ const { method, path, query, headers: opHeaders, security } = conf;
2951
+ const base = conf.baseURL ?? this._baseURL;
2952
+ if (!base) return ERR(new InvalidRequestError("No base URL provided for operation"));
2953
+ const baseURL = new URL(base);
2954
+ let reqURL;
2955
+ if (path) {
2956
+ baseURL.pathname = baseURL.pathname.replace(/\/+$/, "") + "/";
2957
+ reqURL = new URL(path, baseURL);
2958
+ } else reqURL = baseURL;
2959
+ reqURL.hash = "";
2960
+ let finalQuery = query || "";
2961
+ const secQuery = [];
2962
+ for (const [k, v] of Object.entries(security?.queryParams || {})) {
2963
+ const q = encodeForm(k, v, { charEncoding: "percent" });
2964
+ if (typeof q !== "undefined") secQuery.push(q);
2965
+ }
2966
+ if (secQuery.length) finalQuery += `&${secQuery.join("&")}`;
2967
+ if (finalQuery) {
2968
+ const q = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery;
2969
+ reqURL.search = `?${q}`;
2970
+ }
2971
+ const headers = new Headers(opHeaders);
2972
+ const username = security?.basic.username;
2973
+ const password = security?.basic.password;
2974
+ if (username != null || password != null) {
2975
+ const encoded = stringToBase64([username || "", password || ""].join(":"));
2976
+ headers.set("Authorization", `Basic ${encoded}`);
2977
+ }
2978
+ const securityHeaders = new Headers(security?.headers || {});
2979
+ for (const [k, v] of securityHeaders) headers.set(k, v);
2980
+ let cookie = headers.get("cookie") || "";
2981
+ for (const [k, v] of Object.entries(security?.cookies || {})) cookie += `; ${k}=${v}`;
2982
+ cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie;
2983
+ headers.set("cookie", cookie);
2984
+ const userHeaders = new Headers(options?.headers ?? options?.fetchOptions?.headers);
2985
+ for (const [k, v] of userHeaders) headers.set(k, v);
2986
+ if (!isBrowserLike) headers.set(conf.uaHeader ?? "user-agent", conf.userAgent ?? SDK_METADATA.userAgent);
2987
+ const fetchOptions = {
2988
+ ...options?.fetchOptions,
2989
+ ...options
2990
+ };
2991
+ if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) fetchOptions.signal = AbortSignal.timeout(conf.timeoutMs);
2992
+ if (conf.body instanceof ReadableStream) Object.assign(fetchOptions, { duplex: "half" });
2993
+ let input;
2994
+ try {
2995
+ input = this.#hooks.beforeCreateRequest(context, {
2996
+ url: reqURL,
2997
+ options: {
2998
+ ...fetchOptions,
2999
+ body: conf.body ?? null,
3000
+ headers,
3001
+ method
3002
+ }
3003
+ });
3004
+ } catch (err) {
3005
+ return ERR(new UnexpectedClientError("Create request hook failed to execute", { cause: err }));
3006
+ }
3007
+ return OK(new Request(input.url, input.options));
3008
+ }
3009
+ async _do(request, options) {
3010
+ const { context, isErrorStatusCode } = options;
3011
+ return retry(async () => {
3012
+ const req = await this.#hooks.beforeRequest(context, request.clone());
3013
+ await logRequest(this.#logger, req).catch((e) => this.#logger?.log("Failed to log request:", e));
3014
+ let response = await this.#httpClient.request(req);
3015
+ try {
3016
+ if (isErrorStatusCode(response.status)) {
3017
+ const result = await this.#hooks.afterError(context, response, null);
3018
+ if (result.error) throw result.error;
3019
+ response = result.response || response;
3020
+ } else response = await this.#hooks.afterSuccess(context, response);
3021
+ } finally {
3022
+ await logResponse(this.#logger, response, req).catch((e) => this.#logger?.log("Failed to log response:", e));
3023
+ }
3024
+ return response;
3025
+ }, {
3026
+ config: options.retryConfig,
3027
+ statusCodes: options.retryCodes
3028
+ }).then((r) => OK(r), (err) => {
3029
+ switch (true) {
3030
+ case isAbortError(err): return ERR(new RequestAbortedError("Request aborted by client", { cause: err }));
3031
+ case isTimeoutError(err): return ERR(new RequestTimeoutError("Request timed out", { cause: err }));
3032
+ case isConnectionError(err): return ERR(new ConnectionError("Unable to make request", { cause: err }));
3033
+ default: return ERR(new UnexpectedClientError("Unexpected HTTP client error", { cause: err }));
3034
+ }
3035
+ });
3036
+ }
3037
+ };
3038
+ const jsonLikeContentTypeRE = /^(application|text)\/([^+]+\+)*json.*/;
3039
+ const jsonlLikeContentTypeRE = /^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;
3040
+ async function logRequest(logger, req) {
3041
+ if (!logger) return;
3042
+ const contentType = req.headers.get("content-type");
3043
+ const ct = contentType?.split(";")[0] || "";
3044
+ logger.group(`> Request: ${req.method} ${req.url}`);
3045
+ logger.group("Headers:");
3046
+ for (const [k, v] of req.headers.entries()) logger.log(`${k}: ${v}`);
3047
+ logger.groupEnd();
3048
+ logger.group("Body:");
3049
+ switch (true) {
3050
+ case jsonLikeContentTypeRE.test(ct):
3051
+ logger.log(await req.clone().json());
3052
+ break;
3053
+ case ct.startsWith("text/"):
3054
+ logger.log(await req.clone().text());
3055
+ break;
3056
+ case ct === "multipart/form-data": {
3057
+ const body = await req.clone().formData();
3058
+ for (const [k, v] of body) {
3059
+ const vlabel = v instanceof Blob ? "<Blob>" : v;
3060
+ logger.log(`${k}: ${vlabel}`);
3061
+ }
3062
+ break;
3063
+ }
3064
+ default: logger.log(`<${contentType}>`);
3065
+ }
3066
+ logger.groupEnd();
3067
+ logger.groupEnd();
3068
+ }
3069
+ async function logResponse(logger, res, req) {
3070
+ if (!logger) return;
3071
+ const contentType = res.headers.get("content-type");
3072
+ const ct = contentType?.split(";")[0] || "";
3073
+ logger.group(`< Response: ${req.method} ${req.url}`);
3074
+ logger.log("Status Code:", res.status, res.statusText);
3075
+ logger.group("Headers:");
3076
+ for (const [k, v] of res.headers.entries()) logger.log(`${k}: ${v}`);
3077
+ logger.groupEnd();
3078
+ logger.group("Body:");
3079
+ switch (true) {
3080
+ case matchContentType(res, "application/json") || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct):
3081
+ logger.log(await res.clone().json());
3082
+ break;
3083
+ case matchContentType(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct):
3084
+ case matchContentType(res, "text/event-stream"):
3085
+ logger.log(`<${contentType}>`);
3086
+ break;
3087
+ case matchContentType(res, "text/*"):
3088
+ logger.log(await res.clone().text());
3089
+ break;
3090
+ case matchContentType(res, "multipart/form-data"): {
3091
+ const body = await res.clone().formData();
3092
+ for (const [k, v] of body) {
3093
+ const vlabel = v instanceof Blob ? "<Blob>" : v;
3094
+ logger.log(`${k}: ${vlabel}`);
3095
+ }
3096
+ break;
3097
+ }
3098
+ default: logger.log(`<${contentType}>`);
3099
+ }
3100
+ logger.groupEnd();
3101
+ logger.groupEnd();
3102
+ }
3103
+ //#endregion
3104
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/extra/structChat.js
3105
+ /**
3106
+ * Recursively makes a JSON schema strict-mode compatible:
3107
+ * - Sets additionalProperties: false on all objects
3108
+ * - Makes optional properties required with nullable type
3109
+ * Mirrors Python SDK's rec_strict_json_schema + optional handling.
3110
+ */
3111
+ function makeStrictJsonSchema(node) {
3112
+ if (typeof node !== "object" || node === null) return node;
3113
+ const result = { ...node };
3114
+ if (result.type === "object" && result.properties && typeof result.properties === "object") {
3115
+ const required = new Set(Array.isArray(result.required) ? result.required : []);
3116
+ const props = {};
3117
+ for (const [key, value] of Object.entries(result.properties)) {
3118
+ const processed = makeStrictJsonSchema(value);
3119
+ if (!required.has(key)) {
3120
+ required.add(key);
3121
+ if (Array.isArray(processed.type)) {
3122
+ if (!processed.type.includes("null")) props[key] = {
3123
+ ...processed,
3124
+ type: [...processed.type, "null"]
3125
+ };
3126
+ else props[key] = processed;
3127
+ } else if (Array.isArray(processed.anyOf)) {
3128
+ if (!processed.anyOf.some((s) => s.type === "null")) props[key] = {
3129
+ ...processed,
3130
+ anyOf: [...processed.anyOf, { type: "null" }]
3131
+ };
3132
+ else props[key] = processed;
3133
+ } else if (processed.type) props[key] = {
3134
+ ...processed,
3135
+ type: [processed.type, "null"]
3136
+ };
3137
+ else props[key] = processed;
3138
+ } else props[key] = processed;
3139
+ }
3140
+ result.properties = props;
3141
+ result.required = [...required];
3142
+ result.additionalProperties = false;
3143
+ }
3144
+ if (result.items) result.items = makeStrictJsonSchema(result.items);
3145
+ for (const key of [
3146
+ "anyOf",
3147
+ "oneOf",
3148
+ "allOf"
3149
+ ]) if (Array.isArray(result[key])) result[key] = result[key].map(makeStrictJsonSchema);
3150
+ for (const key of ["$defs", "definitions"]) if (result[key] && typeof result[key] === "object") {
3151
+ const defs = {};
3152
+ for (const [k, v] of Object.entries(result[key])) defs[k] = makeStrictJsonSchema(v);
3153
+ result[key] = defs;
3154
+ }
3155
+ return result;
3156
+ }
3157
+ function toJsonSchema(schema) {
3158
+ let jsonSchema;
3159
+ if ("_zod" in schema) jsonSchema = z.toJSONSchema(schema);
3160
+ else jsonSchema = zodToJsonSchema(schema, { target: "openAi" });
3161
+ delete jsonSchema["$schema"];
3162
+ return makeStrictJsonSchema(jsonSchema);
3163
+ }
3164
+ function transformToChatCompletionRequest(parsedRequest) {
3165
+ const { responseFormat, ...rest } = parsedRequest;
3166
+ const transformedResponseFormat = responseFormatFromZodObject(responseFormat);
3167
+ return {
3168
+ ...rest,
3169
+ ...transformedResponseFormat ? { responseFormat: transformedResponseFormat } : {}
3170
+ };
3171
+ }
3172
+ function convertToParsedChatCompletionResponse(response, responseFormat) {
3173
+ if (response.choices === void 0 || response.choices.length === 0) return {
3174
+ ...response,
3175
+ choices: response.choices === void 0 ? void 0 : []
3176
+ };
3177
+ const parsedChoices = [];
3178
+ for (const _choice of response.choices) if (_choice.message === null || typeof _choice.message === "undefined") parsedChoices.push({
3179
+ ..._choice,
3180
+ message: void 0
3181
+ });
3182
+ else if (_choice.message.content !== null && typeof _choice.message.content !== "undefined" && !Array.isArray(_choice.message.content)) {
3183
+ let parsed;
3184
+ try {
3185
+ parsed = responseFormat.safeParse(JSON.parse(_choice.message.content)).data;
3186
+ } catch {
3187
+ parsed = void 0;
3188
+ }
3189
+ parsedChoices.push({
3190
+ ..._choice,
3191
+ message: {
3192
+ ..._choice.message,
3193
+ parsed
3194
+ }
3195
+ });
3196
+ } else parsedChoices.push({
3197
+ ..._choice,
3198
+ message: {
3199
+ ..._choice.message,
3200
+ parsed: void 0
3201
+ }
3202
+ });
3203
+ return {
3204
+ ...response,
3205
+ choices: parsedChoices
3206
+ };
3207
+ }
3208
+ function responseFormatFromZodObject(responseFormat) {
3209
+ return {
3210
+ type: "json_schema",
3211
+ jsonSchema: {
3212
+ name: "placeholderName",
3213
+ schemaDefinition: toJsonSchema(responseFormat),
3214
+ strict: true
3215
+ }
3216
+ };
3217
+ }
3218
+ //#endregion
3219
+ //#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/sdk/chat.js
3220
+ var Chat = class extends ClientSDK {
3221
+ /**
3222
+ * Chat Completion with the response parsed in the same format as the input requestFormat.
3223
+ *
3224
+ * @remarks
3225
+ * The response will be parsed back to the initial Zod object passed in the requestFormat field.
3226
+ */
3227
+ async parse(request, options) {
3228
+ const ccr_request = transformToChatCompletionRequest(request);
3229
+ return convertToParsedChatCompletionResponse(await unwrapAsync(chatComplete(this, ccr_request, options)), request.responseFormat);
3230
+ }
3231
+ /**
3232
+ * Stream chat completion with a parsed request input.
3233
+ *
3234
+ * @remarks
3235
+ * Unlike the .parse method, this method will return a stream of events containing the JSON response. It will not be parsed back to the initial Zod object.
3236
+ * If you need to parse the stream, see the examples/src/async_structured_outputs.ts file.
3237
+ */
3238
+ async parseStream(request, options) {
3239
+ const ccr_request = transformToChatCompletionRequest(request);
3240
+ return unwrapAsync(chatStream(this, ccr_request, options));
3241
+ }
3242
+ /**
3243
+ * Chat Completion
3244
+ */
3245
+ async complete(request, options) {
3246
+ return unwrapAsync(chatComplete(this, request, options));
3247
+ }
3248
+ /**
3249
+ * Stream chat completion
3250
+ *
3251
+ * @remarks
3252
+ * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
3253
+ */
3254
+ async stream(request, options) {
3255
+ return unwrapAsync(chatStream(this, request, options));
3256
+ }
3257
+ };
3258
+ //#endregion
3259
+ //#region packages/ai/src/providers/mistral.ts
3260
+ var mistral_exports = /* @__PURE__ */ __exportAll({
3261
+ createBoundedMistralFetcher: () => createBoundedMistralFetcher,
3262
+ streamMistral: () => streamMistral,
3263
+ streamSimpleMistral: () => streamSimpleMistral
3264
+ });
3265
+ const MISTRAL_TOOL_CALL_ID_LENGTH = 9;
3266
+ const MISTRAL_STREAM_BODY_MAX_BYTES = 16777216;
3267
+ /** Cap the SDK's response reader while preserving bodyless error responses. */
3268
+ function createBoundedMistralFetcher(upstreamFetch) {
3269
+ return async (input, init) => {
3270
+ const response = init == null ? await upstreamFetch(input) : await upstreamFetch(input, init);
3271
+ return boundResponseBody(response, {
3272
+ maxBytes: MISTRAL_STREAM_BODY_MAX_BYTES,
3273
+ onOverflow: ({ size, maxBytes: cap }) => /* @__PURE__ */ new Error(`mistral: stream body exceeds ${cap} bytes (got ${size})`)
3274
+ });
3275
+ };
3276
+ }
3277
+ const streamMistral = (model, context, options) => {
3278
+ const stream = new AssistantMessageEventStream();
3279
+ (async () => {
3280
+ const output = createAssistantOutput(model);
3281
+ try {
3282
+ const apiKey = requireApiKey(model.provider, options?.apiKey);
3283
+ const boundedFetcher = createBoundedMistralFetcher(getAiTransportHost().buildModelFetch(model) ?? fetch);
3284
+ let mistralResponse;
3285
+ let reportedResponse;
3286
+ const httpClient = new HTTPClient({ fetcher: boundedFetcher });
3287
+ httpClient.addHook("response", async (response) => {
3288
+ mistralResponse = response;
3289
+ if (!response.ok) {
3290
+ await notifyProviderHttpResponse({
3291
+ options,
3292
+ response,
3293
+ model
3294
+ });
3295
+ reportedResponse = response;
3296
+ }
3297
+ });
3298
+ const chat = new Chat({
3299
+ apiKey,
3300
+ serverURL: model.baseUrl,
3301
+ httpClient,
3302
+ retryConfig: { strategy: "none" }
3303
+ });
3304
+ const normalizeMistralToolCallId = createMistralToolCallIdNormalizer();
3305
+ const transformedMessages = transformProviderMessages(context.messages, model, normalizeMistralToolCallId);
3306
+ let payload = {
3307
+ model: model.id,
3308
+ stream: true,
3309
+ messages: toChatMessages(transformedMessages, model.input.includes("image"))
3310
+ };
3311
+ let convertedToolNames;
3312
+ if (context.tools?.length) {
3313
+ const toolsToConvert = context.tools;
3314
+ const mutablePayload = Boolean(options?.onPayload);
3315
+ const converted = toolsToConvert.map((tool) => {
3316
+ const name = tool.name;
3317
+ const description = tool.description;
3318
+ const parameters = tool.parameters;
3319
+ return {
3320
+ name,
3321
+ description,
3322
+ value: {
3323
+ type: "function",
3324
+ function: {
3325
+ name,
3326
+ description,
3327
+ parameters: !mutablePayload && getPublishedRuntimeToolInputSchema(parameters) ? parameters : structuredClone(parameters),
3328
+ strict: false
3329
+ }
3330
+ }
3331
+ };
3332
+ });
3333
+ const tools = sortPromptCacheToolsByName(converted).map(({ value }) => value);
3334
+ convertedToolNames = new Set(tools.map((tool) => tool.function.name));
3335
+ payload.tools = tools;
3336
+ }
3337
+ if (options?.temperature !== void 0) payload.temperature = options.temperature;
3338
+ if (options?.maxTokens !== void 0) payload.maxTokens = options.maxTokens;
3339
+ if (options?.stop !== void 0 && options.stop.length > 0) payload.stop = options.stop;
3340
+ if (options?.toolChoice) {
3341
+ const toolChoice = mapToolChoice(options.toolChoice, convertedToolNames);
3342
+ if (toolChoice) payload.toolChoice = toolChoice;
3343
+ }
3344
+ if (options?.promptMode) payload.promptMode = options.promptMode;
3345
+ if (options?.reasoningEffort) payload.reasoningEffort = options.reasoningEffort;
3346
+ const promptCacheKey = resolveMistralPromptCacheKey(options);
3347
+ if (promptCacheKey) payload.promptCacheKey = promptCacheKey;
3348
+ if (context.systemPrompt) payload.messages.unshift({
3349
+ role: "system",
3350
+ content: sanitizeSurrogates(stripSystemPromptCacheBoundary(context.systemPrompt))
3351
+ });
3352
+ const nextPayload = await options?.onPayload?.(payload, model);
3353
+ if (nextPayload !== void 0) payload = nextPayload;
3354
+ const headers = mergeTransportHeaders(model.headers, options?.headers) ?? {};
3355
+ if (resolveMistralPromptCacheKey(options) && options?.sessionId) {
3356
+ const affinityHeader = Object.keys(headers).find((name) => name.toLowerCase() === "x-affinity");
3357
+ if (!affinityHeader || headers[affinityHeader] === "") headers[affinityHeader ?? "x-affinity"] = options.sessionId;
3358
+ }
3359
+ const mistralStream = await chat.stream(payload, {
3360
+ headers: omitNullRequestHeaders(headers),
3361
+ signal: options?.signal
3362
+ });
3363
+ if (mistralResponse && mistralResponse !== reportedResponse) await notifyProviderHttpResponse({
3364
+ options,
3365
+ response: mistralResponse,
3366
+ model,
3367
+ cancelStream: (reason) => mistralStream.cancel(reason)
3368
+ });
3369
+ stream.push({
3370
+ type: "start",
3371
+ partial: output
3372
+ });
3373
+ const signal = options?.signal;
3374
+ let currentBlock = null;
3375
+ let terminalFinishReason;
3376
+ const blocks = output.content;
3377
+ const blockIndex = () => blocks.length - 1;
3378
+ const toolBlocks = [];
3379
+ const normalizeMissingToolCallId = createMistralToolCallIdNormalizer();
3380
+ const missingToolCallIdScope = randomUUID();
3381
+ const createMissingToolCallId = (contentIndex) => normalizeMissingToolCallId(`${missingToolCallIdScope}:toolcall:${contentIndex}`);
3382
+ const requireSingleCandidate = (candidates) => {
3383
+ if (candidates.length > 1) throw new Error("Mistral streamed tool-call continuation is ambiguous; refusing to merge arguments");
3384
+ return candidates[0];
3385
+ };
3386
+ const resolveToolBlock = (params) => {
3387
+ const explicitId = params.explicitId;
3388
+ const functionName = params.functionName;
3389
+ const toolCallIndex = params.index;
3390
+ const available = toolBlocks.filter((identity) => !params.usedContentIndexes.has(identity.contentIndex));
3391
+ const idCandidates = explicitId ? available.filter((identity) => identity.explicitIds.has(explicitId)) : [];
3392
+ const nameCandidates = functionName ? available.filter((identity) => identity.functionNames.has(functionName)) : [];
3393
+ if (idCandidates.length > 0) {
3394
+ let candidates = idCandidates;
3395
+ if (nameCandidates.length > 0) candidates = candidates.filter((identity) => nameCandidates.includes(identity));
3396
+ const candidate = requireSingleCandidate(candidates);
3397
+ if (!candidate) throw new Error("Mistral streamed tool-call identities conflict; refusing to merge arguments");
3398
+ return candidate;
3399
+ }
3400
+ if (nameCandidates.length > 0) {
3401
+ const idCompatibleCandidates = nameCandidates.filter((identity) => !explicitId || identity.explicitIds.size === 0);
3402
+ if (idCompatibleCandidates.length <= 1 && (toolCallIndex === void 0 || toolCallIndex === 0)) return requireSingleCandidate(idCompatibleCandidates);
3403
+ const indexCompatibleCandidates = idCompatibleCandidates.filter((identity) => toolCallIndex === void 0 || identity.indexes.size === 0 || identity.indexes.has(toolCallIndex));
3404
+ return requireSingleCandidate(indexCompatibleCandidates);
3405
+ }
3406
+ const indexCandidates = toolCallIndex === void 0 ? [] : available.filter((identity) => identity.indexes.has(toolCallIndex));
3407
+ return requireSingleCandidate(indexCandidates.filter((identity) => (!functionName || identity.functionNames.size === 0) && (!explicitId || identity.explicitIds.size === 0)));
3408
+ };
3409
+ const finishCurrentBlock = () => {
3410
+ if (!currentBlock) return;
3411
+ stream.push({
3412
+ type: currentBlock.type === "text" ? "text_end" : "thinking_end",
3413
+ contentIndex: blockIndex(),
3414
+ content: currentBlock.type === "text" ? currentBlock.text : currentBlock.thinking,
3415
+ partial: output
3416
+ });
3417
+ };
3418
+ const appendContentDelta = (type, text) => {
3419
+ const delta = sanitizeSurrogates(text);
3420
+ if (type === "thinking" && !delta) return;
3421
+ if (!currentBlock || currentBlock.type !== type) {
3422
+ finishCurrentBlock();
3423
+ currentBlock = type === "text" ? {
3424
+ type,
3425
+ text: ""
3426
+ } : {
3427
+ type,
3428
+ thinking: ""
3429
+ };
3430
+ output.content.push(currentBlock);
3431
+ stream.push({
3432
+ type: `${type}_start`,
3433
+ contentIndex: blockIndex(),
3434
+ partial: output
3435
+ });
3436
+ }
3437
+ if (currentBlock.type === "text") currentBlock.text += delta;
3438
+ else appendAssistantThinking(currentBlock, delta);
3439
+ stream.push({
3440
+ type: `${type}_delta`,
3441
+ contentIndex: blockIndex(),
3442
+ delta,
3443
+ partial: output
3444
+ });
3445
+ };
3446
+ for await (const event of mistralStream) {
3447
+ notifyLlmRequestActivity(signal);
3448
+ const chunk = event.data;
3449
+ output.responseId ||= chunk.id;
3450
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
3451
+ if (chunk.usage) {
3452
+ const usageOutput = output.usage;
3453
+ const usage = chunk.usage;
3454
+ const terminal = Boolean(terminalFinishReason || chunk.choices[0]?.finishReason);
3455
+ const promptTokens = usage.promptTokens || 0;
3456
+ const record = usage;
3457
+ const rawCachedTokens = record.promptTokensDetails?.cachedTokens ?? record.prompt_tokens_details?.cached_tokens ?? record.cachedTokens ?? record.cached_tokens;
3458
+ const cacheRead = Math.min(promptTokens, Math.max(0, typeof rawCachedTokens === "number" && Number.isFinite(rawCachedTokens) ? rawCachedTokens : 0));
3459
+ usageOutput.input = Math.max(0, promptTokens - cacheRead);
3460
+ usageOutput.output = usage.completionTokens || 0;
3461
+ usageOutput.cacheRead = cacheRead;
3462
+ usageOutput.cacheWrite = 0;
3463
+ usageOutput.totalTokens = usage.totalTokens || usageOutput.input + usageOutput.output + cacheRead;
3464
+ usageOutput.usageReport = { state: terminal ? "available" : "unavailable" };
3465
+ calculateCost(model, usageOutput);
3466
+ }
3467
+ const choice = chunk.choices[0];
3468
+ if (!choice) continue;
3469
+ if (choice.finishReason) {
3470
+ terminalFinishReason = choice.finishReason;
3471
+ const { stopReason, errorMessage } = mapOpenAIStopReason(choice.finishReason === "model_length" ? "length" : choice.finishReason);
3472
+ output.stopReason = stopReason;
3473
+ if (errorMessage) output.errorMessage = errorMessage;
3474
+ }
3475
+ const delta = choice.delta;
3476
+ if (delta.content !== null && delta.content !== void 0) {
3477
+ const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content;
3478
+ for (const item of contentItems) {
3479
+ if (typeof item === "string") {
3480
+ appendContentDelta("text", item);
3481
+ continue;
3482
+ }
3483
+ if (item.type === "thinking") appendContentDelta("thinking", item.thinking.map((part) => "text" in part ? part.text : "").join(""));
3484
+ else if (item.type === "text") appendContentDelta("text", item.text);
3485
+ }
3486
+ }
3487
+ const toolCalls = delta.toolCalls || [];
3488
+ const usedToolBlockIndexes = /* @__PURE__ */ new Set();
3489
+ for (const toolCall of toolCalls) {
3490
+ if (currentBlock) {
3491
+ finishCurrentBlock();
3492
+ currentBlock = null;
3493
+ }
3494
+ const toolCallIndex = typeof toolCall.index === "number" && Number.isInteger(toolCall.index) ? toolCall.index : void 0;
3495
+ const providedCallId = toolCall.id && toolCall.id !== "null" ? toolCall.id : void 0;
3496
+ const functionName = toolCall.function.name.trim() || void 0;
3497
+ let identity = resolveToolBlock({
3498
+ explicitId: providedCallId,
3499
+ functionName,
3500
+ index: toolCallIndex,
3501
+ usedContentIndexes: usedToolBlockIndexes
3502
+ });
3503
+ if (!identity) {
3504
+ const contentIndex = output.content.length;
3505
+ const block = {
3506
+ type: "toolCall",
3507
+ id: providedCallId ?? createMissingToolCallId(contentIndex),
3508
+ name: functionName ?? "",
3509
+ arguments: {},
3510
+ partialJson: ""
3511
+ };
3512
+ output.content.push(block);
3513
+ identity = {
3514
+ block,
3515
+ contentIndex,
3516
+ preview: createToolArgumentPreviewSchedule(),
3517
+ explicitIds: /* @__PURE__ */ new Set(),
3518
+ functionNames: /* @__PURE__ */ new Set(),
3519
+ indexes: /* @__PURE__ */ new Set()
3520
+ };
3521
+ toolBlocks.push(identity);
3522
+ stream.push({
3523
+ type: "toolcall_start",
3524
+ contentIndex,
3525
+ partial: output
3526
+ });
3527
+ }
3528
+ const { block, contentIndex } = identity;
3529
+ usedToolBlockIndexes.add(contentIndex);
3530
+ if (providedCallId) {
3531
+ block.id = providedCallId;
3532
+ identity.explicitIds.add(providedCallId);
3533
+ }
3534
+ if (functionName) {
3535
+ if (identity.functionNames.size > 0 && !identity.functionNames.has(functionName)) throw new Error("Mistral streamed tool-call continuation changed function name; refusing to merge arguments");
3536
+ block.name = functionName;
3537
+ identity.functionNames.add(functionName);
3538
+ }
3539
+ if (toolCallIndex !== void 0) identity.indexes.add(toolCallIndex);
3540
+ const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {});
3541
+ block.partialJson = (block.partialJson || "") + argsDelta;
3542
+ if (identity.preview(block.partialJson.length)) block.arguments = parseStreamingJson(block.partialJson);
3543
+ stream.push({
3544
+ type: "toolcall_delta",
3545
+ contentIndex,
3546
+ delta: argsDelta,
3547
+ partial: output
3548
+ });
3549
+ }
3550
+ }
3551
+ finishCurrentBlock();
3552
+ if (!terminalFinishReason || output.stopReason !== "toolUse") {
3553
+ blocks.splice(0, blocks.length, ...blocks.filter((block) => block.type !== "toolCall"));
3554
+ if (!terminalFinishReason) throw new Error("Mistral stream ended without a terminal finish reason");
3555
+ } else {
3556
+ finalizeTerminalToolCallArguments(toolBlocks.map(({ block }) => block), (block) => block.partialJson ?? "", "Mistral completed tool call has invalid JSON arguments");
3557
+ for (const { block, contentIndex } of toolBlocks) {
3558
+ delete block.partialJson;
3559
+ stream.push({
3560
+ type: "toolcall_end",
3561
+ contentIndex,
3562
+ toolCall: block,
3563
+ partial: output
3564
+ });
3565
+ }
3566
+ }
3567
+ finalizeTransportStream({
3568
+ stream,
3569
+ output,
3570
+ signal: options?.signal
3571
+ });
3572
+ } catch (error) {
3573
+ const terminal = assignTransportErrorDetails(output, error, options?.signal);
3574
+ output.content = output.content.filter((block) => block.type !== "toolCall");
3575
+ stream.push({
3576
+ type: "error",
3577
+ reason: terminal.stopReason,
3578
+ error: output
3579
+ });
3580
+ stream.end();
3581
+ }
3582
+ })();
3583
+ return stream;
3584
+ };
3585
+ const streamSimpleMistral = (model, context, options) => {
3586
+ const apiKey = requireApiKey(model.provider, options?.apiKey);
3587
+ const base = {
3588
+ ...buildBaseOptions(model, options, apiKey),
3589
+ maxTokens: clampMaxTokensToModel(model, options?.maxTokens)
3590
+ };
3591
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
3592
+ const reasoning = clampedReasoning === "off" ? void 0 : clampedReasoning;
3593
+ const shouldUseReasoning = model.reasoning && reasoning !== void 0;
3594
+ const supportsReasoningEffort = model.id === "mistral-small-2603" || model.id === "mistral-small-latest" || model.id === "mistral-medium-3-5";
3595
+ return streamMistral(model, context, {
3596
+ ...base,
3597
+ promptMode: shouldUseReasoning && !supportsReasoningEffort ? "reasoning" : void 0,
3598
+ reasoningEffort: shouldUseReasoning && supportsReasoningEffort ? ReasoningEffort$inboundSchema.parse(model.thinkingLevelMap?.[reasoning] ?? (reasoning === "minimal" ? "none" : "high")) : void 0
3599
+ });
3600
+ };
3601
+ function createMistralToolCallIdNormalizer() {
3602
+ const idMap = /* @__PURE__ */ new Map();
3603
+ const reverseMap = /* @__PURE__ */ new Map();
3604
+ return (id) => {
3605
+ const existing = idMap.get(id);
3606
+ if (existing) return existing;
3607
+ let attempt = 0;
3608
+ while (true) {
3609
+ const candidate = deriveMistralToolCallId(id, attempt);
3610
+ const owner = reverseMap.get(candidate);
3611
+ if (!owner || owner === id) {
3612
+ idMap.set(id, candidate);
3613
+ reverseMap.set(candidate, id);
3614
+ return candidate;
3615
+ }
3616
+ attempt++;
3617
+ }
3618
+ };
3619
+ }
3620
+ function deriveMistralToolCallId(id, attempt) {
3621
+ const normalized = id.replace(/[^a-zA-Z0-9]/g, "");
3622
+ if (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH) return normalized;
3623
+ const seedBase = normalized || id;
3624
+ const seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`;
3625
+ return shortHash(seed).replace(/[^a-zA-Z0-9]/g, "").padEnd(MISTRAL_TOOL_CALL_ID_LENGTH, "0").slice(0, MISTRAL_TOOL_CALL_ID_LENGTH);
3626
+ }
3627
+ function resolveMistralPromptCacheKey(options) {
3628
+ if (options?.cacheRetention === "none") return;
3629
+ return options?.promptCacheKey?.trim() || options?.sessionId?.trim() || void 0;
3630
+ }
3631
+ function toChatMessages(messages, supportsImages) {
3632
+ const result = [];
3633
+ for (const msg of messages) {
3634
+ if (msg.role === "user") {
3635
+ if (typeof msg.content === "string") {
3636
+ result.push({
3637
+ role: "user",
3638
+ content: sanitizeSurrogates(msg.content)
3639
+ });
3640
+ continue;
3641
+ }
3642
+ const hadImages = msg.content.some((item) => item.type === "image");
3643
+ const content = msg.content.filter((item) => item.type === "text" || supportsImages).map((item) => {
3644
+ if (item.type === "text") return {
3645
+ type: "text",
3646
+ text: sanitizeSurrogates(item.text)
3647
+ };
3648
+ return {
3649
+ type: "image_url",
3650
+ imageUrl: `data:${item.mimeType};base64,${item.data}`
3651
+ };
3652
+ });
3653
+ if (content.length > 0) {
3654
+ result.push({
3655
+ role: "user",
3656
+ content
3657
+ });
3658
+ continue;
3659
+ }
3660
+ if (hadImages && !supportsImages) result.push({
3661
+ role: "user",
3662
+ content: "(image omitted: model does not support images)"
3663
+ });
3664
+ continue;
3665
+ }
3666
+ if (msg.role === "assistant") {
3667
+ const contentParts = [];
3668
+ const toolCalls = [];
3669
+ for (const block of msg.content) {
3670
+ if (block.type === "text" || block.type === "thinking") {
3671
+ const text = block.type === "text" ? block.text : block.thinking;
3672
+ if (text.trim().length > 0) {
3673
+ const part = {
3674
+ type: "text",
3675
+ text: sanitizeSurrogates(text)
3676
+ };
3677
+ contentParts.push(block.type === "text" ? part : {
3678
+ type: "thinking",
3679
+ thinking: [part]
3680
+ });
3681
+ }
3682
+ continue;
3683
+ }
3684
+ toolCalls.push({
3685
+ id: block.id,
3686
+ type: "function",
3687
+ function: {
3688
+ name: block.name,
3689
+ arguments: JSON.stringify(block.arguments || {})
3690
+ }
3691
+ });
3692
+ }
3693
+ const assistantMessage = { role: "assistant" };
3694
+ if (contentParts.length > 0) assistantMessage.content = contentParts;
3695
+ if (toolCalls.length > 0) assistantMessage.toolCalls = toolCalls;
3696
+ if (contentParts.length > 0 || toolCalls.length > 0) result.push(assistantMessage);
3697
+ continue;
3698
+ }
3699
+ const toolContent = [];
3700
+ const textResult = extractToolResultText(msg.content);
3701
+ const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
3702
+ const omittedMediaPlaceholder = msg.content.some(isImageWithMediaPayload) && !supportsImages ? textResult.trim() ? "[tool image omitted: model does not support images]" : mediaPlaceholder === "(see attached media)" ? "(media omitted: model does not support images)" : "(image omitted: model does not support images)" : void 0;
3703
+ const toolText = formatToolResultText({
3704
+ text: textResult,
3705
+ mediaPlaceholder,
3706
+ omittedMediaPlaceholder,
3707
+ isError: msg.isError
3708
+ });
3709
+ toolContent.push({
3710
+ type: "text",
3711
+ text: toolText
3712
+ });
3713
+ for (const part of msg.content) {
3714
+ if (!supportsImages) continue;
3715
+ if (!isImageWithMediaPayload(part)) continue;
3716
+ toolContent.push({
3717
+ type: "image_url",
3718
+ imageUrl: `data:${part.mimeType};base64,${part.data}`
3719
+ });
3720
+ }
3721
+ result.push({
3722
+ role: "tool",
3723
+ toolCallId: msg.toolCallId,
3724
+ name: msg.toolName,
3725
+ content: toolContent
3726
+ });
3727
+ }
3728
+ return result;
3729
+ }
3730
+ function mapToolChoice(choice, convertedToolNames) {
3731
+ if (!choice) return;
3732
+ if (choice === "auto" || choice === "none" || choice === "any" || choice === "required") return choice;
3733
+ const toolName = choice.function.name;
3734
+ if (convertedToolNames && !convertedToolNames.has(toolName)) throw new Error(`Mistral tool_choice requested unavailable tool "${toolName}" after schema conversion`);
3735
+ return {
3736
+ type: "function",
3737
+ function: { name: toolName }
3738
+ };
3739
+ }
3740
+ //#endregion
3741
+ export { registerTracerProvider as a, createBoundedMistralFetcher, getRegisteredTracerProvider as i, completionChunkFromJSON as n, UsageInfo$outboundSchema as r, streamMistral, streamSimpleMistral, mistral_exports as t };