@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,623 @@
1
+ 'use strict';
2
+
3
+ var chunk6OWXYBBT_cjs = require('./chunk-6OWXYBBT.cjs');
4
+ var chunkPPOUNWNA_cjs = require('./chunk-PPOUNWNA.cjs');
5
+ var protocol = require('@enlitt/protocol');
6
+
7
+ function createMediaMethods(client, provider) {
8
+ return {
9
+ images: {
10
+ generate: async (body, options) => {
11
+ validateRequestOptions(options);
12
+ assertPremiumModel(body, provider);
13
+ if (typeof body.model !== "string" || body.model.length === 0) {
14
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(
15
+ "images.generate() through Enlitt requires a model name, so the operation names the model it paid for."
16
+ );
17
+ }
18
+ if (body.stream === true) {
19
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Streaming image generation is not supported through Enlitt.");
20
+ }
21
+ const method = requireMethod(provider?.images?.generate, "images.generate");
22
+ const { enlitt: _removed, ...request } = body;
23
+ return runMediaCall(client, body, options, {
24
+ kind: "image",
25
+ request,
26
+ invoke: () => method.call(provider.images, request, options),
27
+ facts: imageUsageFacts
28
+ });
29
+ }
30
+ },
31
+ audio: {
32
+ speech: {
33
+ create: async (body, options) => {
34
+ validateRequestOptions(options);
35
+ assertPremiumModel(body, provider);
36
+ const method = requireMethod(provider?.audio?.speech?.create, "audio.speech.create");
37
+ const { enlitt: _removed, ...request } = body;
38
+ return runMediaCall(client, body, options, {
39
+ kind: "speech",
40
+ request,
41
+ characters: [...request.input].length,
42
+ // The `Response` body is the caller's; the adapter never reads it.
43
+ invoke: () => method.call(provider.audio.speech, request, options),
44
+ facts: () => ({})
45
+ });
46
+ }
47
+ },
48
+ transcriptions: {
49
+ create: async (body, options) => {
50
+ validateRequestOptions(options);
51
+ assertPremiumModel(body, provider);
52
+ if (body.stream === true) {
53
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Streaming transcription is not supported through Enlitt.");
54
+ }
55
+ const method = requireMethod(provider?.audio?.transcriptions?.create, "audio.transcriptions.create");
56
+ const { enlitt: _removed, ...request } = body;
57
+ return runMediaCall(client, body, options, {
58
+ kind: "transcription",
59
+ request,
60
+ invoke: () => method.call(provider.audio.transcriptions, request, options),
61
+ facts: () => ({})
62
+ });
63
+ }
64
+ }
65
+ }
66
+ };
67
+ }
68
+ function assertPremiumModel(body, provider) {
69
+ if (body.model === protocol.ENLITT_STANDARD_MODEL) {
70
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(
71
+ `Enlitt has no standard image or audio model; "${protocol.ENLITT_STANDARD_MODEL}" is a language model only.`
72
+ );
73
+ }
74
+ if (provider === void 0) {
75
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("A premium OpenAI model requires an OpenAI client passed to enlitt().");
76
+ }
77
+ }
78
+ function requireMethod(method, name) {
79
+ if (typeof method !== "function") {
80
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`The OpenAI client passed to enlitt() does not expose ${name}().`);
81
+ }
82
+ return method;
83
+ }
84
+ async function runMediaCall(client, body, options, spec) {
85
+ const call = readCallOptions(body, "premium");
86
+ const price = call.price;
87
+ const signal = options?.signal;
88
+ const request = {
89
+ maxCharge: call.maxCharge,
90
+ provider: { id: "openai", model: String(body.model) },
91
+ callId: call.idempotencyKey,
92
+ ...call.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: call.reportingDeadlineMs } : {},
93
+ ...call.metadata !== void 0 ? { metadata: call.metadata } : {},
94
+ ...signal !== void 0 ? { signal } : {}
95
+ };
96
+ return chunkPPOUNWNA_cjs.runPremiumCharge(client, request, async (charge, operation) => {
97
+ const startedAt = /* @__PURE__ */ new Date();
98
+ let result;
99
+ try {
100
+ result = await spec.invoke();
101
+ } catch (thrown) {
102
+ const endedAt2 = /* @__PURE__ */ new Date();
103
+ const canceled = chunkPPOUNWNA_cjs.isCancellation(thrown, signal);
104
+ if (canceled) {
105
+ charge(await evaluatePrice(client, price, buildContext(spec, "canceled", void 0, startedAt, endedAt2, operation)));
106
+ }
107
+ operation.describe({
108
+ timing: { startedAt: startedAt.toISOString(), endedAt: endedAt2.toISOString() },
109
+ delivery: { outputStarted: false, outputCompleted: false },
110
+ errorCategory: canceled ? "canceled" : "provider"
111
+ });
112
+ throw thrown;
113
+ }
114
+ const endedAt = /* @__PURE__ */ new Date();
115
+ charge(await evaluatePrice(client, price, buildContext(spec, "completed", result, startedAt, endedAt, operation)));
116
+ operation.describe({
117
+ timing: { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() },
118
+ delivery: { outputStarted: true, outputCompleted: true },
119
+ ...spec.facts(result)
120
+ });
121
+ return result;
122
+ });
123
+ }
124
+ function buildContext(spec, status, result, startedAt, endedAt, operation) {
125
+ const base = {
126
+ status,
127
+ startedAt,
128
+ endedAt,
129
+ durationMs: endedAt.getTime() - startedAt.getTime(),
130
+ effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd
131
+ };
132
+ if (spec.kind === "speech") {
133
+ return { ...base, kind: "speech", request: spec.request, characters: spec.characters };
134
+ }
135
+ return {
136
+ ...base,
137
+ kind: spec.kind,
138
+ request: spec.request,
139
+ ...result !== void 0 ? { response: result } : {}
140
+ };
141
+ }
142
+ function imageUsageFacts(result) {
143
+ const usage = result?.usage;
144
+ if (usage === void 0) return {};
145
+ return { usage: { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } };
146
+ }
147
+
148
+ // src/openai/client.ts
149
+ var RESPONSES_PATH = "/v1/responses";
150
+ var STANDARD_FIELDS = /* @__PURE__ */ new Set(["model", "input", "instructions", "max_output_tokens", "tools", "tool_choice", "stream", "metadata", "enlitt"]);
151
+ function enlitt(first = {}, second = {}) {
152
+ const looksLikeClient = hasResponsesProperty(first);
153
+ let provider;
154
+ let options;
155
+ if (looksLikeClient) {
156
+ if (!isOpenAIClient(first)) {
157
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("The OpenAI client must expose responses.create().");
158
+ }
159
+ provider = first;
160
+ options = second;
161
+ } else {
162
+ options = first;
163
+ }
164
+ const client = chunkPPOUNWNA_cjs.createInternalClient(options);
165
+ return {
166
+ // Premium-only image and audio methods (owner decision 2026-11-15).
167
+ ...createMediaMethods(client, provider),
168
+ responses: {
169
+ create: (body, requestOptions) => {
170
+ validateRequestOptions(requestOptions);
171
+ return body.model === protocol.ENLITT_STANDARD_MODEL ? createStandardResponse(client, body, requestOptions) : createPremiumResponse(client, provider, body, requestOptions);
172
+ }
173
+ }
174
+ };
175
+ }
176
+ function hasResponsesProperty(value) {
177
+ return typeof value === "object" && value !== null && "responses" in value;
178
+ }
179
+ function isOpenAIClient(value) {
180
+ if (!hasResponsesProperty(value)) return false;
181
+ const responses = value.responses;
182
+ return typeof responses === "object" && responses !== null && typeof responses.create === "function";
183
+ }
184
+ function validateRequestOptions(options) {
185
+ if (options === void 0) return;
186
+ for (const key of Object.keys(options)) {
187
+ if (key !== "signal" && key !== "timeout") {
188
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`OpenAI request option "${key}" is not supported by the Enlitt adapter.`);
189
+ }
190
+ }
191
+ if (options.timeout !== void 0 && (!Number.isSafeInteger(options.timeout) || options.timeout <= 0)) {
192
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("OpenAI request option timeout must be a positive safe integer.");
193
+ }
194
+ }
195
+ function readCallOptions(body, mode) {
196
+ const input = body.enlitt ?? {};
197
+ const known = /* @__PURE__ */ new Set(["idempotencyKey", "maxCharge", "price", "reportingDeadlineMs", "metadata"]);
198
+ for (const key of Object.keys(input)) {
199
+ if (!known.has(key)) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`enlitt.${key} is not a recognized Enlitt option.`);
200
+ }
201
+ if (mode === "standard" && (input.maxCharge !== void 0 || input.price !== void 0 || input.reportingDeadlineMs !== void 0)) {
202
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("maxCharge, price, and reportingDeadlineMs are premium-only options.");
203
+ }
204
+ const idempotencyKey = input.idempotencyKey === void 0 ? chunkPPOUNWNA_cjs.generateRandomCallId() : chunkPPOUNWNA_cjs.assertCallId(input.idempotencyKey);
205
+ const metadata = input.metadata === void 0 ? void 0 : chunkPPOUNWNA_cjs.assertCallerMetadata(input.metadata, "enlitt.metadata");
206
+ if (mode === "standard") return { idempotencyKey, metadata };
207
+ const price = input.price;
208
+ if (price !== void 0 && typeof price !== "string" && typeof price !== "function") {
209
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("enlitt.price must be a canonical NANOUSD string or a function.");
210
+ }
211
+ const constantPrice = typeof price === "string" ? chunkPPOUNWNA_cjs.assertNanoUsd(price, "enlitt.price") : price;
212
+ const maxCharge = input.maxCharge === void 0 ? typeof constantPrice === "string" ? constantPrice : void 0 : chunkPPOUNWNA_cjs.assertNanoUsd(input.maxCharge, "enlitt.maxCharge");
213
+ if (maxCharge === void 0) {
214
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("A premium call requires enlitt.maxCharge, or a constant enlitt.price.");
215
+ }
216
+ if (typeof constantPrice === "string" && BigInt(constantPrice) > BigInt(maxCharge)) {
217
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("enlitt.price cannot exceed enlitt.maxCharge.");
218
+ }
219
+ const reportingDeadlineMs = input.reportingDeadlineMs === void 0 ? void 0 : chunkPPOUNWNA_cjs.assertReportingDeadlineMs(input.reportingDeadlineMs, "enlitt.reportingDeadlineMs");
220
+ return { idempotencyKey, metadata, maxCharge, price: constantPrice, reportingDeadlineMs };
221
+ }
222
+ function timedSignal(options) {
223
+ if (options?.timeout === void 0) return { ...options?.signal !== void 0 ? { signal: options.signal } : {}, cleanup: () => void 0 };
224
+ const controller = new AbortController();
225
+ const abort = () => controller.abort(options.signal?.reason);
226
+ options.signal?.addEventListener("abort", abort, { once: true });
227
+ const timer = setTimeout(() => controller.abort(new DOMException("The request timed out.", "AbortError")), options.timeout);
228
+ return {
229
+ signal: controller.signal,
230
+ cleanup() {
231
+ clearTimeout(timer);
232
+ options.signal?.removeEventListener("abort", abort);
233
+ }
234
+ };
235
+ }
236
+ async function createStandardResponse(client, body, options) {
237
+ const call = readCallOptions(body, "standard");
238
+ const request = buildStandardRequest(body, call.metadata);
239
+ const timed = timedSignal(options);
240
+ try {
241
+ const response = await chunkPPOUNWNA_cjs.requestEnlitt(client, {
242
+ path: RESPONSES_PATH,
243
+ body: request,
244
+ callId: call.idempotencyKey,
245
+ accept: body.stream === true ? "text/event-stream" : "application/json",
246
+ ...timed.signal !== void 0 ? { signal: timed.signal } : {}
247
+ });
248
+ if (body.stream === true) {
249
+ if (response.body === null) throw new chunkPPOUNWNA_cjs.EnlittError("malformed_response", "Enlitt's streaming response carried no body.");
250
+ return mapStandardStream(response.body, () => timed.cleanup());
251
+ }
252
+ const parsed = protocol.validateOpenAIResponse(await chunkPPOUNWNA_cjs.readEnlittJson(response), { mode: "tolerant" });
253
+ if (!parsed.ok) throw malformed(parsed.error.message, parsed.error.param);
254
+ return mapStandardResponse(parsed.value);
255
+ } finally {
256
+ if (body.stream !== true) timed.cleanup();
257
+ }
258
+ }
259
+ function buildStandardRequest(body, metadata) {
260
+ for (const key of Object.keys(body)) {
261
+ if (!STANDARD_FIELDS.has(key)) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`OpenAI field "${key}" is not supported by Enlitt's standard route.`);
262
+ }
263
+ const messages = [];
264
+ if (body.instructions !== void 0 && body.instructions !== null) {
265
+ if (typeof body.instructions !== "string") throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Standard instructions must be a string.");
266
+ messages.push({ role: "system", content: body.instructions });
267
+ }
268
+ messages.push(...mapInput(body.input));
269
+ const draft = { model: protocol.ENLITT_STANDARD_MODEL, messages };
270
+ if (body.max_output_tokens !== void 0 && body.max_output_tokens !== null) draft.max_output_tokens = body.max_output_tokens;
271
+ if (body.stream === true) draft.stream = true;
272
+ if (metadata !== void 0) draft.metadata = metadata;
273
+ if (body.metadata !== void 0 && body.metadata !== null) {
274
+ if (metadata !== void 0) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Supply metadata under enlitt.metadata, not both metadata locations.");
275
+ draft.metadata = chunkPPOUNWNA_cjs.assertCallerMetadata(body.metadata, "metadata");
276
+ }
277
+ if (body.tool_choice !== void 0 && body.tool_choice !== "auto" && body.tool_choice !== "none") {
278
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Standard tool_choice supports only auto or none.");
279
+ }
280
+ if (body.tools !== void 0 && body.tool_choice !== "none") {
281
+ draft.tools = body.tools.map((tool, index) => {
282
+ const value = tool;
283
+ if (value.type !== "function") throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`tools[${index}] must be a function tool.`);
284
+ if (value.strict !== void 0) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`tools[${index}].strict is not supported.`);
285
+ return { name: value.name, ...value.description !== void 0 ? { description: value.description } : {}, input_schema: value.parameters };
286
+ });
287
+ }
288
+ const validated = protocol.validateEnlittStandardRequest(draft);
289
+ if (!validated.ok) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`${validated.error.message} (${validated.error.param})`);
290
+ return validated.value;
291
+ }
292
+ function mapInput(input) {
293
+ if (typeof input === "string") return [{ role: "user", content: [{ type: "text", text: input }] }];
294
+ if (!Array.isArray(input)) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Standard input must be a string or an array of supported input items.");
295
+ return input.map((item, index) => {
296
+ if (typeof item !== "object" || item === null) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}] is not supported.`);
297
+ const value = item;
298
+ if (value.type === "function_call") {
299
+ return { role: "assistant", tool_calls: [{ id: String(value.call_id), name: String(value.name), arguments: String(value.arguments) }] };
300
+ }
301
+ if (value.type === "function_call_output") {
302
+ if (typeof value.output !== "string") throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].output must be a string.`);
303
+ return { role: "tool", tool_call_id: String(value.call_id), content: value.output };
304
+ }
305
+ const role = value.role;
306
+ if (role !== "user" && role !== "system" && role !== "developer" && role !== "assistant") {
307
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].role is not supported.`);
308
+ }
309
+ const content = value.content;
310
+ if (role === "system" || role === "developer") {
311
+ if (typeof content !== "string") throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].content must be a string.`);
312
+ return { role: "system", content };
313
+ }
314
+ if (role === "assistant") {
315
+ if (typeof content !== "string") throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].content must be a string.`);
316
+ return { role: "assistant", content };
317
+ }
318
+ const parts = typeof content === "string" ? [{ type: "input_text", text: content }] : content;
319
+ if (!Array.isArray(parts)) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].content is not supported.`);
320
+ return {
321
+ role: "user",
322
+ content: parts.map((part, partIndex) => {
323
+ const p = part;
324
+ if (p.type === "input_text" && typeof p.text === "string") return { type: "text", text: p.text };
325
+ if (p.type === "input_image" && typeof p.image_url === "string") {
326
+ const match = /^data:(image\/(?:png|jpeg));base64,(.+)$/.exec(p.image_url);
327
+ return match ? { type: "image", source: { type: "base64", media_type: match[1], data: match[2] } } : { type: "image", source: { type: "url", url: p.image_url } };
328
+ }
329
+ throw new chunkPPOUNWNA_cjs.EnlittConfigurationError(`input[${index}].content[${partIndex}] is not supported.`);
330
+ })
331
+ };
332
+ });
333
+ }
334
+ function mapStandardResponse(value) {
335
+ const known = value.output.filter((item) => !("unknown" in item));
336
+ const output = known.map((item) => item.type === "message" ? { ...item, content: item.content.filter((part) => !("unknown" in part)).map((part) => ({ ...part, annotations: [] })) } : item);
337
+ return {
338
+ id: value.id,
339
+ access_programs: null,
340
+ created_at: value.created_at,
341
+ ...value.completed_at !== void 0 ? { completed_at: value.completed_at } : {},
342
+ output_text: value.output_text ?? output.flatMap((item) => item.type === "message" ? item.content.flatMap((part) => "text" in part ? [part.text] : []) : []).join(""),
343
+ error: value.error,
344
+ incomplete_details: value.incomplete_details,
345
+ instructions: null,
346
+ metadata: value.metadata,
347
+ model: protocol.ENLITT_STANDARD_MODEL,
348
+ object: "response",
349
+ output,
350
+ parallel_tool_calls: false,
351
+ temperature: null,
352
+ tool_choice: "auto",
353
+ tools: [],
354
+ top_p: null,
355
+ status: value.status === "other" ? "failed" : value.status,
356
+ usage: value.usage
357
+ };
358
+ }
359
+ async function* mapStandardStream(stream, cleanup) {
360
+ let previous;
361
+ let previousJson;
362
+ let sawTerminal = false;
363
+ try {
364
+ for await (const framed of chunk6OWXYBBT_cjs.createSseEventStream(stream)) {
365
+ if (sawTerminal) throw malformed("a stream event followed the terminal event", "body");
366
+ let json;
367
+ try {
368
+ json = JSON.parse(framed.data);
369
+ } catch {
370
+ throw malformed("stream event was not valid JSON", "body");
371
+ }
372
+ const parsed = protocol.validateResponseStreamEvent(json, { mode: "tolerant" });
373
+ if (!parsed.ok) throw malformed(parsed.error.message, parsed.error.param);
374
+ const event = parsed.value;
375
+ const eventJson = JSON.stringify(event);
376
+ if (previous === void 0) {
377
+ if (event.type !== "response.created") {
378
+ throw malformed('the first stream event was not "response.created"', "body");
379
+ }
380
+ } else if (event.sequence_number === previous.sequence_number) {
381
+ if (eventJson === previousJson) continue;
382
+ throw malformed("two stream events reused a sequence number with different content", "body");
383
+ } else if (event.sequence_number !== previous.sequence_number + 1) {
384
+ throw malformed("stream event sequence numbers were not contiguous", "body");
385
+ }
386
+ previous = event;
387
+ previousJson = eventJson;
388
+ if ("unknown" in event) continue;
389
+ const mapped = mapStandardEvent(event);
390
+ if (mapped !== void 0) yield mapped;
391
+ sawTerminal = event.type === "response.completed" || event.type === "response.incomplete" || event.type === "response.failed";
392
+ }
393
+ if (!sawTerminal) throw malformed("the stream ended without a terminal event", "body");
394
+ } finally {
395
+ cleanup();
396
+ }
397
+ }
398
+ function mapStandardEvent(event) {
399
+ if ("response" in event) return { ...event, response: mapStandardResponse(event.response) };
400
+ if ("item" in event) {
401
+ if ("unknown" in event.item) return void 0;
402
+ const item = event.item.type === "message" ? { ...event.item, content: event.item.content.filter((part) => !("unknown" in part)).map((part) => ({ ...part, annotations: [] })) } : event.item;
403
+ return { ...event, item };
404
+ }
405
+ if ("part" in event) {
406
+ if ("unknown" in event.part) return void 0;
407
+ return { ...event, part: { ...event.part, annotations: [] } };
408
+ }
409
+ return event;
410
+ }
411
+ function malformed(message, param) {
412
+ return new chunkPPOUNWNA_cjs.EnlittError("malformed_response", `Enlitt's response could not be validated: ${message} (${param}).`);
413
+ }
414
+ async function createPremiumResponse(client, provider, body, options) {
415
+ if (provider === void 0) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("A premium OpenAI model requires an OpenAI client passed to enlitt().");
416
+ if (typeof body.model !== "string" || body.model.length === 0) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("A premium OpenAI call requires a model name.");
417
+ if (body.background === true) throw new chunkPPOUNWNA_cjs.EnlittConfigurationError("Background OpenAI responses are not supported.");
418
+ const call = readCallOptions(body, "premium");
419
+ const { enlitt: _removed, ...providerBody } = body;
420
+ const request = {
421
+ maxCharge: call.maxCharge,
422
+ provider: { id: "openai", model: body.model },
423
+ callId: call.idempotencyKey,
424
+ ...call.reportingDeadlineMs !== void 0 ? { reportingDeadlineMs: call.reportingDeadlineMs } : {},
425
+ ...call.metadata !== void 0 ? { metadata: call.metadata } : {},
426
+ ...options?.signal !== void 0 ? { signal: options.signal } : {}
427
+ };
428
+ return body.stream === true ? wrapPremiumStream(client, provider, request, call.price, providerBody, options) : wrapPremiumResponse(client, provider, request, call.price, providerBody, options);
429
+ }
430
+ var TerminalResponse = class extends Error {
431
+ constructor(result, canceled) {
432
+ super();
433
+ this.result = result;
434
+ this.name = canceled ? "AbortError" : "TerminalResponse";
435
+ }
436
+ result;
437
+ };
438
+ async function wrapPremiumResponse(client, provider, request, price, body, options) {
439
+ try {
440
+ return await chunkPPOUNWNA_cjs.runPremiumCharge(client, request, async (charge, operation) => {
441
+ const startedAt = /* @__PURE__ */ new Date();
442
+ let response;
443
+ try {
444
+ response = await provider.responses.create(body, options);
445
+ } catch (error) {
446
+ if (chunkPPOUNWNA_cjs.isCancellation(error, request.signal)) {
447
+ const endedAt2 = /* @__PURE__ */ new Date();
448
+ charge(await evaluatePrice(
449
+ client,
450
+ price,
451
+ contextForEvents(
452
+ void 0,
453
+ void 0,
454
+ startedAt,
455
+ endedAt2,
456
+ operation,
457
+ void 0,
458
+ "canceled"
459
+ )
460
+ ));
461
+ describe(operation, startedAt, endedAt2, void 0, "canceled");
462
+ }
463
+ throw error;
464
+ }
465
+ const endedAt = /* @__PURE__ */ new Date();
466
+ const canceled = response.status === "cancelled";
467
+ if (response.status !== "failed") charge(await evaluatePrice(client, price, contextForResponse(response, startedAt, endedAt, operation, canceled)));
468
+ describe(operation, startedAt, endedAt, response, response.status === "failed" ? "provider" : canceled ? "canceled" : void 0);
469
+ if (response.status === "failed" || canceled) throw new TerminalResponse(response, canceled);
470
+ return response;
471
+ });
472
+ } catch (thrown) {
473
+ if (thrown instanceof TerminalResponse) return thrown.result;
474
+ throw thrown;
475
+ }
476
+ }
477
+ async function wrapPremiumStream(client, provider, request, price, body, options) {
478
+ let expose;
479
+ let rejectExpose;
480
+ const exposed = new Promise((resolve, reject) => {
481
+ expose = resolve;
482
+ rejectExpose = reject;
483
+ });
484
+ let wasExposed = false;
485
+ void chunkPPOUNWNA_cjs.runPremiumCharge(client, request, async (charge, operation) => {
486
+ const startedAt = /* @__PURE__ */ new Date();
487
+ let source;
488
+ try {
489
+ source = await provider.responses.create(body, options);
490
+ } catch (error) {
491
+ if (chunkPPOUNWNA_cjs.isCancellation(error, request.signal)) {
492
+ const endedAt = /* @__PURE__ */ new Date();
493
+ charge(await evaluatePrice(
494
+ client,
495
+ price,
496
+ contextForEvents(
497
+ typeof price === "function" ? [] : void 0,
498
+ void 0,
499
+ startedAt,
500
+ endedAt,
501
+ operation,
502
+ void 0,
503
+ "canceled"
504
+ )
505
+ ));
506
+ describe(operation, startedAt, endedAt, void 0, "canceled");
507
+ }
508
+ rejectExpose(error);
509
+ throw error;
510
+ }
511
+ let settle;
512
+ let fail;
513
+ const terminal = new Promise((resolve, reject) => {
514
+ settle = resolve;
515
+ fail = reject;
516
+ });
517
+ wasExposed = true;
518
+ expose(streamWithSettlement(source, price, client, charge, operation, startedAt, settle, fail, request.signal));
519
+ return terminal;
520
+ }).catch((error) => {
521
+ if (!wasExposed) rejectExpose(error);
522
+ });
523
+ return exposed;
524
+ }
525
+ async function* streamWithSettlement(source, price, client, charge, operation, startedAt, settle, fail, signal) {
526
+ const events = typeof price === "function" ? [] : void 0;
527
+ let terminal = false;
528
+ let firstTokenAt;
529
+ try {
530
+ for await (const event of source) {
531
+ events?.push(event);
532
+ if (firstTokenAt === void 0 && (event.type === "response.output_text.delta" || event.type === "response.function_call_arguments.delta")) firstTokenAt = /* @__PURE__ */ new Date();
533
+ yield event;
534
+ if (event.type === "response.completed" || event.type === "response.incomplete") {
535
+ terminal = true;
536
+ const endedAt = /* @__PURE__ */ new Date();
537
+ charge(await evaluatePrice(client, price, contextForEvents(events, event.response.usage, startedAt, endedAt, operation, firstTokenAt, "completed")));
538
+ describe(operation, startedAt, endedAt, event.response);
539
+ settle();
540
+ return;
541
+ }
542
+ if (event.type === "response.failed") {
543
+ terminal = true;
544
+ describe(operation, startedAt, /* @__PURE__ */ new Date(), event.response, "provider");
545
+ fail(new Error("OpenAI response failed"));
546
+ return;
547
+ }
548
+ }
549
+ terminal = true;
550
+ fail(new Error("OpenAI stream ended without a terminal event"));
551
+ } catch (error) {
552
+ if (!terminal) {
553
+ terminal = true;
554
+ const endedAt = /* @__PURE__ */ new Date();
555
+ if (chunkPPOUNWNA_cjs.isCancellation(error, signal)) {
556
+ charge(await evaluatePrice(
557
+ client,
558
+ price,
559
+ contextForEvents(events, void 0, startedAt, endedAt, operation, firstTokenAt, "canceled")
560
+ ));
561
+ describe(operation, startedAt, endedAt, void 0, "canceled");
562
+ } else {
563
+ describe(operation, startedAt, endedAt, void 0, "provider");
564
+ }
565
+ fail(error);
566
+ }
567
+ throw error;
568
+ } finally {
569
+ if (!terminal) {
570
+ const endedAt = /* @__PURE__ */ new Date();
571
+ charge(await evaluatePrice(client, price, contextForEvents(events, void 0, startedAt, endedAt, operation, firstTokenAt, "canceled")));
572
+ describe(operation, startedAt, endedAt, void 0, "canceled");
573
+ fail(new DOMException("OpenAI stream canceled", "AbortError"));
574
+ }
575
+ }
576
+ }
577
+ function contextForResponse(response, startedAt, endedAt, operation, canceled) {
578
+ return { status: canceled ? "canceled" : "completed", response, ...response.usage !== void 0 ? { usage: response.usage } : {}, startedAt, endedAt, durationMs: endedAt.getTime() - startedAt.getTime(), effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd };
579
+ }
580
+ function contextForEvents(events, usage, startedAt, endedAt, operation, firstTokenAt, status) {
581
+ return { status, ...events !== void 0 ? { events } : {}, ...usage !== void 0 ? { usage } : {}, startedAt, endedAt, durationMs: endedAt.getTime() - startedAt.getTime(), ...firstTokenAt !== void 0 ? { timeToFirstTokenMs: firstTokenAt.getTime() - startedAt.getTime() } : {}, effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd };
582
+ }
583
+ async function evaluatePrice(client, price, context) {
584
+ if (price === void 0) return "0";
585
+ if (typeof price === "string") return price;
586
+ try {
587
+ return chunkPPOUNWNA_cjs.assertNanoUsd(await price(context), "price() result");
588
+ } catch (error) {
589
+ client.onTerminalReportError?.(error instanceof chunkPPOUNWNA_cjs.EnlittError ? error : new chunkPPOUNWNA_cjs.EnlittConfigurationError(`The price function failed, so the call was charged "0": ${error instanceof Error ? error.message : String(error)}`));
590
+ return "0";
591
+ }
592
+ }
593
+ function describe(operation, startedAt, endedAt, response, errorCategory) {
594
+ const usage = response?.usage;
595
+ operation.describe({
596
+ timing: { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() },
597
+ delivery: { outputStarted: response !== void 0, outputCompleted: response !== void 0 && response.status !== "failed" },
598
+ ...response?.id !== void 0 ? { providerResponseId: response.id } : {},
599
+ ...usage !== void 0 ? {
600
+ usage: {
601
+ inputTokens: usage.input_tokens,
602
+ outputTokens: usage.output_tokens,
603
+ ...usage.input_tokens_details?.cached_tokens !== void 0 ? { cachedInputTokens: usage.input_tokens_details.cached_tokens } : {},
604
+ ...usage.output_tokens_details?.reasoning_tokens !== void 0 ? { reasoningTokens: usage.output_tokens_details.reasoning_tokens } : {}
605
+ }
606
+ } : {},
607
+ ...errorCategory !== void 0 ? { errorCategory } : {}
608
+ });
609
+ }
610
+ function perToken(rates) {
611
+ const input = BigInt(chunkPPOUNWNA_cjs.assertNanoUsd(rates.input, "perToken input rate"));
612
+ const output = BigInt(chunkPPOUNWNA_cjs.assertNanoUsd(rates.output, "perToken output rate"));
613
+ return (context) => (input * BigInt(context.usage?.input_tokens ?? 0) + output * BigInt(context.usage?.output_tokens ?? 0)).toString();
614
+ }
615
+
616
+ Object.defineProperty(exports, "ENLITT_STANDARD_MODEL", {
617
+ enumerable: true,
618
+ get: function () { return protocol.ENLITT_STANDARD_MODEL; }
619
+ });
620
+ exports.enlitt = enlitt;
621
+ exports.perToken = perToken;
622
+ //# sourceMappingURL=openai.cjs.map
623
+ //# sourceMappingURL=openai.cjs.map