@compose-market/sdk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +21 -0
  3. package/README.md +158 -35
  4. package/dist/errors.d.ts +145 -0
  5. package/dist/errors.d.ts.map +1 -0
  6. package/dist/errors.js +152 -0
  7. package/dist/errors.js.map +1 -0
  8. package/dist/events.d.ts +75 -0
  9. package/dist/events.d.ts.map +1 -0
  10. package/dist/events.js +68 -0
  11. package/dist/events.js.map +1 -0
  12. package/dist/http.d.ts +98 -0
  13. package/dist/http.d.ts.map +1 -0
  14. package/dist/http.js +350 -0
  15. package/dist/http.js.map +1 -0
  16. package/dist/index.d.ts +206 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +340 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/resources/inference.d.ts +175 -0
  21. package/dist/resources/inference.d.ts.map +1 -0
  22. package/dist/resources/inference.js +740 -0
  23. package/dist/resources/inference.js.map +1 -0
  24. package/dist/resources/instrumentation.d.ts +28 -0
  25. package/dist/resources/instrumentation.d.ts.map +1 -0
  26. package/dist/resources/instrumentation.js +43 -0
  27. package/dist/resources/instrumentation.js.map +1 -0
  28. package/dist/resources/keys.d.ts +54 -0
  29. package/dist/resources/keys.d.ts.map +1 -0
  30. package/dist/resources/keys.js +164 -0
  31. package/dist/resources/keys.js.map +1 -0
  32. package/dist/resources/models.d.ts +26 -0
  33. package/dist/resources/models.d.ts.map +1 -0
  34. package/dist/resources/models.js +52 -0
  35. package/dist/resources/models.js.map +1 -0
  36. package/dist/resources/session-events.d.ts +46 -0
  37. package/dist/resources/session-events.d.ts.map +1 -0
  38. package/dist/resources/session-events.js +199 -0
  39. package/dist/resources/session-events.js.map +1 -0
  40. package/dist/resources/webhooks.d.ts +27 -0
  41. package/dist/resources/webhooks.d.ts.map +1 -0
  42. package/dist/resources/webhooks.js +78 -0
  43. package/dist/resources/webhooks.js.map +1 -0
  44. package/dist/resources/x402.d.ts +37 -0
  45. package/dist/resources/x402.d.ts.map +1 -0
  46. package/dist/resources/x402.js +72 -0
  47. package/dist/resources/x402.js.map +1 -0
  48. package/dist/storage.d.ts +27 -0
  49. package/dist/storage.d.ts.map +1 -0
  50. package/dist/storage.js +46 -0
  51. package/dist/storage.js.map +1 -0
  52. package/dist/streaming/budget.d.ts +22 -0
  53. package/dist/streaming/budget.d.ts.map +1 -0
  54. package/dist/streaming/budget.js +40 -0
  55. package/dist/streaming/budget.js.map +1 -0
  56. package/dist/streaming/receipt.d.ts +25 -0
  57. package/dist/streaming/receipt.d.ts.map +1 -0
  58. package/dist/streaming/receipt.js +92 -0
  59. package/dist/streaming/receipt.js.map +1 -0
  60. package/dist/streaming/sse.d.ts +29 -0
  61. package/dist/streaming/sse.d.ts.map +1 -0
  62. package/dist/streaming/sse.js +125 -0
  63. package/dist/streaming/sse.js.map +1 -0
  64. package/dist/types/index.d.ts +540 -0
  65. package/dist/types/index.d.ts.map +1 -0
  66. package/dist/types/index.js +10 -0
  67. package/dist/types/index.js.map +1 -0
  68. package/dist/version.d.ts +9 -0
  69. package/dist/version.d.ts.map +1 -0
  70. package/dist/version.js +9 -0
  71. package/dist/version.js.map +1 -0
  72. package/package.json +32 -21
  73. package/index.d.ts +0 -244
  74. package/index.js +0 -397
