@enlitt/sdk 0.0.0-stage → 0.1.1

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 (117) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +63 -2
  4. package/dist/browser/auth.d.cts +44 -0
  5. package/dist/browser/auth.d.ts +45 -0
  6. package/dist/browser/auth.d.ts.map +1 -0
  7. package/dist/browser.cjs +35 -0
  8. package/dist/browser.cjs.map +1 -0
  9. package/dist/browser.d.cts +12 -0
  10. package/dist/browser.d.ts +13 -0
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +32 -0
  13. package/dist/browser.js.map +1 -0
  14. package/dist/chunk-2BGWYTJM.cjs +1097 -0
  15. package/dist/chunk-2BGWYTJM.cjs.map +1 -0
  16. package/dist/chunk-6OWXYBBT.cjs +146 -0
  17. package/dist/chunk-6OWXYBBT.cjs.map +1 -0
  18. package/dist/chunk-NI6WH5FI.js +33 -0
  19. package/dist/chunk-NI6WH5FI.js.map +1 -0
  20. package/dist/chunk-O6ASIA3X.js +866 -0
  21. package/dist/chunk-O6ASIA3X.js.map +1 -0
  22. package/dist/chunk-PPOUNWNA.cjs +895 -0
  23. package/dist/chunk-PPOUNWNA.cjs.map +1 -0
  24. package/dist/chunk-UVZMKGIL.js +1091 -0
  25. package/dist/chunk-UVZMKGIL.js.map +1 -0
  26. package/dist/chunk-V5TCSQ7C.js +143 -0
  27. package/dist/chunk-V5TCSQ7C.js.map +1 -0
  28. package/dist/chunk-YPA4R65T.cjs +35 -0
  29. package/dist/chunk-YPA4R65T.cjs.map +1 -0
  30. package/dist/core/errors.d.cts +262 -0
  31. package/dist/core/errors.d.ts +263 -0
  32. package/dist/core/errors.d.ts.map +1 -0
  33. package/dist/core/index.d.cts +24 -0
  34. package/dist/core/index.d.ts +25 -0
  35. package/dist/core/index.d.ts.map +1 -0
  36. package/dist/core/premium.d.cts +230 -0
  37. package/dist/core/premium.d.ts +231 -0
  38. package/dist/core/premium.d.ts.map +1 -0
  39. package/dist/core/session.d.cts +122 -0
  40. package/dist/core/session.d.ts +123 -0
  41. package/dist/core/session.d.ts.map +1 -0
  42. package/dist/core/sse.d.cts +79 -0
  43. package/dist/core/sse.d.ts +80 -0
  44. package/dist/core/sse.d.ts.map +1 -0
  45. package/dist/core/transport.d.cts +223 -0
  46. package/dist/core/transport.d.ts +224 -0
  47. package/dist/core/transport.d.ts.map +1 -0
  48. package/dist/core/usage.d.cts +35 -0
  49. package/dist/core/usage.d.ts +36 -0
  50. package/dist/core/usage.d.ts.map +1 -0
  51. package/dist/core.cjs +77 -0
  52. package/dist/core.cjs.map +1 -0
  53. package/dist/core.js +4 -0
  54. package/dist/core.js.map +1 -0
  55. package/dist/index.cjs +4 -0
  56. package/dist/index.cjs.map +1 -0
  57. package/dist/index.d.cts +16 -0
  58. package/dist/index.d.ts +17 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +3 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/openai/client.d.cts +72 -0
  63. package/dist/openai/client.d.ts +73 -0
  64. package/dist/openai/client.d.ts.map +1 -0
  65. package/dist/openai/index.d.cts +2 -0
  66. package/dist/openai/index.d.ts +3 -0
  67. package/dist/openai/index.d.ts.map +1 -0
  68. package/dist/openai/media.d.cts +108 -0
  69. package/dist/openai/media.d.ts +109 -0
  70. package/dist/openai/media.d.ts.map +1 -0
  71. package/dist/openai.cjs +623 -0
  72. package/dist/openai.cjs.map +1 -0
  73. package/dist/openai.js +617 -0
  74. package/dist/openai.js.map +1 -0
  75. package/dist/server/callback.d.cts +107 -0
  76. package/dist/server/callback.d.ts +108 -0
  77. package/dist/server/callback.d.ts.map +1 -0
  78. package/dist/server/client-sign-in.d.cts +77 -0
  79. package/dist/server/client-sign-in.d.ts +78 -0
  80. package/dist/server/client-sign-in.d.ts.map +1 -0
  81. package/dist/server/index.d.cts +20 -0
  82. package/dist/server/index.d.ts +21 -0
  83. package/dist/server/index.d.ts.map +1 -0
  84. package/dist/server/secrets.d.cts +46 -0
  85. package/dist/server/secrets.d.ts +47 -0
  86. package/dist/server/secrets.d.ts.map +1 -0
  87. package/dist/server-unavailable.cjs +8 -0
  88. package/dist/server-unavailable.cjs.map +1 -0
  89. package/dist/server-unavailable.d.cts +10 -0
  90. package/dist/server-unavailable.d.ts +11 -0
  91. package/dist/server-unavailable.d.ts.map +1 -0
  92. package/dist/server-unavailable.js +6 -0
  93. package/dist/server-unavailable.js.map +1 -0
  94. package/dist/server.cjs +880 -0
  95. package/dist/server.cjs.map +1 -0
  96. package/dist/server.js +795 -0
  97. package/dist/server.js.map +1 -0
  98. package/dist/vercel/index.d.cts +17 -0
  99. package/dist/vercel/index.d.ts +18 -0
  100. package/dist/vercel/index.d.ts.map +1 -0
  101. package/dist/vercel/language-model.d.cts +146 -0
  102. package/dist/vercel/language-model.d.ts +147 -0
  103. package/dist/vercel/language-model.d.ts.map +1 -0
  104. package/dist/vercel/premium-language-model.d.cts +127 -0
  105. package/dist/vercel/premium-language-model.d.ts +128 -0
  106. package/dist/vercel/premium-language-model.d.ts.map +1 -0
  107. package/dist/vercel/premium-media-model.d.cts +101 -0
  108. package/dist/vercel/premium-media-model.d.ts +102 -0
  109. package/dist/vercel/premium-media-model.d.ts.map +1 -0
  110. package/dist/vercel/standard-language-model.d.cts +104 -0
  111. package/dist/vercel/standard-language-model.d.ts +105 -0
  112. package/dist/vercel/standard-language-model.d.ts.map +1 -0
  113. package/dist/vercel.cjs +22 -0
  114. package/dist/vercel.cjs.map +1 -0
  115. package/dist/vercel.js +5 -0
  116. package/dist/vercel.js.map +1 -0
  117. package/package.json +139 -3