@@ -0,0 +1,740 @@
1
+ import { BadRequestError, ComposeError } from "../errors.js";
2
+ import { parseSSEStream } from "../streaming/sse.js";
3
+ import { parseReceiptEvent } from "../streaming/receipt.js";
4
+ import { instrumentBillableResponse, } from "./instrumentation.js";
5
+ function buildCallHeaders(options, ctxWallet, ctxToken) {
6
+ // When the caller explicitly passes `composeKey: null`, force the raw x402
7
+ // path by suppressing the instance-level token. Any other value (string or
8
+ // undefined) falls back to the instance token.
9
+ const tokenResolved = options && "composeKey" in options
10
+ ? options.composeKey
11
+ : ctxToken;
12
+ return {
13
+ userAddress: options?.userAddress ?? ctxWallet.address ?? undefined,
14
+ chainId: options?.chainId ?? ctxWallet.chainId ?? undefined,
15
+ composeKey: tokenResolved ?? undefined,
16
+ paymentSignature: options?.paymentSignature,
17
+ x402MaxAmountWei: options?.x402MaxAmountWei,
18
+ idempotencyKey: options?.idempotencyKey,
19
+ composeRunId: options?.composeRunId,
20
+ };
21
+ }
22
+ /**
23
+ * Read the response header / body pair produced by a billable call, extract
24
+ * receipt + budget + invalid-reason, emit them on the SDK event bus, and
25
+ * return the public `ComposeCompletion<T>` shape.
26
+ */
27
+ function toComposeCompletion(ctx, response, data) {
28
+ const result = instrumentBillableResponse(ctx, response, data);
29
+ return {
30
+ data: result.data,
31
+ receipt: result.receipt,
32
+ requestId: result.requestId,
33
+ response: result.response,
34
+ budget: result.budget,
35
+ sessionInvalidReason: result.sessionInvalidReason,
36
+ };
37
+ }
38
+ /**
39
+ * Emit budget / receipt / invalid events for a streaming response. The receipt
40
+ * is attached optionally because streaming calls produce it via the in-band
41
+ * `compose.receipt` SSE frame, not necessarily via the header.
42
+ */
43
+ function emitStreamingEvents(ctx, response, receipt, requestId) {
44
+ const walletCtx = ctx.getWalletMaybe();
45
+ // Budget / session-invalid headers are set on the initial SSE response
46
+ // (before the stream body), so extracting them from `response` is fine.
47
+ const { extractSessionBudgetFromResponse } = budgetExtractor;
48
+ const { budget, sessionInvalidReason } = extractSessionBudgetFromResponse(response);
49
+ if (receipt) {
50
+ ctx.events.emit("receipt", {
51
+ userAddress: walletCtx.address,
52
+ chainId: walletCtx.chainId,
53
+ receipt,
54
+ requestId,
55
+ source: "stream",
56
+ });
57
+ }
58
+ if (budget) {
59
+ ctx.events.emit("budget", {
60
+ userAddress: walletCtx.address,
61
+ chainId: walletCtx.chainId,
62
+ snapshot: budget,
63
+ requestId,
64
+ });
65
+ }
66
+ if (sessionInvalidReason) {
67
+ ctx.events.emit("sessionInvalid", {
68
+ userAddress: walletCtx.address,
69
+ chainId: walletCtx.chainId,
70
+ reason: sessionInvalidReason,
71
+ requestId,
72
+ });
73
+ }
74
+ return { budget, sessionInvalidReason };
75
+ }
76
+ // Lazy-loaded to avoid a circular import through instrumentation.ts -> budget.ts
77
+ // (budget.ts is a pure leaf, so we just import it directly).
78
+ import * as budgetExtractor from "../streaming/budget.js";
79
+ /**
80
+ * Async iterable returned by `inference.chat.completions.stream(...)` and
81
+ * `inference.responses.stream(...)`. Exposes `.final()` for consumers that
82
+ * want the reassembled final object + receipt without iterating manually.
83
+ *
84
+ * `for await (const chunk of stream) { ... }` consumes chunks; the generator's
85
+ * return value is captured internally so a subsequent `await stream.final()`
86
+ * resolves to the typed final object even when the caller drove iteration.
87
+ */
88
+ export class ComposeStreamIterator {
89
+ iterator;
90
+ finalResult = null;
91
+ finalSettled = false;
92
+ finalPromise = null;
93
+ constructor(iterator) {
94
+ this.iterator = iterator;
95
+ }
96
+ [Symbol.asyncIterator]() {
97
+ const self = this;
98
+ return {
99
+ next: async () => {
100
+ const r = await self.iterator.next();
101
+ if (r.done) {
102
+ self.finalResult = r.value;
103
+ self.finalSettled = true;
104
+ return { done: true, value: undefined };
105
+ }
106
+ return { done: false, value: r.value };
107
+ },
108
+ return: async () => {
109
+ const r = await self.iterator.return(undefined);
110
+ if (r.done) {
111
+ self.finalResult = r.value;
112
+ self.finalSettled = true;
113
+ }
114
+ return { done: true, value: undefined };
115
+ },
116
+ };
117
+ }
118
+ async final() {
119
+ if (this.finalSettled)
120
+ return this.finalResult;
121
+ if (this.finalPromise)
122
+ return this.finalPromise;
123
+ this.finalPromise = (async () => {
124
+ let last;
125
+ do {
126
+ last = await this.iterator.next();
127
+ } while (!last.done);
128
+ this.finalResult = last.value;
129
+ this.finalSettled = true;
130
+ return last.value;
131
+ })();
132
+ return this.finalPromise;
133
+ }
134
+ }
135
+ // ---------------------------------------------------------------------------
136
+ // Chat completions
137
+ // ---------------------------------------------------------------------------
138
+ class ChatCompletionsNamespace {
139
+ client;
140
+ ctx;
141
+ constructor(client, ctx) {
142
+ this.client = client;
143
+ this.ctx = ctx;
144
+ }
145
+ async create(params, options) {
146
+ if (params.stream === true) {
147
+ throw new BadRequestError({
148
+ message: "Pass stream: true only to chat.completions.stream(). Use create() for non-streaming calls.",
149
+ });
150
+ }
151
+ const { data, response } = await this.client.request({
152
+ method: "POST",
153
+ path: "/v1/chat/completions",
154
+ body: { ...params, stream: false },
155
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
156
+ signal: options?.signal,
157
+ timeoutMs: options?.timeoutMs,
158
+ }).withResponse();
159
+ return toComposeCompletion(this.ctx, response, data);
160
+ }
161
+ stream(params, options) {
162
+ const iterator = streamChatCompletions(this.client, this.ctx, params, options);
163
+ return new ComposeStreamIterator(iterator);
164
+ }
165
+ }
166
+ async function* streamChatCompletions(client, ctx, params, options) {
167
+ const response = await client.request({
168
+ method: "POST",
169
+ path: "/v1/chat/completions",
170
+ body: { ...params, stream: true },
171
+ headers: buildCallHeaders(options, ctx.getWalletMaybe(), ctx.getTokenMaybe()),
172
+ signal: options?.signal,
173
+ timeoutMs: options?.timeoutMs,
174
+ expectStream: true,
175
+ }).asResponse();
176
+ if (!response.body) {
177
+ throw new ComposeError({
178
+ code: "upstream_error",
179
+ message: "Streaming response had no body",
180
+ });
181
+ }
182
+ let receipt = null;
183
+ const aggregator = buildChatCompletionAggregator(params.model);
184
+ let streamError = null;
185
+ try {
186
+ for await (const frame of parseSSEStream(response.body, { signal: options?.signal })) {
187
+ if (frame.event === "compose.receipt") {
188
+ try {
189
+ receipt = parseReceiptEvent(frame.data);
190
+ }
191
+ catch { /* ignore */ }
192
+ continue;
193
+ }
194
+ if (frame.event === "compose.error") {
195
+ try {
196
+ const parsed = JSON.parse(frame.data);
197
+ streamError = new ComposeError({
198
+ code: parsed.code ?? "upstream_error",
199
+ message: parsed.message ?? "Stream error",
200
+ details: parsed.details,
201
+ });
202
+ }
203
+ catch { /* ignore */ }
204
+ continue;
205
+ }
206
+ if (frame.data === "[DONE]") {
207
+ break;
208
+ }
209
+ if (frame.event !== "message") {
210
+ // Unknown Compose-specific frames: surface nothing to the chunk stream.
211
+ continue;
212
+ }
213
+ let parsed;
214
+ try {
215
+ parsed = JSON.parse(frame.data);
216
+ }
217
+ catch {
218
+ continue;
219
+ }
220
+ aggregator.absorb(parsed);
221
+ yield parsed;
222
+ }
223
+ if (streamError)
224
+ throw streamError;
225
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("X-Request-Id");
226
+ const { budget, sessionInvalidReason } = emitStreamingEvents(ctx, response, receipt, requestId);
227
+ return {
228
+ chatCompletion: aggregator.finalize(),
229
+ receipt,
230
+ requestId,
231
+ budget,
232
+ sessionInvalidReason,
233
+ };
234
+ }
235
+ finally {
236
+ try {
237
+ response.body?.cancel();
238
+ }
239
+ catch { /* best-effort */ }
240
+ }
241
+ }
242
+ function buildChatCompletionAggregator(modelHint) {
243
+ let id = "";
244
+ let created = 0;
245
+ let model = modelHint;
246
+ let role = undefined;
247
+ let content = "";
248
+ let reasoningContent = "";
249
+ let finishReason = "stop";
250
+ const toolCalls = new Map();
251
+ let usage;
252
+ return {
253
+ absorb(chunk) {
254
+ id = id || chunk.id;
255
+ created = created || chunk.created;
256
+ model = model || chunk.model;
257
+ if (chunk.usage)
258
+ usage = chunk.usage;
259
+ const choice = chunk.choices?.[0];
260
+ if (!choice)
261
+ return;
262
+ if (choice.finish_reason)
263
+ finishReason = choice.finish_reason;
264
+ const delta = choice.delta;
265
+ if (delta?.role)
266
+ role = delta.role;
267
+ if (typeof delta?.content === "string")
268
+ content += delta.content;
269
+ if (typeof delta?.reasoning_content === "string")
270
+ reasoningContent += delta.reasoning_content;
271
+ if (Array.isArray(delta?.tool_calls)) {
272
+ for (const toolCall of delta.tool_calls) {
273
+ const idx = toolCall.index ?? 0;
274
+ const existing = toolCalls.get(idx) ?? {
275
+ id: toolCall.id ?? `call_${idx}`,
276
+ type: "function",
277
+ function: { name: "", arguments: "" },
278
+ };
279
+ if (toolCall.id)
280
+ existing.id = toolCall.id;
281
+ if (toolCall.function?.name)
282
+ existing.function.name += toolCall.function.name;
283
+ if (toolCall.function?.arguments)
284
+ existing.function.arguments += toolCall.function.arguments;
285
+ toolCalls.set(idx, existing);
286
+ }
287
+ }
288
+ },
289
+ finalize() {
290
+ return {
291
+ id,
292
+ object: "chat.completion",
293
+ created,
294
+ model,
295
+ choices: [
296
+ {
297
+ index: 0,
298
+ message: {
299
+ role: role ?? "assistant",
300
+ content,
301
+ ...(toolCalls.size > 0 ? { tool_calls: Array.from(toolCalls.values()) } : {}),
302
+ ...(reasoningContent.length > 0 ? { reasoning_content: reasoningContent } : {}),
303
+ },
304
+ finish_reason: finishReason,
305
+ },
306
+ ],
307
+ usage: usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
308
+ };
309
+ },
310
+ };
311
+ }
312
+ // ---------------------------------------------------------------------------
313
+ // Responses API
314
+ // ---------------------------------------------------------------------------
315
+ class ResponsesNamespace {
316
+ client;
317
+ ctx;
318
+ constructor(client, ctx) {
319
+ this.client = client;
320
+ this.ctx = ctx;
321
+ }
322
+ async create(params, options) {
323
+ if (params.stream === true) {
324
+ throw new BadRequestError({
325
+ message: "Pass stream: true only to responses.stream(). Use create() for non-streaming calls.",
326
+ });
327
+ }
328
+ const { data, response } = await this.client.request({
329
+ method: "POST",
330
+ path: "/v1/responses",
331
+ body: { ...params, stream: false },
332
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
333
+ signal: options?.signal,
334
+ timeoutMs: options?.timeoutMs,
335
+ }).withResponse();
336
+ return toComposeCompletion(this.ctx, response, data);
337
+ }
338
+ stream(params, options) {
339
+ const iterator = streamResponses(this.client, this.ctx, params, options);
340
+ return new ComposeStreamIterator(iterator);
341
+ }
342
+ async get(responseId, options) {
343
+ return this.client.request({
344
+ method: "GET",
345
+ path: `/v1/responses/${encodeURIComponent(responseId)}`,
346
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
347
+ signal: options?.signal,
348
+ timeoutMs: options?.timeoutMs,
349
+ });
350
+ }
351
+ async inputItems(responseId, options) {
352
+ return this.client.request({
353
+ method: "GET",
354
+ path: `/v1/responses/${encodeURIComponent(responseId)}/input_items`,
355
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
356
+ signal: options?.signal,
357
+ timeoutMs: options?.timeoutMs,
358
+ });
359
+ }
360
+ async cancel(responseId, options) {
361
+ return this.client.request({
362
+ method: "POST",
363
+ path: `/v1/responses/${encodeURIComponent(responseId)}/cancel`,
364
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
365
+ signal: options?.signal,
366
+ timeoutMs: options?.timeoutMs,
367
+ });
368
+ }
369
+ }
370
+ async function* streamResponses(client, ctx, params, options) {
371
+ const response = await client.request({
372
+ method: "POST",
373
+ path: "/v1/responses",
374
+ body: { ...params, stream: true },
375
+ headers: buildCallHeaders(options, ctx.getWalletMaybe(), ctx.getTokenMaybe()),
376
+ signal: options?.signal,
377
+ timeoutMs: options?.timeoutMs,
378
+ expectStream: true,
379
+ }).asResponse();
380
+ if (!response.body) {
381
+ throw new ComposeError({ code: "upstream_error", message: "Streaming response had no body" });
382
+ }
383
+ let receipt = null;
384
+ let lastCompleted = null;
385
+ let streamError = null;
386
+ try {
387
+ for await (const frame of parseSSEStream(response.body, { signal: options?.signal })) {
388
+ if (frame.event === "compose.receipt") {
389
+ try {
390
+ receipt = parseReceiptEvent(frame.data);
391
+ }
392
+ catch { /* ignore */ }
393
+ continue;
394
+ }
395
+ if (frame.event === "compose.error") {
396
+ try {
397
+ const parsed = JSON.parse(frame.data);
398
+ streamError = new ComposeError({
399
+ code: parsed.code ?? "upstream_error",
400
+ message: parsed.message ?? "Stream error",
401
+ });
402
+ }
403
+ catch { /* ignore */ }
404
+ continue;
405
+ }
406
+ if (frame.data === "[DONE]") {
407
+ break;
408
+ }
409
+ if (frame.event !== "message")
410
+ continue;
411
+ let parsed;
412
+ try {
413
+ parsed = JSON.parse(frame.data);
414
+ }
415
+ catch {
416
+ continue;
417
+ }
418
+ if (parsed.type === "response.completed") {
419
+ lastCompleted = parsed;
420
+ }
421
+ yield parsed;
422
+ }
423
+ if (streamError)
424
+ throw streamError;
425
+ const finalResponse = lastCompleted
426
+ ? {
427
+ id: lastCompleted.response_id,
428
+ object: "response",
429
+ created_at: Math.floor(Date.now() / 1000),
430
+ status: "completed",
431
+ model: lastCompleted.model,
432
+ output: [],
433
+ ...(lastCompleted.usage
434
+ ? {
435
+ usage: {
436
+ input_tokens: lastCompleted.usage.input_tokens,
437
+ output_tokens: lastCompleted.usage.output_tokens,
438
+ total_tokens: lastCompleted.usage.total_tokens,
439
+ },
440
+ }
441
+ : {}),
442
+ }
443
+ : null;
444
+ const requestId = response.headers.get("x-request-id") ?? response.headers.get("X-Request-Id");
445
+ const { budget, sessionInvalidReason } = emitStreamingEvents(ctx, response, receipt, requestId);
446
+ return {
447
+ response: finalResponse,
448
+ receipt,
449
+ requestId,
450
+ budget,
451
+ sessionInvalidReason,
452
+ };
453
+ }
454
+ finally {
455
+ try {
456
+ response.body?.cancel();
457
+ }
458
+ catch { /* best-effort */ }
459
+ }
460
+ }
461
+ // ---------------------------------------------------------------------------
462
+ // Embeddings
463
+ // ---------------------------------------------------------------------------
464
+ class EmbeddingsNamespace {
465
+ client;
466
+ ctx;
467
+ constructor(client, ctx) {
468
+ this.client = client;
469
+ this.ctx = ctx;
470
+ }
471
+ async create(params, options) {
472
+ const { data, response } = await this.client.request({
473
+ method: "POST",
474
+ path: "/v1/embeddings",
475
+ body: params,
476
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
477
+ signal: options?.signal,
478
+ timeoutMs: options?.timeoutMs,
479
+ }).withResponse();
480
+ return toComposeCompletion(this.ctx, response, data);
481
+ }
482
+ }
483
+ // ---------------------------------------------------------------------------
484
+ // Images
485
+ // ---------------------------------------------------------------------------
486
+ class ImagesNamespace {
487
+ client;
488
+ ctx;
489
+ constructor(client, ctx) {
490
+ this.client = client;
491
+ this.ctx = ctx;
492
+ }
493
+ async generate(params, options) {
494
+ const { data, response } = await this.client.request({
495
+ method: "POST",
496
+ path: "/v1/images/generations",
497
+ body: params,
498
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
499
+ signal: options?.signal,
500
+ timeoutMs: options?.timeoutMs,
501
+ }).withResponse();
502
+ return toComposeCompletion(this.ctx, response, data);
503
+ }
504
+ async edit(params, options) {
505
+ const { data, response } = await this.client.request({
506
+ method: "POST",
507
+ path: "/v1/images/edits",
508
+ body: params,
509
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
510
+ signal: options?.signal,
511
+ timeoutMs: options?.timeoutMs,
512
+ }).withResponse();
513
+ return toComposeCompletion(this.ctx, response, data);
514
+ }
515
+ }
516
+ // ---------------------------------------------------------------------------
517
+ // Audio
518
+ // ---------------------------------------------------------------------------
519
+ class AudioNamespace {
520
+ client;
521
+ ctx;
522
+ constructor(client, ctx) {
523
+ this.client = client;
524
+ this.ctx = ctx;
525
+ }
526
+ /**
527
+ * Text-to-speech. Returns the raw audio `Response` (stream the body via
528
+ * `response.body` or `await response.arrayBuffer()`), plus any receipt
529
+ * extracted from response headers, plus the live budget snapshot.
530
+ */
531
+ async speech(params, options) {
532
+ const response = await this.client.request({
533
+ method: "POST",
534
+ path: "/v1/audio/speech",
535
+ body: params,
536
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
537
+ signal: options?.signal,
538
+ timeoutMs: options?.timeoutMs,
539
+ expectStream: true,
540
+ }).asResponse();
541
+ // No JSON body to mirror; receipt comes from the header only.
542
+ const result = instrumentBillableResponse(this.ctx, response, undefined);
543
+ return {
544
+ response,
545
+ receipt: result.receipt,
546
+ requestId: result.requestId,
547
+ budget: result.budget,
548
+ sessionInvalidReason: result.sessionInvalidReason,
549
+ };
550
+ }
551
+ /**
552
+ * Speech-to-text. Supports both multipart/form-data (preferred, OpenAI-
553
+ * compatible) when `file` is a `Blob`/`File`/`Uint8Array`, and base64-in-
554
+ * JSON (Compose legacy) when `file` is a string.
555
+ */
556
+ async transcriptions(params, options) {
557
+ const useMultipart = typeof File !== "undefined" && params.file instanceof File
558
+ || typeof Blob !== "undefined" && params.file instanceof Blob
559
+ || (params.file && typeof params.file === "object" && "byteLength" in params.file);
560
+ if (useMultipart) {
561
+ const form = new FormData();
562
+ form.append("model", params.model);
563
+ const { file, filename, model: _model, ...rest } = params;
564
+ void _model;
565
+ const name = filename ?? "audio";
566
+ let blob;
567
+ if (typeof File !== "undefined" && file instanceof File)
568
+ blob = file;
569
+ else if (typeof Blob !== "undefined" && file instanceof Blob)
570
+ blob = file;
571
+ else if (file.byteLength !== undefined) {
572
+ const bytes = file;
573
+ const copy = new Uint8Array(new ArrayBuffer(bytes.byteLength));
574
+ copy.set(bytes);
575
+ blob = new Blob([copy.buffer]);
576
+ }
577
+ else
578
+ throw new BadRequestError({ message: "audio transcriptions: unsupported file type" });
579
+ form.append("file", blob, name);
580
+ for (const [key, value] of Object.entries(rest)) {
581
+ if (value === undefined)
582
+ continue;
583
+ form.append(key, typeof value === "string" ? value : JSON.stringify(value));
584
+ }
585
+ const { data, response } = await this.client.request({
586
+ method: "POST",
587
+ path: "/v1/audio/transcriptions",
588
+ rawBody: form,
589
+ bodyType: "form-data",
590
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
591
+ signal: options?.signal,
592
+ timeoutMs: options?.timeoutMs,
593
+ }).withResponse();
594
+ return toComposeCompletion(this.ctx, response, data);
595
+ }
596
+ const { data, response } = await this.client.request({
597
+ method: "POST",
598
+ path: "/v1/audio/transcriptions",
599
+ body: params,
600
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
601
+ signal: options?.signal,
602
+ timeoutMs: options?.timeoutMs,
603
+ }).withResponse();
604
+ return toComposeCompletion(this.ctx, response, data);
605
+ }
606
+ }
607
+ // ---------------------------------------------------------------------------
608
+ // Videos
609
+ // ---------------------------------------------------------------------------
610
+ class VideosNamespace {
611
+ client;
612
+ ctx;
613
+ constructor(client, ctx) {
614
+ this.client = client;
615
+ this.ctx = ctx;
616
+ }
617
+ async generate(params, options) {
618
+ const { data, response } = await this.client.request({
619
+ method: "POST",
620
+ path: "/v1/videos/generations",
621
+ body: params,
622
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
623
+ signal: options?.signal,
624
+ timeoutMs: options?.timeoutMs,
625
+ }).withResponse();
626
+ return toComposeCompletion(this.ctx, response, data);
627
+ }
628
+ get(videoId, options) {
629
+ return Promise.resolve(this.client.request({
630
+ method: "GET",
631
+ path: `/v1/videos/${encodeURIComponent(videoId)}`,
632
+ headers: buildCallHeaders(options, this.ctx.getWalletMaybe(), this.ctx.getTokenMaybe()),
633
+ signal: options?.signal,
634
+ timeoutMs: options?.timeoutMs,
635
+ }));
636
+ }
637
+ /**
638
+ * Server-driven polling via SSE. Subscribes to `/v1/videos/:id/stream`
639
+ * and yields each status update as it arrives, terminating on the
640
+ * `completed` or `failed` state.
641
+ */
642
+ stream(videoId, opts = {}) {
643
+ const iterator = streamVideoStatus(this.client, this.ctx, videoId, opts);
644
+ return new ComposeStreamIterator(iterator);
645
+ }
646
+ /**
647
+ * Convenience helper: resolves once the video job hits a terminal state,
648
+ * driven by the server-side SSE poller. Aborts after `timeoutMs` elapses.
649
+ */
650
+ async waitUntilDone(videoId, opts = {}) {
651
+ const stream = this.stream(videoId, opts);
652
+ for await (const event of stream) {
653
+ opts.onStatus?.(event);
654
+ }
655
+ const { final } = await stream.final();
656
+ return final;
657
+ }
658
+ }
659
+ async function* streamVideoStatus(client, ctx, videoId, opts) {
660
+ const query = {};
661
+ if (opts.pollIntervalMs !== undefined)
662
+ query.pollIntervalMs = String(opts.pollIntervalMs);
663
+ if (opts.timeoutMs !== undefined)
664
+ query.timeoutMs = String(opts.timeoutMs);
665
+ const response = await client.request({
666
+ method: "GET",
667
+ path: `/v1/videos/${encodeURIComponent(videoId)}/stream`,
668
+ query,
669
+ headers: buildCallHeaders(opts, ctx.getWalletMaybe(), ctx.getTokenMaybe()),
670
+ signal: opts.signal,
671
+ timeoutMs: opts.timeoutMs,
672
+ expectStream: true,
673
+ }).asResponse();
674
+ if (!response.body) {
675
+ throw new ComposeError({ code: "upstream_error", message: "Streaming response had no body" });
676
+ }
677
+ let lastStatus = null;
678
+ try {
679
+ for await (const frame of parseSSEStream(response.body, { signal: opts.signal })) {
680
+ if (frame.data === "[DONE]") {
681
+ yield { type: "done" };
682
+ break;
683
+ }
684
+ if (frame.event === "compose.video.status") {
685
+ try {
686
+ const parsed = JSON.parse(frame.data);
687
+ lastStatus = {
688
+ id: parsed.jobId,
689
+ object: "video.generation",
690
+ status: parsed.status,
691
+ url: parsed.url,
692
+ error: parsed.error,
693
+ progress: parsed.progress,
694
+ };
695
+ yield { type: "compose.video.status", ...parsed };
696
+ }
697
+ catch { /* skip malformed frame */ }
698
+ continue;
699
+ }
700
+ if (frame.event === "compose.error") {
701
+ try {
702
+ const parsed = JSON.parse(frame.data);
703
+ yield { type: "compose.error", code: parsed.code ?? "upstream_error", message: parsed.message ?? "Stream error", details: parsed.details };
704
+ }
705
+ catch { /* skip */ }
706
+ continue;
707
+ }
708
+ }
709
+ return {
710
+ final: lastStatus,
711
+ requestId: response.headers.get("x-request-id") ?? response.headers.get("X-Request-Id"),
712
+ };
713
+ }
714
+ finally {
715
+ try {
716
+ response.body?.cancel();
717
+ }
718
+ catch { /* best-effort */ }
719
+ }
720
+ }
721
+ // ---------------------------------------------------------------------------
722
+ // Top-level inference resource
723
+ // ---------------------------------------------------------------------------
724
+ export class InferenceResource {
725
+ chat;
726
+ responses;
727
+ embeddings;
728
+ images;
729
+ audio;
730
+ videos;
731
+ constructor(client, ctx) {
732
+ this.chat = { completions: new ChatCompletionsNamespace(client, ctx) };
733
+ this.responses = new ResponsesNamespace(client, ctx);
734
+ this.embeddings = new EmbeddingsNamespace(client, ctx);
735
+ this.images = new ImagesNamespace(client, ctx);
736
+ this.audio = new AudioNamespace(client, ctx);
737
+ this.videos = new VideosNamespace(client, ctx);
738
+ }
739
+ }
740
+ //# sourceMappingURL=inference.js.map