@@ -0,0 +1,1091 @@
1
+ import { createSseEventStream, SseFramingError } from './chunk-V5TCSQ7C.js';
2
+ import { assertNanoUsd, createInternalClient, EnlittConfigurationError, requestEnlitt, EnlittError, readEnlittJson, assertIdempotencyKeyBase, assertCallerMetadata, generateRandomCallId, assertCallId, runPremiumCharge, isCancellation, assertReportingDeadlineMs } from './chunk-O6ASIA3X.js';
3
+ import { ENLITT_STANDARD_MODEL, validateOpenAIResponse, validateEnlittStandardRequest, validateResponseStreamEvent, isTerminalResponseStreamEventType } from '@enlitt/protocol';
4
+ export { ENLITT_STANDARD_MODEL } from '@enlitt/protocol';
5
+
6
+ var RESPONSES_PATH = "/v1/responses";
7
+ var ENLITT_METADATA_KEYS = {
8
+ operationId: "enlitt_operation_id",
9
+ routedProvider: "enlitt_routed_provider",
10
+ routedModel: "enlitt_routed_model",
11
+ policyVersion: "enlitt_policy_version"
12
+ };
13
+ function createStandardLanguageModel(client) {
14
+ return {
15
+ specificationVersion: "v3",
16
+ provider: "enlitt",
17
+ modelId: ENLITT_STANDARD_MODEL,
18
+ // Every URL is downloaded by the caller or sent as an image URL rather than
19
+ // referenced natively: no pattern is claimed because none can be verified.
20
+ supportedUrls: {},
21
+ async doGenerate(params) {
22
+ const options = readEnlittCallOptions(params.providerOptions, "standard");
23
+ const callId = resolveCallId(options, params);
24
+ const body = buildStandardRequest(params, options);
25
+ const response = await requestEnlitt(client, {
26
+ path: RESPONSES_PATH,
27
+ body,
28
+ callId,
29
+ accept: "application/json",
30
+ ...params.abortSignal !== void 0 ? { signal: params.abortSignal } : {}
31
+ });
32
+ const validated = validateOpenAIResponse(await readEnlittJson(response), { mode: "tolerant" });
33
+ if (!validated.ok) {
34
+ throw new EnlittError(
35
+ "malformed_response",
36
+ `Enlitt's response could not be validated: ${validated.error.message} (${validated.error.param}).`
37
+ );
38
+ }
39
+ return mapStandardGenerateResponse(validated.value);
40
+ },
41
+ async doStream(params) {
42
+ const options = readEnlittCallOptions(params.providerOptions, "standard");
43
+ const callId = resolveCallId(options, params);
44
+ const body = buildStandardRequest(params, options, callId, true);
45
+ const response = await requestEnlitt(client, {
46
+ path: RESPONSES_PATH,
47
+ body,
48
+ callId,
49
+ accept: "text/event-stream",
50
+ ...params.abortSignal !== void 0 ? { signal: params.abortSignal } : {}
51
+ });
52
+ if (response.body === null) {
53
+ throw new EnlittError("malformed_response", "Enlitt's streaming response carried no body.");
54
+ }
55
+ const events = createSseEventStream(response.body);
56
+ return { stream: mapStandardStream(events, params.abortSignal) };
57
+ }
58
+ };
59
+ }
60
+ function hasProviderOptions(value) {
61
+ return typeof value === "object" && value !== null && Object.keys(value).length > 0;
62
+ }
63
+ function rejectItemProviderOptions(value, where) {
64
+ if (hasProviderOptions(value)) {
65
+ throw new EnlittConfigurationError(
66
+ `Enlitt's standard route does not support provider-specific options on ${where}; remove its providerOptions.`
67
+ );
68
+ }
69
+ }
70
+ function buildStandardRequest(params, options, callId, stream = false) {
71
+ rejectUnsupportedCallControls(params);
72
+ const draft = {
73
+ model: ENLITT_STANDARD_MODEL,
74
+ messages: mapPromptToMessages(params.prompt)
75
+ };
76
+ const choice = params.toolChoice?.type;
77
+ if (choice === "required" || choice === "tool") {
78
+ throw new EnlittConfigurationError(
79
+ "Enlitt's standard route supports only automatic tool choice; remove `toolChoice` or set it to auto or none."
80
+ );
81
+ }
82
+ if (choice !== "none" && params.tools !== void 0 && params.tools.length > 0) {
83
+ draft.tools = mapTools(params.tools);
84
+ }
85
+ if (params.maxOutputTokens !== void 0) {
86
+ draft.max_output_tokens = params.maxOutputTokens;
87
+ }
88
+ if (stream) {
89
+ draft.stream = true;
90
+ }
91
+ if (options.metadata !== void 0) {
92
+ draft.metadata = options.metadata;
93
+ }
94
+ const validated = validateEnlittStandardRequest(draft);
95
+ if (!validated.ok) {
96
+ throw new EnlittConfigurationError(
97
+ `The call could not be mapped to Enlitt's standard request shape: ${validated.error.message} (${validated.error.param}).`
98
+ );
99
+ }
100
+ return validated.value;
101
+ }
102
+ function rejectUnsupportedCallControls(params) {
103
+ const unsupported = [
104
+ ["temperature", params.temperature !== void 0],
105
+ ["topP", params.topP !== void 0],
106
+ ["topK", params.topK !== void 0],
107
+ ["presencePenalty", params.presencePenalty !== void 0],
108
+ ["frequencyPenalty", params.frequencyPenalty !== void 0],
109
+ ["seed", params.seed !== void 0],
110
+ ["stopSequences", params.stopSequences !== void 0 && params.stopSequences.length > 0],
111
+ // A "text" response format is the default and carries nothing; "json" is structured output.
112
+ ["responseFormat", params.responseFormat !== void 0 && params.responseFormat.type !== "text"]
113
+ ];
114
+ for (const [name, present] of unsupported) {
115
+ if (present) {
116
+ throw new EnlittConfigurationError(
117
+ `Enlitt's standard route does not support \`${name}\`; remove it from the call.`
118
+ );
119
+ }
120
+ }
121
+ for (const namespace of Object.keys(params.providerOptions ?? {})) {
122
+ if (namespace !== "enlitt") {
123
+ throw new EnlittConfigurationError(
124
+ `Enlitt's standard route does not support provider-specific options (providerOptions.${namespace}); remove them.`
125
+ );
126
+ }
127
+ }
128
+ }
129
+ function mapPromptToMessages(prompt) {
130
+ const messages = [];
131
+ for (const message of prompt) {
132
+ rejectItemProviderOptions(message.providerOptions, `a ${message.role} message`);
133
+ switch (message.role) {
134
+ case "system": {
135
+ messages.push({ role: "system", content: message.content });
136
+ break;
137
+ }
138
+ case "user": {
139
+ messages.push({ role: "user", content: message.content.map(mapUserPart) });
140
+ break;
141
+ }
142
+ case "assistant": {
143
+ messages.push(mapAssistantMessage(message.content));
144
+ break;
145
+ }
146
+ case "tool": {
147
+ for (const part of message.content) {
148
+ if (part.type === "tool-approval-response") {
149
+ throw new EnlittConfigurationError(
150
+ "Enlitt's standard route does not support tool approval responses; remove the approval response."
151
+ );
152
+ }
153
+ rejectItemProviderOptions(part.providerOptions, "a tool result");
154
+ messages.push({ role: "tool", tool_call_id: part.toolCallId, content: mapToolResultOutput(part.output) });
155
+ }
156
+ break;
157
+ }
158
+ }
159
+ }
160
+ return messages;
161
+ }
162
+ function mapUserPart(part) {
163
+ rejectItemProviderOptions(part.providerOptions, `a user ${part.type} part`);
164
+ if (part.type === "text") {
165
+ return { type: "text", text: part.text };
166
+ }
167
+ if (!part.mediaType.startsWith("image/")) {
168
+ throw new EnlittConfigurationError(
169
+ `Enlitt's standard route supports only text and image parts; "${part.mediaType}" files are not supported.`
170
+ );
171
+ }
172
+ if (part.data instanceof URL) {
173
+ return { type: "image", source: { type: "url", url: part.data.toString() } };
174
+ }
175
+ const data = typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64");
176
+ return { type: "image", source: { type: "base64", media_type: part.mediaType, data } };
177
+ }
178
+ function mapAssistantMessage(content) {
179
+ let text = "";
180
+ const toolCalls = [];
181
+ for (const part of content) {
182
+ rejectItemProviderOptions(part.providerOptions, `an assistant ${part.type} part`);
183
+ switch (part.type) {
184
+ case "text":
185
+ text += part.text;
186
+ break;
187
+ case "tool-call": {
188
+ if (part.providerExecuted === true) {
189
+ throw new EnlittConfigurationError(
190
+ "Enlitt's standard route does not support provider-executed tool calls in history."
191
+ );
192
+ }
193
+ toolCalls.push({
194
+ id: part.toolCallId,
195
+ name: part.toolName,
196
+ arguments: typeof part.input === "string" ? part.input : JSON.stringify(part.input)
197
+ });
198
+ break;
199
+ }
200
+ case "file":
201
+ case "reasoning":
202
+ case "tool-result":
203
+ throw new EnlittConfigurationError(
204
+ `Enlitt's standard route does not support an assistant "${part.type}" part in history.`
205
+ );
206
+ }
207
+ }
208
+ return {
209
+ role: "assistant",
210
+ ...text.length > 0 ? { content: text } : {},
211
+ ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
212
+ };
213
+ }
214
+ function mapToolResultOutput(output) {
215
+ switch (output.type) {
216
+ case "text":
217
+ case "error-text":
218
+ return String(output.value);
219
+ case "json":
220
+ case "error-json":
221
+ return JSON.stringify(output.value);
222
+ default:
223
+ throw new EnlittConfigurationError(
224
+ `Enlitt's standard route does not support a tool result output of type "${output.type}".`
225
+ );
226
+ }
227
+ }
228
+ function mapTools(tools) {
229
+ return tools.map((tool) => {
230
+ if (tool.type !== "function") {
231
+ throw new EnlittConfigurationError(
232
+ "Enlitt's standard route accepts only application-defined function tools, not provider-defined tools."
233
+ );
234
+ }
235
+ rejectItemProviderOptions(tool.providerOptions, `the tool "${tool.name}"`);
236
+ if (tool.strict !== void 0) {
237
+ throw new EnlittConfigurationError(
238
+ `Enlitt's standard route does not support strict tool schemas; remove \`strict\` from the tool "${tool.name}".`
239
+ );
240
+ }
241
+ return {
242
+ name: tool.name,
243
+ ...tool.description !== void 0 ? { description: tool.description } : {},
244
+ input_schema: tool.inputSchema
245
+ };
246
+ });
247
+ }
248
+ function isUnknownVariant(value) {
249
+ return "unknown" in value && value.unknown === true;
250
+ }
251
+ function mapStandardGenerateResponse(response) {
252
+ const content = [];
253
+ const skippedTypes = /* @__PURE__ */ new Set();
254
+ for (const item of response.output) {
255
+ if (isUnknownVariant(item)) {
256
+ skippedTypes.add(item.type);
257
+ } else if (item.type === "message") {
258
+ for (const part of item.content) {
259
+ if (isUnknownVariant(part)) {
260
+ skippedTypes.add(part.type);
261
+ } else {
262
+ content.push({ type: "text", text: part.text });
263
+ }
264
+ }
265
+ } else {
266
+ content.push({ type: "tool-call", toolCallId: item.call_id, toolName: item.name, input: item.arguments });
267
+ }
268
+ }
269
+ const warnings = [...skippedTypes].map((type) => ({
270
+ type: "other",
271
+ message: `Enlitt returned an output item of type "${type}" that this version of @enlitt/sdk does not recognize and skipped it. Upgrade @enlitt/sdk to receive it.`
272
+ }));
273
+ return {
274
+ content,
275
+ finishReason: mapFinishReason(response),
276
+ usage: mapUsage(response),
277
+ warnings,
278
+ ...hasRoutingMetadata(response) ? { providerMetadata: { enlitt: routingMetadata(response) } } : {}
279
+ };
280
+ }
281
+ function mapFinishReason(response) {
282
+ switch (response.status) {
283
+ case "other":
284
+ return { unified: "other", raw: void 0 };
285
+ case "failed":
286
+ return { unified: "error", raw: response.error?.code };
287
+ case "incomplete": {
288
+ const reason = response.incomplete_details?.reason;
289
+ if (reason === "max_output_tokens") {
290
+ return { unified: "length", raw: reason };
291
+ }
292
+ return { unified: "other", raw: reason === "other" ? void 0 : reason };
293
+ }
294
+ case "completed":
295
+ return response.output.some((item) => !isUnknownVariant(item) && item.type === "function_call") ? { unified: "tool-calls", raw: response.status } : { unified: "stop", raw: response.status };
296
+ case "in_progress":
297
+ case "queued":
298
+ case "cancelled":
299
+ return { unified: "other", raw: response.status };
300
+ }
301
+ }
302
+ function mapUsage(response) {
303
+ const usage = response.usage;
304
+ const cachedTokens = usage?.input_tokens_details?.cached_tokens;
305
+ const reasoningTokens = usage?.output_tokens_details?.reasoning_tokens;
306
+ return {
307
+ inputTokens: {
308
+ total: usage?.input_tokens,
309
+ noCache: usage !== void 0 && cachedTokens !== void 0 ? usage.input_tokens - cachedTokens : void 0,
310
+ cacheRead: cachedTokens,
311
+ cacheWrite: void 0
312
+ },
313
+ outputTokens: {
314
+ total: usage?.output_tokens,
315
+ text: usage?.output_tokens !== void 0 && reasoningTokens !== void 0 ? usage.output_tokens - reasoningTokens : usage?.output_tokens,
316
+ reasoning: reasoningTokens
317
+ }
318
+ };
319
+ }
320
+ function hasRoutingMetadata(response) {
321
+ return Object.values(ENLITT_METADATA_KEYS).some((key) => response.metadata[key] !== void 0);
322
+ }
323
+ function routingMetadata(response) {
324
+ const metadata = response.metadata;
325
+ const pick = (name) => {
326
+ const value = metadata[ENLITT_METADATA_KEYS[name]];
327
+ return value !== void 0 ? { [name]: value } : {};
328
+ };
329
+ return {
330
+ ...pick("operationId"),
331
+ ...pick("routedProvider"),
332
+ ...pick("routedModel"),
333
+ ...pick("policyVersion")
334
+ };
335
+ }
336
+ function isKnownEvent(event) {
337
+ return !isUnknownVariant(event);
338
+ }
339
+ function isTerminalEvent(event) {
340
+ return isKnownEvent(event) && isTerminalResponseStreamEventType(event.type);
341
+ }
342
+ function sameEvent(a, b) {
343
+ return JSON.stringify(a) === JSON.stringify(b);
344
+ }
345
+ function mapStandardStream(events, signal) {
346
+ const reader = events.getReader();
347
+ let lastEvent;
348
+ let terminated = false;
349
+ let sawTerminal = false;
350
+ const openText = /* @__PURE__ */ new Set();
351
+ const toolItems = /* @__PURE__ */ new Map();
352
+ function onAbort(controller) {
353
+ if (!terminated) {
354
+ terminated = true;
355
+ controller.error(signal?.reason);
356
+ void reader.cancel(signal?.reason).catch(() => void 0);
357
+ }
358
+ }
359
+ function reject(controller, message) {
360
+ terminated = true;
361
+ controller.enqueue({ type: "error", error: new EnlittError("malformed_response", message) });
362
+ controller.close();
363
+ void reader.cancel().catch(() => void 0);
364
+ }
365
+ return new ReadableStream({
366
+ start(controller) {
367
+ if (signal !== void 0) {
368
+ if (signal.aborted) {
369
+ onAbort(controller);
370
+ } else {
371
+ signal.addEventListener("abort", () => onAbort(controller), { once: true });
372
+ }
373
+ }
374
+ },
375
+ async pull(controller) {
376
+ for (; ; ) {
377
+ if (terminated) {
378
+ return;
379
+ }
380
+ let raw;
381
+ try {
382
+ raw = await reader.read();
383
+ } catch (thrown) {
384
+ if (thrown instanceof SseFramingError) {
385
+ reject(controller, thrown.message);
386
+ } else {
387
+ terminated = true;
388
+ controller.error(thrown);
389
+ }
390
+ return;
391
+ }
392
+ if (sawTerminal) {
393
+ if (raw.done) {
394
+ terminated = true;
395
+ controller.close();
396
+ } else {
397
+ reject(controller, "A stream event was received after the terminal event.");
398
+ }
399
+ return;
400
+ }
401
+ if (raw.done) {
402
+ reject(controller, "The stream ended before a terminal event was received.");
403
+ return;
404
+ }
405
+ let json;
406
+ try {
407
+ json = JSON.parse(raw.value.data);
408
+ } catch {
409
+ reject(controller, "A stream event's data payload was not valid JSON.");
410
+ return;
411
+ }
412
+ const validated = validateResponseStreamEvent(json, { mode: "tolerant" });
413
+ if (!validated.ok) {
414
+ reject(controller, `A stream event failed validation: ${validated.error.message} (${validated.error.param}).`);
415
+ return;
416
+ }
417
+ const event = validated.value;
418
+ const orderingError = checkIncrementalOrdering(lastEvent, event);
419
+ if (orderingError !== void 0) {
420
+ reject(controller, orderingError);
421
+ return;
422
+ }
423
+ const isIdenticalRepeat = lastEvent !== void 0 && sameEvent(lastEvent, event);
424
+ lastEvent = event;
425
+ if (isIdenticalRepeat) {
426
+ continue;
427
+ }
428
+ const parts = isKnownEvent(event) ? translateEvent(event, openText, toolItems) : [];
429
+ if (isTerminalEvent(event)) {
430
+ sawTerminal = true;
431
+ }
432
+ if (parts.length === 0) {
433
+ continue;
434
+ }
435
+ for (const part of parts) {
436
+ controller.enqueue(part);
437
+ }
438
+ return;
439
+ }
440
+ },
441
+ async cancel(reason) {
442
+ terminated = true;
443
+ await reader.cancel(reason);
444
+ }
445
+ });
446
+ }
447
+ function checkIncrementalOrdering(previous, next) {
448
+ if (previous === void 0) {
449
+ return next.type === "response.created" ? void 0 : `The first stream event must be "response.created", got "${next.type}".`;
450
+ }
451
+ if (isTerminalEvent(previous)) {
452
+ return "A stream event was received after the terminal event.";
453
+ }
454
+ if (next.sequence_number === previous.sequence_number) {
455
+ return sameEvent(previous, next) ? void 0 : "Two stream events carried the same sequence_number with conflicting payloads.";
456
+ }
457
+ if (next.sequence_number < previous.sequence_number) {
458
+ return "A stream event arrived out of order (its sequence_number was lower than a prior event's).";
459
+ }
460
+ if (next.sequence_number !== previous.sequence_number + 1) {
461
+ return "A stream event's sequence_number skipped a value (a gap in the sequence).";
462
+ }
463
+ return void 0;
464
+ }
465
+ function translateEvent(event, openText, toolItems) {
466
+ switch (event.type) {
467
+ case "response.created":
468
+ return [{ type: "stream-start", warnings: [] }];
469
+ case "response.output_item.added": {
470
+ const item = event.item;
471
+ if (isUnknownVariant(item) || item.type !== "function_call") {
472
+ return [];
473
+ }
474
+ toolItems.set(item.id, { callId: item.call_id, name: item.name });
475
+ return [{ type: "tool-input-start", id: item.call_id, toolName: item.name }];
476
+ }
477
+ case "response.output_text.delta": {
478
+ const parts = [];
479
+ if (!openText.has(event.item_id)) {
480
+ openText.add(event.item_id);
481
+ parts.push({ type: "text-start", id: event.item_id });
482
+ }
483
+ parts.push({ type: "text-delta", id: event.item_id, delta: event.delta });
484
+ return parts;
485
+ }
486
+ case "response.output_text.done": {
487
+ const parts = [];
488
+ if (!openText.has(event.item_id)) {
489
+ parts.push({ type: "text-start", id: event.item_id });
490
+ }
491
+ openText.delete(event.item_id);
492
+ parts.push({ type: "text-end", id: event.item_id });
493
+ return parts;
494
+ }
495
+ case "response.function_call_arguments.delta": {
496
+ const tool = toolItems.get(event.item_id);
497
+ return [{ type: "tool-input-delta", id: tool?.callId ?? event.item_id, delta: event.delta }];
498
+ }
499
+ case "response.function_call_arguments.done": {
500
+ const tool = toolItems.get(event.item_id);
501
+ const callId = tool?.callId ?? event.item_id;
502
+ return [
503
+ { type: "tool-input-end", id: callId },
504
+ { type: "tool-call", toolCallId: callId, toolName: tool?.name ?? event.item_id, input: event.arguments }
505
+ ];
506
+ }
507
+ case "response.completed":
508
+ case "response.incomplete":
509
+ case "response.failed":
510
+ return [
511
+ {
512
+ type: "finish",
513
+ finishReason: event.type === "response.completed" && toolItems.size > 0 && event.response.status === "completed" ? { unified: "tool-calls", raw: event.response.status } : mapFinishReason(event.response),
514
+ usage: mapUsage(event.response),
515
+ ...hasRoutingMetadata(event.response) ? { providerMetadata: { enlitt: routingMetadata(event.response) } } : {}
516
+ }
517
+ ];
518
+ // Bookkeeping events carry nothing a consumer needs.
519
+ case "response.in_progress":
520
+ case "response.output_item.done":
521
+ case "response.content_part.added":
522
+ case "response.content_part.done":
523
+ return [];
524
+ }
525
+ }
526
+
527
+ // src/vercel/premium-language-model.ts
528
+ function perToken(rates) {
529
+ const inputRate = BigInt(assertNanoUsd(rates.input, "perToken input rate"));
530
+ const outputRate = BigInt(assertNanoUsd(rates.output, "perToken output rate"));
531
+ return (context) => {
532
+ const inputTokens = BigInt(context.usage?.inputTokens.total ?? 0);
533
+ const outputTokens = BigInt(context.usage?.outputTokens.total ?? 0);
534
+ return (inputRate * inputTokens + outputRate * outputTokens).toString();
535
+ };
536
+ }
537
+ function createPremiumLanguageModel(client, wrappedModel) {
538
+ const model = wrappedModel;
539
+ const wrapper = {
540
+ specificationVersion: wrappedModel.specificationVersion,
541
+ provider: model.provider,
542
+ modelId: model.modelId,
543
+ supportedUrls: model.supportedUrls,
544
+ doGenerate(params) {
545
+ return invoke(
546
+ params,
547
+ (request, price) => wrapPremiumGenerate(client, request, price, () => Promise.resolve(model.doGenerate(params)))
548
+ );
549
+ },
550
+ doStream(params) {
551
+ return invoke(
552
+ params,
553
+ (request, price) => wrapPremiumStream(client, request, price, () => Promise.resolve(model.doStream(params)))
554
+ );
555
+ }
556
+ };
557
+ return wrapper;
558
+ async function invoke(params, wrap) {
559
+ const options = readEnlittCallOptions(params.providerOptions, "premium");
560
+ const callId = resolveCallId(options, params);
561
+ const request = {
562
+ maxCharge: options.maxCharge,
563
+ provider: { id: model.provider, model: model.modelId },
564
+ callId,
565
+ ...options.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: options.reportingDeadlineMs } : {},
566
+ ...options.metadata !== void 0 ? { metadata: options.metadata } : {},
567
+ ...params.abortSignal !== void 0 ? { signal: params.abortSignal } : {}
568
+ };
569
+ return wrap(request, options.price);
570
+ }
571
+ }
572
+ async function evaluatePrice(client, price, context) {
573
+ if (price === void 0) {
574
+ return "0";
575
+ }
576
+ if (typeof price === "string") {
577
+ return price;
578
+ }
579
+ try {
580
+ return assertNanoUsd(await price(context), "price() result");
581
+ } catch (thrown) {
582
+ const detail = thrown instanceof Error ? thrown.message : "the price function failed";
583
+ client.onTerminalReportError?.(
584
+ thrown instanceof EnlittConfigurationError ? thrown : new EnlittConfigurationError(`The price function failed, so the call was charged "0": ${detail}`)
585
+ );
586
+ return "0";
587
+ }
588
+ }
589
+ function wrapPremiumGenerate(client, request, price, run) {
590
+ return runPremiumCharge(client, request, async (charge, operation) => {
591
+ const startedAt = /* @__PURE__ */ new Date();
592
+ let result;
593
+ try {
594
+ result = await run();
595
+ } catch (thrown) {
596
+ if (isCancellation(thrown, request.signal)) {
597
+ const endedAt2 = /* @__PURE__ */ new Date();
598
+ charge(
599
+ await evaluatePrice(client, price, {
600
+ status: "canceled",
601
+ output: { kind: "generate", content: [] },
602
+ startedAt,
603
+ endedAt: endedAt2,
604
+ durationMs: endedAt2.getTime() - startedAt.getTime(),
605
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
606
+ })
607
+ );
608
+ operation.describe({
609
+ timing: timingFacts(startedAt, endedAt2),
610
+ delivery: { outputStarted: false, outputCompleted: false },
611
+ errorCategory: "canceled"
612
+ });
613
+ } else {
614
+ operation.describe({
615
+ timing: timingFacts(startedAt, /* @__PURE__ */ new Date()),
616
+ delivery: { outputStarted: false, outputCompleted: false },
617
+ errorCategory: "provider"
618
+ });
619
+ }
620
+ throw thrown;
621
+ }
622
+ const endedAt = /* @__PURE__ */ new Date();
623
+ charge(
624
+ await evaluatePrice(client, price, {
625
+ status: "completed",
626
+ output: { kind: "generate", content: result.content },
627
+ usage: result.usage,
628
+ finishReason: result.finishReason,
629
+ ...result.providerMetadata !== void 0 ? { providerMetadata: result.providerMetadata } : {},
630
+ startedAt,
631
+ endedAt,
632
+ durationMs: endedAt.getTime() - startedAt.getTime(),
633
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
634
+ })
635
+ );
636
+ operation.describe({
637
+ timing: timingFacts(startedAt, endedAt),
638
+ delivery: { outputStarted: true, outputCompleted: true },
639
+ finishReason: result.finishReason.unified,
640
+ ...result.response?.id !== void 0 ? { providerResponseId: result.response.id } : {},
641
+ ...usageFacts(result.usage)
642
+ });
643
+ return attachEnlittMetadataToGenerateResult(result, operation);
644
+ });
645
+ }
646
+ var CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
647
+ "text-delta",
648
+ "reasoning-delta",
649
+ "tool-input-delta",
650
+ "tool-call",
651
+ "file",
652
+ "source"
653
+ ]);
654
+ function wrapPremiumStream(client, request, price, run) {
655
+ return new Promise((resolveStreamResult, rejectStreamResult) => {
656
+ const settler = {};
657
+ const lifecycle = runPremiumCharge(client, request, async (charge, operation) => {
658
+ const startedAt = /* @__PURE__ */ new Date();
659
+ let result;
660
+ try {
661
+ result = await run();
662
+ } catch (thrown) {
663
+ operation.describe({
664
+ timing: timingFacts(startedAt, /* @__PURE__ */ new Date()),
665
+ delivery: { outputStarted: false, outputCompleted: false },
666
+ errorCategory: isCancellation(thrown, request.signal) ? "canceled" : "provider"
667
+ });
668
+ throw thrown;
669
+ }
670
+ const parked = new Promise((resolve, reject) => {
671
+ settler.resolve = resolve;
672
+ settler.reject = reject;
673
+ });
674
+ resolveStreamResult(wrapStream(client, request, price, result, charge, operation, startedAt, settler, lifecycle));
675
+ return parked;
676
+ });
677
+ lifecycle.catch(rejectStreamResult);
678
+ });
679
+ }
680
+ function wrapStream(client, request, price, result, charge, operation, startedAt, settler, lifecycle) {
681
+ const collectParts = typeof price === "function";
682
+ const parts = [];
683
+ const reader = result.stream.getReader();
684
+ let outputStarted = false;
685
+ let firstContentAt;
686
+ let finish;
687
+ let sawErrorPart = false;
688
+ let responseId;
689
+ let settlement;
690
+ const settle = (outcome) => {
691
+ settlement ??= (async () => {
692
+ const endedAt = /* @__PURE__ */ new Date();
693
+ const facts = {
694
+ timing: timingFacts(startedAt, endedAt),
695
+ delivery: { outputStarted, outputCompleted: outcome === "completed" }
696
+ };
697
+ if (outcome === "failed") {
698
+ operation.describe({ ...facts, errorCategory: "provider" });
699
+ settler.reject(new Error("The provider stream failed."));
700
+ } else {
701
+ charge(
702
+ await evaluatePrice(client, price, {
703
+ status: outcome,
704
+ output: { kind: "stream", parts },
705
+ ...finish !== void 0 ? { usage: finish.usage, finishReason: finish.finishReason } : {},
706
+ ...finish?.providerMetadata !== void 0 ? { providerMetadata: finish.providerMetadata } : {},
707
+ startedAt,
708
+ endedAt,
709
+ durationMs: endedAt.getTime() - startedAt.getTime(),
710
+ ...firstContentAt !== void 0 ? { timeToFirstTokenMs: firstContentAt.getTime() - startedAt.getTime() } : {},
711
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
712
+ })
713
+ );
714
+ operation.describe({
715
+ ...facts,
716
+ ...finish !== void 0 ? { finishReason: finish.finishReason.unified, ...usageFacts(finish.usage) } : {},
717
+ ...responseId !== void 0 ? { providerResponseId: responseId } : {},
718
+ ...outcome === "canceled" ? { errorCategory: "canceled" } : {}
719
+ });
720
+ if (outcome === "completed") {
721
+ settler.resolve();
722
+ } else {
723
+ settler.reject(Object.assign(new Error("The stream was canceled."), { name: "AbortError" }));
724
+ }
725
+ }
726
+ await lifecycle.catch(() => void 0);
727
+ })();
728
+ return settlement;
729
+ };
730
+ const stream = new ReadableStream({
731
+ async pull(controller) {
732
+ let chunk;
733
+ try {
734
+ chunk = await reader.read();
735
+ } catch (thrown) {
736
+ await settle(isCancellation(thrown, request.signal) ? "canceled" : "failed");
737
+ controller.error(thrown);
738
+ return;
739
+ }
740
+ if (chunk.done) {
741
+ await settle(finish !== void 0 && !sawErrorPart ? "completed" : "failed");
742
+ controller.close();
743
+ return;
744
+ }
745
+ const part = chunk.value;
746
+ if (collectParts) parts.push(part);
747
+ if (part.type === "response-metadata" && part.id !== void 0) responseId = part.id;
748
+ if (CONTENT_PART_TYPES.has(part.type)) {
749
+ outputStarted = true;
750
+ firstContentAt ??= /* @__PURE__ */ new Date();
751
+ }
752
+ if (part.type === "error") sawErrorPart = true;
753
+ if (part.type === "finish") {
754
+ finish = part;
755
+ controller.enqueue({
756
+ ...part,
757
+ providerMetadata: {
758
+ ...part.providerMetadata,
759
+ enlitt: {
760
+ operationId: operation.operationId,
761
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
762
+ }
763
+ }
764
+ });
765
+ } else {
766
+ controller.enqueue(part);
767
+ }
768
+ },
769
+ async cancel(reason) {
770
+ await reader.cancel(reason).catch(() => void 0);
771
+ await settle("canceled");
772
+ }
773
+ });
774
+ return { ...result, stream };
775
+ }
776
+ function timingFacts(startedAt, endedAt) {
777
+ return { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() };
778
+ }
779
+ function usageFacts(usage) {
780
+ const counts = {
781
+ ...usage.inputTokens.total !== void 0 ? { inputTokens: usage.inputTokens.total } : {},
782
+ ...usage.outputTokens.total !== void 0 ? { outputTokens: usage.outputTokens.total } : {},
783
+ ...usage.inputTokens.cacheRead !== void 0 ? { cachedInputTokens: usage.inputTokens.cacheRead } : {},
784
+ ...usage.outputTokens.reasoning !== void 0 ? { reasoningTokens: usage.outputTokens.reasoning } : {}
785
+ };
786
+ return Object.keys(counts).length > 0 ? { usage: counts } : {};
787
+ }
788
+ function attachEnlittMetadataToGenerateResult(result, operation) {
789
+ return {
790
+ ...result,
791
+ providerMetadata: {
792
+ ...result.providerMetadata,
793
+ enlitt: {
794
+ operationId: operation.operationId,
795
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
796
+ }
797
+ }
798
+ };
799
+ }
800
+
801
+ // src/vercel/premium-media-model.ts
802
+ function createPremiumMediaModel(client, model, kind) {
803
+ const labels = { id: model.provider, model: model.modelId };
804
+ if (kind === "image") {
805
+ const image = model;
806
+ const maxImagesPerCall = image.maxImagesPerCall;
807
+ const wrapped2 = {
808
+ specificationVersion: model.specificationVersion,
809
+ provider: image.provider,
810
+ modelId: image.modelId,
811
+ // Forwarded by reference. A function is bound so that a provider
812
+ // implementation reading `this` still sees its own model.
813
+ maxImagesPerCall: typeof maxImagesPerCall === "function" ? maxImagesPerCall.bind(image) : maxImagesPerCall,
814
+ doGenerate: (options) => runMediaCall(client, labels, options.providerOptions, options.abortSignal, {
815
+ kind: "image",
816
+ request: {
817
+ n: options.n,
818
+ ...options.size !== void 0 ? { size: options.size } : {},
819
+ ...options.aspectRatio !== void 0 ? { aspectRatio: options.aspectRatio } : {}
820
+ },
821
+ invoke: () => Promise.resolve(image.doGenerate(options)),
822
+ // `generateImage` keeps only an `images` array from each
823
+ // `providerMetadata` namespace, so an `enlitt` namespace would be
824
+ // dropped and, lacking `images`, would break its merge. The image
825
+ // result is therefore returned by identity.
826
+ mapResult: (result) => result,
827
+ facts: (result) => imageUsageFacts(result)
828
+ }),
829
+ // v4 only: whether the model accepts input files and masks. Forwarded
830
+ // by reference when present, like `maxImagesPerCall`.
831
+ ...forwardOptional(model, "supportsFileInputs"),
832
+ ...forwardOptional(model, "supportsMaskInputs")
833
+ };
834
+ return wrapped2;
835
+ }
836
+ const audio = model;
837
+ const wrapped = {
838
+ specificationVersion: model.specificationVersion,
839
+ provider: audio.provider,
840
+ modelId: audio.modelId,
841
+ doGenerate(options) {
842
+ if (isSpeechOptions(options)) {
843
+ return runMediaCall(client, labels, options.providerOptions, options.abortSignal, {
844
+ kind: "speech",
845
+ request: {
846
+ characters: [...options.text].length,
847
+ ...options.voice !== void 0 ? { voice: options.voice } : {},
848
+ ...options.outputFormat !== void 0 ? { outputFormat: options.outputFormat } : {}
849
+ },
850
+ invoke: () => Promise.resolve(audio.doGenerate(options)),
851
+ mapResult: attachEnlittMetadata,
852
+ facts: () => ({})
853
+ });
854
+ }
855
+ if (isTranscriptionOptions(options)) {
856
+ return runMediaCall(client, labels, options.providerOptions, options.abortSignal, {
857
+ kind: "transcription",
858
+ request: { mediaType: options.mediaType },
859
+ invoke: () => Promise.resolve(audio.doGenerate(options)),
860
+ mapResult: attachEnlittMetadata,
861
+ facts: () => ({})
862
+ });
863
+ }
864
+ return Promise.reject(
865
+ new EnlittConfigurationError(
866
+ "A premium audio call needs either a string `text` (speech) or `audio` with a string `mediaType` (transcription)."
867
+ )
868
+ );
869
+ }
870
+ };
871
+ return wrapped;
872
+ }
873
+ function forwardOptional(model, key) {
874
+ return key in model ? { [key]: model[key] } : {};
875
+ }
876
+ function isSpeechOptions(options) {
877
+ return typeof options.text === "string";
878
+ }
879
+ function isTranscriptionOptions(options) {
880
+ const audio = options.audio;
881
+ return (typeof audio === "string" || audio instanceof Uint8Array) && typeof options.mediaType === "string";
882
+ }
883
+ async function runMediaCall(client, labels, providerOptions, signal, spec) {
884
+ const options = readEnlittCallOptions(providerOptions, "premium");
885
+ const price = options.price;
886
+ const request = {
887
+ // Always present for a premium call: `readEnlittCallOptions` resolves it
888
+ // from the declared value or a constant price.
889
+ maxCharge: options.maxCharge,
890
+ provider: labels,
891
+ // One media call is one provider invocation, so a supplied key is the
892
+ // call ID itself (the OpenAI adapter's rule), and otherwise a fresh one.
893
+ callId: assertCallId(options.idempotencyKey ?? generateRandomCallId()),
894
+ ...options.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: options.reportingDeadlineMs } : {},
895
+ ...options.metadata !== void 0 ? { metadata: options.metadata } : {},
896
+ ...signal !== void 0 ? { signal } : {}
897
+ };
898
+ return runPremiumCharge(client, request, async (charge, operation) => {
899
+ const startedAt = /* @__PURE__ */ new Date();
900
+ let result;
901
+ try {
902
+ result = await spec.invoke();
903
+ } catch (thrown) {
904
+ const endedAt2 = /* @__PURE__ */ new Date();
905
+ if (isCancellation(thrown, signal)) {
906
+ charge(
907
+ await evaluatePrice(client, price, buildContext(spec, "canceled", void 0, startedAt, endedAt2, operation))
908
+ );
909
+ operation.describe({
910
+ timing: timingFacts(startedAt, endedAt2),
911
+ delivery: { outputStarted: false, outputCompleted: false },
912
+ errorCategory: "canceled"
913
+ });
914
+ } else {
915
+ operation.describe({
916
+ timing: timingFacts(startedAt, endedAt2),
917
+ delivery: { outputStarted: false, outputCompleted: false },
918
+ errorCategory: "provider"
919
+ });
920
+ }
921
+ throw thrown;
922
+ }
923
+ const endedAt = /* @__PURE__ */ new Date();
924
+ charge(await evaluatePrice(client, price, buildContext(spec, "completed", result, startedAt, endedAt, operation)));
925
+ operation.describe({
926
+ timing: timingFacts(startedAt, endedAt),
927
+ delivery: { outputStarted: true, outputCompleted: true },
928
+ ...spec.facts(result)
929
+ });
930
+ return spec.mapResult(result, operation);
931
+ });
932
+ }
933
+ function buildContext(spec, status, result, startedAt, endedAt, operation) {
934
+ const base = {
935
+ status,
936
+ startedAt,
937
+ endedAt,
938
+ durationMs: endedAt.getTime() - startedAt.getTime(),
939
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
940
+ };
941
+ return {
942
+ ...base,
943
+ kind: spec.kind,
944
+ request: spec.request,
945
+ ...result !== void 0 ? { result } : {}
946
+ };
947
+ }
948
+ function imageUsageFacts(result) {
949
+ const usage = result.usage;
950
+ if (usage === void 0) return {};
951
+ const counts = {
952
+ ...usage.inputTokens !== void 0 ? { inputTokens: usage.inputTokens } : {},
953
+ ...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {}
954
+ };
955
+ return Object.keys(counts).length > 0 ? { usage: counts } : {};
956
+ }
957
+ function attachEnlittMetadata(result, operation) {
958
+ const withMetadata = result;
959
+ return {
960
+ ...withMetadata,
961
+ providerMetadata: {
962
+ ...withMetadata.providerMetadata,
963
+ enlitt: {
964
+ operationId: operation.operationId,
965
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
966
+ }
967
+ }
968
+ };
969
+ }
970
+
971
+ // src/vercel/language-model.ts
972
+ function enlitt(target, options = {}) {
973
+ const client = createInternalClient(options);
974
+ if (target === ENLITT_STANDARD_MODEL) {
975
+ return createStandardLanguageModel(client);
976
+ }
977
+ const model = target;
978
+ if (!isSupportedModel(model)) {
979
+ throw new EnlittConfigurationError(
980
+ 'enlitt() accepts "enlitt-standard" or a Vercel AI SDK v3 or v4 language, image, speech, or transcription model.'
981
+ );
982
+ }
983
+ if (typeof model.doStream === "function" && "supportedUrls" in model) {
984
+ return createPremiumLanguageModel(client, target);
985
+ }
986
+ if ("maxImagesPerCall" in model) {
987
+ return createPremiumMediaModel(client, target, "image");
988
+ }
989
+ return createPremiumMediaModel(
990
+ client,
991
+ target,
992
+ "audio"
993
+ );
994
+ }
995
+ function isSupportedModel(model) {
996
+ return (model.specificationVersion === "v3" || model.specificationVersion === "v4") && typeof model.provider === "string" && typeof model.modelId === "string" && typeof model.doGenerate === "function";
997
+ }
998
+ var KNOWN_ENLITT_OPTION_KEYS = /* @__PURE__ */ new Set([
999
+ "idempotencyKey",
1000
+ "maxCharge",
1001
+ "price",
1002
+ "reportingDeadlineMs",
1003
+ "metadata"
1004
+ ]);
1005
+ function readEnlittCallOptions(providerOptions, mode) {
1006
+ const raw = providerOptions?.enlitt;
1007
+ if (raw === void 0) {
1008
+ if (mode === "premium") {
1009
+ throw new EnlittConfigurationError(
1010
+ "A premium call requires providerOptions.enlitt.maxCharge, or a constant providerOptions.enlitt.price."
1011
+ );
1012
+ }
1013
+ return {};
1014
+ }
1015
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
1016
+ throw new EnlittConfigurationError("providerOptions.enlitt must be an object.");
1017
+ }
1018
+ const input = raw;
1019
+ for (const key of Object.keys(input)) {
1020
+ if (!KNOWN_ENLITT_OPTION_KEYS.has(key)) {
1021
+ throw new EnlittConfigurationError(`providerOptions.enlitt.${key} is not a recognized Enlitt option.`);
1022
+ }
1023
+ }
1024
+ if (mode === "standard") {
1025
+ for (const key of ["maxCharge", "price", "reportingDeadlineMs"]) {
1026
+ if (input[key] !== void 0) {
1027
+ throw new EnlittConfigurationError(
1028
+ `providerOptions.enlitt.${key} is a premium-only option; Enlitt's standard route chooses its own model and charges nothing the business declares.`
1029
+ );
1030
+ }
1031
+ }
1032
+ }
1033
+ const idempotencyKey = input.idempotencyKey !== void 0 ? assertIdempotencyKeyBase(input.idempotencyKey, "providerOptions.enlitt.idempotencyKey") : void 0;
1034
+ const metadata = input.metadata !== void 0 ? assertCallerMetadata(input.metadata, "providerOptions.enlitt.metadata") : void 0;
1035
+ let maxCharge;
1036
+ let price;
1037
+ let reportingDeadlineMs;
1038
+ if (mode === "premium") {
1039
+ ({ maxCharge, price } = readPremiumPricing(input));
1040
+ if (input.reportingDeadlineMs !== void 0) {
1041
+ reportingDeadlineMs = assertReportingDeadlineMs(
1042
+ input.reportingDeadlineMs,
1043
+ "providerOptions.enlitt.reportingDeadlineMs"
1044
+ );
1045
+ }
1046
+ }
1047
+ return {
1048
+ ...idempotencyKey !== void 0 ? { idempotencyKey } : {},
1049
+ ...maxCharge !== void 0 ? { maxCharge } : {},
1050
+ ...price !== void 0 ? { price } : {},
1051
+ ...reportingDeadlineMs !== void 0 ? { reportingDeadlineMs } : {},
1052
+ ...metadata !== void 0 ? { metadata } : {}
1053
+ };
1054
+ }
1055
+ function readPremiumPricing(input) {
1056
+ const rawPrice = input.price;
1057
+ let price;
1058
+ if (rawPrice !== void 0) {
1059
+ price = typeof rawPrice === "function" ? rawPrice : assertNanoUsd(rawPrice, "providerOptions.enlitt.price");
1060
+ }
1061
+ let maxCharge;
1062
+ if (input.maxCharge !== void 0) {
1063
+ maxCharge = assertNanoUsd(input.maxCharge, "providerOptions.enlitt.maxCharge");
1064
+ }
1065
+ if (maxCharge === void 0) {
1066
+ if (typeof price === "string") {
1067
+ maxCharge = price;
1068
+ } else if (typeof price === "function") {
1069
+ throw new EnlittConfigurationError(
1070
+ "providerOptions.enlitt.maxCharge is required when providerOptions.enlitt.price is a function."
1071
+ );
1072
+ } else {
1073
+ throw new EnlittConfigurationError(
1074
+ "A premium call requires providerOptions.enlitt.maxCharge, or a constant providerOptions.enlitt.price."
1075
+ );
1076
+ }
1077
+ } else if (typeof price === "string" && BigInt(price) > BigInt(maxCharge)) {
1078
+ throw new EnlittConfigurationError(
1079
+ "providerOptions.enlitt.price is above providerOptions.enlitt.maxCharge and could never be charged in full."
1080
+ );
1081
+ }
1082
+ return { maxCharge, price };
1083
+ }
1084
+ function resolveCallId(options, params) {
1085
+ const base = options.idempotencyKey ?? generateRandomCallId();
1086
+ return assertCallId(`${base}.${params.prompt.length}`);
1087
+ }
1088
+
1089
+ export { enlitt, perToken };
1090
+ //# sourceMappingURL=chunk-UVZMKGIL.js.map
1091
+ //# sourceMappingURL=chunk-UVZMKGIL.js.map