@runinfra/sdk 0.1.3 → 0.2.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.
- package/CHANGELOG.md +80 -54
- package/README.md +94 -72
- package/dist/index.d.ts +90 -27
- package/dist/index.js +342 -80
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,11 +1,86 @@
|
|
|
1
1
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
-
export const RUNINFRA_SDK_VERSION = "0.
|
|
2
|
+
export const RUNINFRA_SDK_VERSION = "0.2.0";
|
|
3
3
|
const MAX_AUTOMATIC_RETRY_AFTER_MS = 60_000;
|
|
4
|
+
const CHAT_COMPLETION_REQUEST_KEYS = new Set([
|
|
5
|
+
"model",
|
|
6
|
+
"messages",
|
|
7
|
+
"stream",
|
|
8
|
+
"temperature",
|
|
9
|
+
"top_p",
|
|
10
|
+
"max_tokens",
|
|
11
|
+
"max_completion_tokens",
|
|
12
|
+
"stop",
|
|
13
|
+
"presence_penalty",
|
|
14
|
+
"frequency_penalty",
|
|
15
|
+
"user",
|
|
16
|
+
"metadata",
|
|
17
|
+
"stream_options",
|
|
18
|
+
"tools",
|
|
19
|
+
"tool_choice",
|
|
20
|
+
"response_format",
|
|
21
|
+
"seed",
|
|
22
|
+
"logprobs",
|
|
23
|
+
"top_logprobs",
|
|
24
|
+
]);
|
|
25
|
+
const RESPONSES_CREATE_REQUEST_KEYS = new Set([
|
|
26
|
+
"model",
|
|
27
|
+
"input",
|
|
28
|
+
"instructions",
|
|
29
|
+
"max_output_tokens",
|
|
30
|
+
"stream",
|
|
31
|
+
"temperature",
|
|
32
|
+
"top_p",
|
|
33
|
+
"tools",
|
|
34
|
+
"tool_choice",
|
|
35
|
+
"response_format",
|
|
36
|
+
]);
|
|
37
|
+
const EMBEDDING_REQUEST_KEYS = new Set([
|
|
38
|
+
"model",
|
|
39
|
+
"input",
|
|
40
|
+
"encoding_format",
|
|
41
|
+
"dimensions",
|
|
42
|
+
"user",
|
|
43
|
+
]);
|
|
44
|
+
const SPEECH_REQUEST_KEYS = new Set([
|
|
45
|
+
"model",
|
|
46
|
+
"input",
|
|
47
|
+
"voice",
|
|
48
|
+
"ref_audio",
|
|
49
|
+
"ref_text",
|
|
50
|
+
"task_type",
|
|
51
|
+
"response_format",
|
|
52
|
+
"speed",
|
|
53
|
+
]);
|
|
54
|
+
const TRANSCRIPTION_REQUEST_KEYS = new Set([
|
|
55
|
+
"model",
|
|
56
|
+
"file",
|
|
57
|
+
"filename",
|
|
58
|
+
"language",
|
|
59
|
+
"prompt",
|
|
60
|
+
"response_format",
|
|
61
|
+
"temperature",
|
|
62
|
+
]);
|
|
63
|
+
const IMAGE_GENERATE_REQUEST_KEYS = new Set([
|
|
64
|
+
"model",
|
|
65
|
+
"prompt",
|
|
66
|
+
"n",
|
|
67
|
+
"size",
|
|
68
|
+
"response_format",
|
|
69
|
+
"quality",
|
|
70
|
+
"style",
|
|
71
|
+
"user",
|
|
72
|
+
]);
|
|
73
|
+
const VOICE_PIPELINE_REQUEST_KEYS = new Set([
|
|
74
|
+
"audio",
|
|
75
|
+
"mimeType",
|
|
76
|
+
]);
|
|
4
77
|
export class RunInfraError extends Error {
|
|
5
78
|
status;
|
|
6
79
|
type;
|
|
7
80
|
requestId;
|
|
8
81
|
retryAfterMs;
|
|
82
|
+
code;
|
|
83
|
+
param;
|
|
9
84
|
constructor(message, input) {
|
|
10
85
|
super(message);
|
|
11
86
|
this.name = "RunInfraError";
|
|
@@ -13,41 +88,57 @@ export class RunInfraError extends Error {
|
|
|
13
88
|
this.type = input.type;
|
|
14
89
|
this.requestId = input.requestId;
|
|
15
90
|
this.retryAfterMs = input.retryAfterMs;
|
|
91
|
+
this.code = input.code;
|
|
92
|
+
this.param = input.param;
|
|
16
93
|
}
|
|
17
94
|
}
|
|
18
95
|
export class AuthenticationError extends RunInfraError {
|
|
19
|
-
constructor(message, status, requestId) {
|
|
20
|
-
super(message, { status, type: "auth_error", requestId });
|
|
96
|
+
constructor(message, status, requestId, code, param) {
|
|
97
|
+
super(message, { status, type: "auth_error", requestId, code, param });
|
|
21
98
|
this.name = "AuthenticationError";
|
|
22
99
|
}
|
|
23
100
|
}
|
|
24
101
|
export class PermissionDeniedError extends RunInfraError {
|
|
25
|
-
|
|
26
|
-
|
|
102
|
+
// `type` defaults to "permission_denied" but the gateway can supply a more
|
|
103
|
+
// specific discriminator on the 403 body (e.g. "byoc_plan_required" when a
|
|
104
|
+
// workspace below the deploy tier calls a BYOC-deployed endpoint). We thread
|
|
105
|
+
// it onto `.type` so callers can branch — `err instanceof PermissionDeniedError
|
|
106
|
+
// && err.type === "byoc_plan_required"` — instead of regex-scraping the message.
|
|
107
|
+
constructor(message, status, requestId, code, param, type = "permission_denied") {
|
|
108
|
+
super(message, { status, type, requestId, code, param });
|
|
27
109
|
this.name = "PermissionDeniedError";
|
|
28
110
|
}
|
|
29
111
|
}
|
|
30
112
|
export class RateLimitError extends RunInfraError {
|
|
31
|
-
constructor(message, status, requestId, retryAfterMs) {
|
|
32
|
-
super(message, { status, type: "rate_limit_error", requestId, retryAfterMs });
|
|
113
|
+
constructor(message, status, requestId, retryAfterMs, code, param) {
|
|
114
|
+
super(message, { status, type: "rate_limit_error", requestId, retryAfterMs, code, param });
|
|
33
115
|
this.name = "RateLimitError";
|
|
34
116
|
}
|
|
35
117
|
}
|
|
36
118
|
export class InsufficientCreditsError extends RunInfraError {
|
|
37
|
-
|
|
38
|
-
|
|
119
|
+
/** Remaining workspace balance in cents, when the gateway reports it. */
|
|
120
|
+
currentBalanceCents;
|
|
121
|
+
/** Credits this request needed, in cents, when the gateway reports it. */
|
|
122
|
+
requiredCents;
|
|
123
|
+
/** Where to top up, when the gateway reports it. */
|
|
124
|
+
topupUrl;
|
|
125
|
+
constructor(message, status, requestId, code, param, details) {
|
|
126
|
+
super(message, { status, type: "insufficient_credits", requestId, code, param });
|
|
39
127
|
this.name = "InsufficientCreditsError";
|
|
128
|
+
this.currentBalanceCents = details?.currentBalanceCents;
|
|
129
|
+
this.requiredCents = details?.requiredCents;
|
|
130
|
+
this.topupUrl = details?.topupUrl;
|
|
40
131
|
}
|
|
41
132
|
}
|
|
42
133
|
export class DeploymentError extends RunInfraError {
|
|
43
|
-
constructor(message, status, requestId) {
|
|
44
|
-
super(message, { status, type: "deployment_error", requestId });
|
|
134
|
+
constructor(message, status, requestId, code, param) {
|
|
135
|
+
super(message, { status, type: "deployment_error", requestId, code, param });
|
|
45
136
|
this.name = "DeploymentError";
|
|
46
137
|
}
|
|
47
138
|
}
|
|
48
139
|
export class ModelNotFoundError extends RunInfraError {
|
|
49
|
-
constructor(message, status, requestId) {
|
|
50
|
-
super(message, { status, type: "model_not_found", requestId });
|
|
140
|
+
constructor(message, status, requestId, code, param) {
|
|
141
|
+
super(message, { status, type: "model_not_found", requestId, code, param });
|
|
51
142
|
this.name = "ModelNotFoundError";
|
|
52
143
|
}
|
|
53
144
|
}
|
|
@@ -176,11 +267,13 @@ export class RunInfraAudioResponse {
|
|
|
176
267
|
requestId;
|
|
177
268
|
response;
|
|
178
269
|
readTimeoutMs;
|
|
179
|
-
|
|
270
|
+
sensitiveValues;
|
|
271
|
+
constructor(response, readTimeoutMs, sensitiveValues = []) {
|
|
180
272
|
this.response = response;
|
|
181
273
|
this.contentType = response.headers.get("content-type") ?? "application/octet-stream";
|
|
182
274
|
this.requestId = response.headers.get("x-request-id") ?? undefined;
|
|
183
275
|
this.readTimeoutMs = readTimeoutMs;
|
|
276
|
+
this.sensitiveValues = sensitiveValues;
|
|
184
277
|
}
|
|
185
278
|
arrayBuffer() {
|
|
186
279
|
return this.readBody(() => this.response.arrayBuffer(), "RunInfra audio response timed out while reading body");
|
|
@@ -199,7 +292,7 @@ export class RunInfraAudioResponse {
|
|
|
199
292
|
return await bodyRead;
|
|
200
293
|
}
|
|
201
294
|
catch (error) {
|
|
202
|
-
throw normalizeTransportError(error, this.requestId);
|
|
295
|
+
throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
|
|
203
296
|
}
|
|
204
297
|
}
|
|
205
298
|
let timeout;
|
|
@@ -215,7 +308,7 @@ export class RunInfraAudioResponse {
|
|
|
215
308
|
]);
|
|
216
309
|
}
|
|
217
310
|
catch (error) {
|
|
218
|
-
throw normalizeTransportError(error, this.requestId);
|
|
311
|
+
throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
|
|
219
312
|
}
|
|
220
313
|
finally {
|
|
221
314
|
if (timeout !== undefined)
|
|
@@ -227,10 +320,12 @@ export class RunInfraStream {
|
|
|
227
320
|
response;
|
|
228
321
|
requestId;
|
|
229
322
|
readTimeoutMs;
|
|
230
|
-
|
|
323
|
+
sensitiveValues;
|
|
324
|
+
constructor(response, readTimeoutMs, sensitiveValues = []) {
|
|
231
325
|
this.response = response;
|
|
232
326
|
this.requestId = response.headers.get("x-request-id") ?? undefined;
|
|
233
327
|
this.readTimeoutMs = readTimeoutMs;
|
|
328
|
+
this.sensitiveValues = sensitiveValues;
|
|
234
329
|
}
|
|
235
330
|
async *[Symbol.asyncIterator]() {
|
|
236
331
|
if (!this.response.body)
|
|
@@ -315,9 +410,7 @@ export class RunInfraStream {
|
|
|
315
410
|
}
|
|
316
411
|
}
|
|
317
412
|
catch (error) {
|
|
318
|
-
|
|
319
|
-
throw error;
|
|
320
|
-
throw normalizeTransportError(error, this.requestId);
|
|
413
|
+
throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
|
|
321
414
|
}
|
|
322
415
|
finally {
|
|
323
416
|
if (!readerDone) {
|
|
@@ -337,9 +430,6 @@ export class RunInfraStream {
|
|
|
337
430
|
}
|
|
338
431
|
}
|
|
339
432
|
}
|
|
340
|
-
function unsupportedOperation(message) {
|
|
341
|
-
return Promise.reject(new UnsupportedOperationError(message));
|
|
342
|
-
}
|
|
343
433
|
function baseUrlAlreadyHasPipelineId(baseURL, pipelineId) {
|
|
344
434
|
const encodedPipelineId = encodeURIComponent(pipelineId);
|
|
345
435
|
try {
|
|
@@ -418,6 +508,14 @@ function normalizeBaseURL(baseURL, pipelineId) {
|
|
|
418
508
|
return trimmed;
|
|
419
509
|
return `${trimmed}/${encodeURIComponent(validatedPipelineId)}`;
|
|
420
510
|
}
|
|
511
|
+
function baseUrlLooksPipelineScoped(baseURL) {
|
|
512
|
+
const parsed = new URL(baseURL);
|
|
513
|
+
const segments = parsed.pathname.split("/").filter(Boolean);
|
|
514
|
+
const lastV1 = segments.lastIndexOf("v1");
|
|
515
|
+
if (lastV1 >= 0)
|
|
516
|
+
return segments.length > lastV1 + 1;
|
|
517
|
+
return segments.length > 0;
|
|
518
|
+
}
|
|
421
519
|
function sleep(ms) {
|
|
422
520
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
423
521
|
}
|
|
@@ -458,6 +556,16 @@ function withValidatedModel(request) {
|
|
|
458
556
|
model: validateSdkModel(request.model),
|
|
459
557
|
};
|
|
460
558
|
}
|
|
559
|
+
function validateRequestFields(request, allowedKeys, label) {
|
|
560
|
+
if (!isPlainRecord(request)) {
|
|
561
|
+
throw invalidRequestOption(`${label} request must be an object`);
|
|
562
|
+
}
|
|
563
|
+
for (const key of Object.keys(request)) {
|
|
564
|
+
if (!allowedKeys.has(key)) {
|
|
565
|
+
throw invalidRequestOption(`Unknown ${label} request field: ${key}`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
461
569
|
function validateNonEmptyStringField(value, name) {
|
|
462
570
|
if (typeof value !== "string") {
|
|
463
571
|
throw invalidRequestOption(`${name} must be a string`);
|
|
@@ -517,10 +625,24 @@ function validateEmbeddingInput(value) {
|
|
|
517
625
|
}
|
|
518
626
|
throw invalidRequestOption("input must be a non-empty string or array of strings");
|
|
519
627
|
}
|
|
628
|
+
function validateEmbeddingResponseOptions(body) {
|
|
629
|
+
if (body.encoding_format !== undefined && body.encoding_format !== "float") {
|
|
630
|
+
throw invalidRequestOption("embedding encoding_format must be float for native SDK typed responses");
|
|
631
|
+
}
|
|
632
|
+
if (body.dimensions !== undefined &&
|
|
633
|
+
(typeof body.dimensions !== "number" ||
|
|
634
|
+
!Number.isSafeInteger(body.dimensions) ||
|
|
635
|
+
body.dimensions <= 0)) {
|
|
636
|
+
throw invalidRequestOption("embedding dimensions must be a positive integer");
|
|
637
|
+
}
|
|
638
|
+
}
|
|
520
639
|
function validateBlobFile(value) {
|
|
521
640
|
if (!(value instanceof Blob)) {
|
|
522
641
|
throw invalidRequestOption("file must be a Blob");
|
|
523
642
|
}
|
|
643
|
+
if (value.size === 0) {
|
|
644
|
+
throw invalidRequestOption("file must not be empty");
|
|
645
|
+
}
|
|
524
646
|
return value;
|
|
525
647
|
}
|
|
526
648
|
function validateVoicePipelineAudio(value) {
|
|
@@ -555,12 +677,6 @@ function validateMimeType(value, fallback = "audio/wav") {
|
|
|
555
677
|
}
|
|
556
678
|
return validateSdkHeader(trimmed, "mimeType", 255);
|
|
557
679
|
}
|
|
558
|
-
function validateMultipartFieldName(value) {
|
|
559
|
-
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(value)) {
|
|
560
|
-
throw invalidRequestOption("multipart field names must be ASCII tokens");
|
|
561
|
-
}
|
|
562
|
-
return value;
|
|
563
|
-
}
|
|
564
680
|
function validateMultipartFilename(value) {
|
|
565
681
|
if (typeof value !== "string") {
|
|
566
682
|
throw invalidRequestOption("filename must be a string");
|
|
@@ -585,6 +701,21 @@ function validateMultipartFieldValue(value) {
|
|
|
585
701
|
}
|
|
586
702
|
return String(value);
|
|
587
703
|
}
|
|
704
|
+
function validateTranscriptionResponseFormat(body) {
|
|
705
|
+
const responseFormat = body.response_format;
|
|
706
|
+
if (responseFormat !== undefined &&
|
|
707
|
+
responseFormat !== "json" &&
|
|
708
|
+
responseFormat !== "verbose_json") {
|
|
709
|
+
throw invalidRequestOption("audio transcription response_format must be json or verbose_json for native SDK typed responses");
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
function validateTranscriptionRequestKeys(request) {
|
|
713
|
+
for (const key of Object.keys(request)) {
|
|
714
|
+
if (!TRANSCRIPTION_REQUEST_KEYS.has(key)) {
|
|
715
|
+
throw invalidRequestOption(`Unknown audio transcription request field: ${key}`);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
588
719
|
const JSON_BODY_ERROR = "JSON request body must be JSON-serializable and contain only finite numbers";
|
|
589
720
|
function sanitizeJsonValue(value, seen = new WeakSet()) {
|
|
590
721
|
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
@@ -629,6 +760,27 @@ function sanitizeJsonValue(value, seen = new WeakSet()) {
|
|
|
629
760
|
function encodeJsonBody(payload) {
|
|
630
761
|
return JSON.stringify(sanitizeJsonValue(payload));
|
|
631
762
|
}
|
|
763
|
+
function mergeExtraJsonBody(payload, extraBody, typedKeys = new Set()) {
|
|
764
|
+
if (extraBody === undefined)
|
|
765
|
+
return payload;
|
|
766
|
+
if (!isPlainRecord(extraBody)) {
|
|
767
|
+
throw invalidRequestOption("extraBody must be an object");
|
|
768
|
+
}
|
|
769
|
+
if (!isPlainRecord(payload)) {
|
|
770
|
+
throw invalidRequestOption("extraBody can only be used with JSON object request bodies");
|
|
771
|
+
}
|
|
772
|
+
const merged = { ...payload };
|
|
773
|
+
for (const [key, value] of Object.entries(extraBody)) {
|
|
774
|
+
if (!key.trim()) {
|
|
775
|
+
throw invalidRequestOption("extraBody keys must be non-empty strings");
|
|
776
|
+
}
|
|
777
|
+
if (typedKeys.has(key) || key in payload) {
|
|
778
|
+
throw invalidRequestOption(`extraBody must not override typed request field: ${key}`);
|
|
779
|
+
}
|
|
780
|
+
merged[key] = value;
|
|
781
|
+
}
|
|
782
|
+
return merged;
|
|
783
|
+
}
|
|
632
784
|
function invalidRequestOption(message) {
|
|
633
785
|
return new RunInfraError(message, {
|
|
634
786
|
status: 0,
|
|
@@ -725,6 +877,7 @@ const REQUEST_OPTION_KEYS = new Set([
|
|
|
725
877
|
"maxRetries",
|
|
726
878
|
"retryBaseMs",
|
|
727
879
|
"headers",
|
|
880
|
+
"extraBody",
|
|
728
881
|
]);
|
|
729
882
|
function validateRequestOptions(requestOptions) {
|
|
730
883
|
if (requestOptions === undefined)
|
|
@@ -824,11 +977,22 @@ function retryDelayMs(attempt, baseMs, response) {
|
|
|
824
977
|
async function parseError(response) {
|
|
825
978
|
try {
|
|
826
979
|
const body = (await response.json());
|
|
980
|
+
const error = body.error ?? {};
|
|
827
981
|
return {
|
|
828
|
-
message: typeof
|
|
829
|
-
?
|
|
982
|
+
message: typeof error.message === "string"
|
|
983
|
+
? error.message
|
|
830
984
|
: `RunInfra request failed with status ${response.status}`,
|
|
831
|
-
type: typeof
|
|
985
|
+
type: typeof error.type === "string" ? error.type : "api_error",
|
|
986
|
+
...(typeof error.code === "string" ? { code: error.code } : {}),
|
|
987
|
+
...(typeof error.param === "string" ? { param: error.param } : {}),
|
|
988
|
+
// Structured remediation fields the gateway ships on 402 insufficient_credits.
|
|
989
|
+
...(typeof error.current_balance_cents === "number" && Number.isFinite(error.current_balance_cents)
|
|
990
|
+
? { currentBalanceCents: error.current_balance_cents }
|
|
991
|
+
: {}),
|
|
992
|
+
...(typeof error.required_cents === "number" && Number.isFinite(error.required_cents)
|
|
993
|
+
? { requiredCents: error.required_cents }
|
|
994
|
+
: {}),
|
|
995
|
+
...(typeof error.topup_url === "string" ? { topupUrl: error.topup_url } : {}),
|
|
832
996
|
};
|
|
833
997
|
}
|
|
834
998
|
catch {
|
|
@@ -849,41 +1013,48 @@ async function discardResponseBody(response) {
|
|
|
849
1013
|
async function raiseForStatus(response) {
|
|
850
1014
|
if (response.ok)
|
|
851
1015
|
return;
|
|
852
|
-
const { message, type } = await parseError(response);
|
|
1016
|
+
const { message, type, code, param, currentBalanceCents, requiredCents, topupUrl } = await parseError(response);
|
|
853
1017
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
854
1018
|
if (response.status === 401)
|
|
855
|
-
throw new AuthenticationError(message, response.status, requestId);
|
|
856
|
-
if (response.status === 403)
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
throw new
|
|
1019
|
+
throw new AuthenticationError(message, response.status, requestId, code, param);
|
|
1020
|
+
if (response.status === 403) {
|
|
1021
|
+
// Keep a more specific gateway discriminator (e.g. "byoc_plan_required")
|
|
1022
|
+
// on `.type` so callers can branch instead of regex-scraping the message.
|
|
1023
|
+
throw new PermissionDeniedError(message, response.status, requestId, code, param, type !== "api_error" ? type : "permission_denied");
|
|
1024
|
+
}
|
|
1025
|
+
if (response.status === 402) {
|
|
1026
|
+
throw new InsufficientCreditsError(message, response.status, requestId, code, param, {
|
|
1027
|
+
currentBalanceCents,
|
|
1028
|
+
requiredCents,
|
|
1029
|
+
topupUrl,
|
|
1030
|
+
});
|
|
1031
|
+
}
|
|
860
1032
|
if (response.status === 404 || type === "model_not_found") {
|
|
861
|
-
throw new ModelNotFoundError(message, response.status, requestId);
|
|
1033
|
+
throw new ModelNotFoundError(message, response.status, requestId, code, param);
|
|
862
1034
|
}
|
|
863
1035
|
if (response.status === 429) {
|
|
864
|
-
throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined);
|
|
1036
|
+
throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined, code, param);
|
|
865
1037
|
}
|
|
866
1038
|
if (type === "deployment_error")
|
|
867
|
-
throw new DeploymentError(message, response.status, requestId);
|
|
868
|
-
throw new RunInfraError(message, { status: response.status, type, requestId });
|
|
1039
|
+
throw new DeploymentError(message, response.status, requestId, code, param);
|
|
1040
|
+
throw new RunInfraError(message, { status: response.status, type, requestId, code, param });
|
|
869
1041
|
}
|
|
870
|
-
async function parseJsonResponse(response) {
|
|
1042
|
+
async function parseJsonResponse(response, sensitiveValues = []) {
|
|
871
1043
|
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
1044
|
+
const idempotentReplay = response.headers.get("x-runinfra-idempotent-replay")?.trim().toLowerCase() === "true";
|
|
872
1045
|
let payload;
|
|
873
1046
|
try {
|
|
874
1047
|
payload = await response.json();
|
|
875
1048
|
}
|
|
876
1049
|
catch (error) {
|
|
877
|
-
throw new ResponseBodyReadError(normalizeTransportError(error, requestId));
|
|
878
|
-
}
|
|
879
|
-
if (requestId &&
|
|
880
|
-
payload &&
|
|
881
|
-
typeof payload === "object" &&
|
|
882
|
-
!Array.isArray(payload)) {
|
|
883
|
-
return { ...payload, _request_id: requestId };
|
|
1050
|
+
throw new ResponseBodyReadError(normalizeTransportError(error, requestId, sensitiveValues));
|
|
884
1051
|
}
|
|
885
1052
|
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
886
|
-
return
|
|
1053
|
+
return {
|
|
1054
|
+
...payload,
|
|
1055
|
+
...(requestId ? { _request_id: requestId } : {}),
|
|
1056
|
+
...(idempotentReplay ? { _idempotent_replay: true } : {}),
|
|
1057
|
+
};
|
|
887
1058
|
}
|
|
888
1059
|
throw new RunInfraError(`RunInfra JSON response shape error: expected object, got ${jsonPayloadKind(payload)}.`, {
|
|
889
1060
|
status: response.status,
|
|
@@ -906,17 +1077,72 @@ class ResponseBodyReadError extends Error {
|
|
|
906
1077
|
this.error = error;
|
|
907
1078
|
}
|
|
908
1079
|
}
|
|
909
|
-
function
|
|
1080
|
+
function redactSensitiveValues(message, sensitiveValues = []) {
|
|
1081
|
+
let redacted = message;
|
|
1082
|
+
for (const value of sensitiveValues) {
|
|
1083
|
+
if (value)
|
|
1084
|
+
redacted = redacted.split(value).join("[redacted]");
|
|
1085
|
+
}
|
|
1086
|
+
return redacted;
|
|
1087
|
+
}
|
|
1088
|
+
function redactRunInfraError(error, sensitiveValues) {
|
|
1089
|
+
const message = redactSensitiveValues(error.message, sensitiveValues);
|
|
1090
|
+
const code = error.code === undefined ? undefined : redactSensitiveValues(error.code, sensitiveValues);
|
|
1091
|
+
const param = error.param === undefined ? undefined : redactSensitiveValues(error.param, sensitiveValues);
|
|
1092
|
+
if (error instanceof AuthenticationError) {
|
|
1093
|
+
return new AuthenticationError(message, error.status, error.requestId, code, param);
|
|
1094
|
+
}
|
|
1095
|
+
if (error instanceof PermissionDeniedError) {
|
|
1096
|
+
// Preserve the gateway discriminator (e.g. "byoc_plan_required") through redaction.
|
|
1097
|
+
return new PermissionDeniedError(message, error.status, error.requestId, code, param, error.type);
|
|
1098
|
+
}
|
|
1099
|
+
if (error instanceof RateLimitError) {
|
|
1100
|
+
return new RateLimitError(message, error.status, error.requestId, error.retryAfterMs, code, param);
|
|
1101
|
+
}
|
|
1102
|
+
if (error instanceof InsufficientCreditsError) {
|
|
1103
|
+
// Carry the structured top-up fields through redaction (they hold no secrets).
|
|
1104
|
+
return new InsufficientCreditsError(message, error.status, error.requestId, code, param, {
|
|
1105
|
+
currentBalanceCents: error.currentBalanceCents,
|
|
1106
|
+
requiredCents: error.requiredCents,
|
|
1107
|
+
topupUrl: error.topupUrl,
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
if (error instanceof DeploymentError) {
|
|
1111
|
+
return new DeploymentError(message, error.status, error.requestId, code, param);
|
|
1112
|
+
}
|
|
1113
|
+
if (error instanceof ModelNotFoundError) {
|
|
1114
|
+
return new ModelNotFoundError(message, error.status, error.requestId, code, param);
|
|
1115
|
+
}
|
|
1116
|
+
if (error instanceof RunInfraTimeoutError)
|
|
1117
|
+
return new RunInfraTimeoutError(message, error.requestId);
|
|
1118
|
+
if (error instanceof RunInfraConnectionError)
|
|
1119
|
+
return new RunInfraConnectionError(message, error.requestId);
|
|
1120
|
+
if (error instanceof RunInfraStreamParseError)
|
|
1121
|
+
return new RunInfraStreamParseError(message, error.requestId);
|
|
1122
|
+
if (error instanceof UnsupportedOperationError)
|
|
1123
|
+
return new UnsupportedOperationError(message);
|
|
1124
|
+
if (error instanceof WebhookVerificationError)
|
|
1125
|
+
return new WebhookVerificationError(message);
|
|
1126
|
+
return new RunInfraError(message, {
|
|
1127
|
+
status: error.status,
|
|
1128
|
+
type: error.type,
|
|
1129
|
+
requestId: error.requestId,
|
|
1130
|
+
retryAfterMs: error.retryAfterMs,
|
|
1131
|
+
code,
|
|
1132
|
+
param,
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
function normalizeTransportError(error, requestId, sensitiveValues = []) {
|
|
910
1136
|
if (error instanceof RunInfraError)
|
|
911
|
-
return error;
|
|
1137
|
+
return redactRunInfraError(error, sensitiveValues);
|
|
912
1138
|
if (error instanceof DOMException &&
|
|
913
1139
|
error.name === "AbortError") {
|
|
914
|
-
return new RunInfraTimeoutError(error.message, requestId);
|
|
1140
|
+
return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
|
|
915
1141
|
}
|
|
916
1142
|
if (error instanceof Error && error.name === "AbortError") {
|
|
917
|
-
return new RunInfraTimeoutError(error.message, requestId);
|
|
1143
|
+
return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
|
|
918
1144
|
}
|
|
919
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1145
|
+
const message = redactSensitiveValues(error instanceof Error ? error.message : String(error), sensitiveValues);
|
|
920
1146
|
return new RunInfraConnectionError(message, requestId);
|
|
921
1147
|
}
|
|
922
1148
|
export class RunInfra {
|
|
@@ -926,28 +1152,33 @@ export class RunInfra {
|
|
|
926
1152
|
/**
|
|
927
1153
|
* Audio surfaces (text-to-speech + speech-to-text).
|
|
928
1154
|
*
|
|
929
|
-
*
|
|
930
|
-
* against a live deployed pipeline in our canary suite. The HTTP envelope
|
|
1155
|
+
* Preview helpers for deployed RunInfra audio routes. The HTTP envelope
|
|
931
1156
|
* matches the OpenAI Audio API contract and the request/response shapes are
|
|
932
|
-
* stable
|
|
933
|
-
*
|
|
1157
|
+
* stable. Supported voices, reference-audio modes, and response formats are
|
|
1158
|
+
* deployment-specific.
|
|
934
1159
|
*/
|
|
935
1160
|
audio;
|
|
936
1161
|
models;
|
|
937
1162
|
/**
|
|
938
1163
|
* Image generation surface.
|
|
939
1164
|
*
|
|
940
|
-
*
|
|
941
|
-
*
|
|
942
|
-
*
|
|
943
|
-
* own deployed model before using in production. Live-canary verification
|
|
944
|
-
* is tracked for v1.0.0 GA.
|
|
1165
|
+
* Preview helper for deployed RunInfra image routes. The HTTP envelope
|
|
1166
|
+
* matches the OpenAI Images API contract. Supported size, response format,
|
|
1167
|
+
* quality, style, and user fields depend on the selected deployment.
|
|
945
1168
|
*/
|
|
946
1169
|
images;
|
|
947
1170
|
webhooks;
|
|
1171
|
+
/**
|
|
1172
|
+
* Voice pipeline surface.
|
|
1173
|
+
*
|
|
1174
|
+
* Preview helper for co-located voice pipelines. It requires a
|
|
1175
|
+
* pipeline-scoped client and posts binary audio to `/pipeline`; transcript
|
|
1176
|
+
* and response behavior depends on the selected deployment.
|
|
1177
|
+
*/
|
|
948
1178
|
voice;
|
|
949
1179
|
apiKey;
|
|
950
1180
|
baseURL;
|
|
1181
|
+
hasPipelineScope;
|
|
951
1182
|
timeoutMs;
|
|
952
1183
|
maxRetries;
|
|
953
1184
|
retryBaseMs;
|
|
@@ -969,7 +1200,9 @@ export class RunInfra {
|
|
|
969
1200
|
throw new RunInfraError("RunInfra SDK is intended for server-side environments because API keys are bearer secrets. Pass dangerouslyAllowBrowser: true only if you understand the risk.", { status: 0, type: "invalid_runtime" });
|
|
970
1201
|
}
|
|
971
1202
|
this.apiKey = validatedApiKey;
|
|
972
|
-
|
|
1203
|
+
const normalizedBaseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
|
|
1204
|
+
this.baseURL = normalizedBaseURL;
|
|
1205
|
+
this.hasPipelineScope = Boolean(options.pipelineId) || baseUrlLooksPipelineScoped(normalizedBaseURL);
|
|
973
1206
|
this.timeoutMs = validatePositiveNumber(options.timeoutMs ?? 120_000, "timeoutMs");
|
|
974
1207
|
this.maxRetries = validateNonNegativeInteger(options.maxRetries ?? 2, "maxRetries");
|
|
975
1208
|
this.retryBaseMs = validateNonNegativeNumber(options.retryBaseMs ?? 250, "retryBaseMs");
|
|
@@ -978,12 +1211,15 @@ export class RunInfra {
|
|
|
978
1211
|
}
|
|
979
1212
|
this.fetcher = options.fetch ?? fetch;
|
|
980
1213
|
const createChatCompletion = ((request, requestOptions) => {
|
|
1214
|
+
validateRequestFields(request, CHAT_COMPLETION_REQUEST_KEYS, "chat completion");
|
|
981
1215
|
const body = withValidatedModel(request);
|
|
982
1216
|
validateChatMessages(body.messages);
|
|
983
1217
|
return this.request("/chat/completions", {
|
|
984
1218
|
method: "POST",
|
|
985
1219
|
body,
|
|
1220
|
+
typedBodyKeys: CHAT_COMPLETION_REQUEST_KEYS,
|
|
986
1221
|
stream: body.stream === true,
|
|
1222
|
+
idempotentReplaySafe: true,
|
|
987
1223
|
}, requestOptions);
|
|
988
1224
|
});
|
|
989
1225
|
this.chat = {
|
|
@@ -993,49 +1229,58 @@ export class RunInfra {
|
|
|
993
1229
|
};
|
|
994
1230
|
this.embeddings = {
|
|
995
1231
|
create: (request, requestOptions) => {
|
|
1232
|
+
validateRequestFields(request, EMBEDDING_REQUEST_KEYS, "embedding");
|
|
996
1233
|
const body = withValidatedModel(request);
|
|
997
1234
|
validateEmbeddingInput(body.input);
|
|
1235
|
+
validateEmbeddingResponseOptions(body);
|
|
998
1236
|
return this.request("/embeddings", {
|
|
999
1237
|
method: "POST",
|
|
1000
1238
|
body,
|
|
1239
|
+
typedBodyKeys: EMBEDDING_REQUEST_KEYS,
|
|
1001
1240
|
}, requestOptions);
|
|
1002
1241
|
},
|
|
1003
1242
|
};
|
|
1004
1243
|
this.responses = {
|
|
1005
1244
|
create: ((request, requestOptions) => {
|
|
1245
|
+
validateRequestFields(request, RESPONSES_CREATE_REQUEST_KEYS, "responses");
|
|
1006
1246
|
const body = withValidatedModel(request);
|
|
1007
1247
|
validateResponsesInput(body.input);
|
|
1008
1248
|
return this.request("/responses", {
|
|
1009
1249
|
method: "POST",
|
|
1010
1250
|
body,
|
|
1251
|
+
typedBodyKeys: RESPONSES_CREATE_REQUEST_KEYS,
|
|
1011
1252
|
stream: body.stream === true,
|
|
1253
|
+
idempotentReplaySafe: true,
|
|
1012
1254
|
}, requestOptions);
|
|
1013
1255
|
}),
|
|
1014
1256
|
};
|
|
1015
1257
|
this.audio = {
|
|
1016
1258
|
speech: {
|
|
1017
1259
|
create: async (request, requestOptions) => {
|
|
1260
|
+
validateRequestFields(request, SPEECH_REQUEST_KEYS, "audio speech");
|
|
1018
1261
|
const body = withValidatedModel(request);
|
|
1019
1262
|
validateNonEmptyStringField(body.input, "input");
|
|
1020
1263
|
validateSpeechReference(body);
|
|
1021
1264
|
const response = await this.rawRequest("/audio/speech", {
|
|
1022
1265
|
method: "POST",
|
|
1023
1266
|
body,
|
|
1267
|
+
typedBodyKeys: SPEECH_REQUEST_KEYS,
|
|
1024
1268
|
binary: true,
|
|
1025
1269
|
}, requestOptions);
|
|
1026
|
-
return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions));
|
|
1270
|
+
return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
|
|
1027
1271
|
},
|
|
1028
1272
|
},
|
|
1029
1273
|
transcriptions: {
|
|
1030
1274
|
create: (request, requestOptions) => {
|
|
1275
|
+
validateTranscriptionRequestKeys(request);
|
|
1276
|
+
validateTranscriptionResponseFormat(request);
|
|
1031
1277
|
const formData = new FormData();
|
|
1032
1278
|
formData.append("model", validateSdkModel(request.model));
|
|
1033
1279
|
formData.append("file", validateBlobFile(request.file), validateMultipartFilename(request.filename ?? "audio.wav"));
|
|
1034
|
-
for (const [
|
|
1035
|
-
|
|
1036
|
-
continue;
|
|
1280
|
+
for (const key of ["language", "prompt", "response_format", "temperature"]) {
|
|
1281
|
+
const value = request[key];
|
|
1037
1282
|
if (value !== undefined && value !== null) {
|
|
1038
|
-
formData.append(
|
|
1283
|
+
formData.append(key, validateMultipartFieldValue(value));
|
|
1039
1284
|
}
|
|
1040
1285
|
}
|
|
1041
1286
|
return this.request("/audio/transcriptions", {
|
|
@@ -1051,23 +1296,27 @@ export class RunInfra {
|
|
|
1051
1296
|
};
|
|
1052
1297
|
this.images = {
|
|
1053
1298
|
generate: (request, requestOptions) => {
|
|
1299
|
+
validateRequestFields(request, IMAGE_GENERATE_REQUEST_KEYS, "image generation");
|
|
1054
1300
|
const body = withValidatedModel(request);
|
|
1055
1301
|
validateNonEmptyStringField(body.prompt, "prompt");
|
|
1056
1302
|
return this.request("/images/generations", {
|
|
1057
1303
|
method: "POST",
|
|
1058
1304
|
body,
|
|
1305
|
+
typedBodyKeys: IMAGE_GENERATE_REQUEST_KEYS,
|
|
1059
1306
|
}, requestOptions);
|
|
1060
1307
|
},
|
|
1061
1308
|
};
|
|
1062
1309
|
this.webhooks = {
|
|
1063
1310
|
verifySignature: verifyWebhookSignature,
|
|
1064
1311
|
constructEvent: constructWebhookEvent,
|
|
1065
|
-
create: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
|
|
1066
|
-
list: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
|
|
1067
1312
|
};
|
|
1068
1313
|
this.voice = {
|
|
1069
1314
|
pipeline: {
|
|
1070
1315
|
create: (request, requestOptions) => {
|
|
1316
|
+
if (!this.hasPipelineScope) {
|
|
1317
|
+
throw invalidRequestOption("voice pipeline requests require pipelineId or a pipeline-scoped baseURL");
|
|
1318
|
+
}
|
|
1319
|
+
validateRequestFields(request, VOICE_PIPELINE_REQUEST_KEYS, "voice pipeline");
|
|
1071
1320
|
const audio = validateVoicePipelineAudio(request?.audio);
|
|
1072
1321
|
return this.request("/pipeline", {
|
|
1073
1322
|
method: "POST",
|
|
@@ -1082,7 +1331,7 @@ export class RunInfra {
|
|
|
1082
1331
|
async request(path, options, requestOptions) {
|
|
1083
1332
|
if (options.stream) {
|
|
1084
1333
|
const response = await this.rawRequest(path, options, requestOptions);
|
|
1085
|
-
return new RunInfraStream(response, this.requestTimeoutMs(requestOptions));
|
|
1334
|
+
return new RunInfraStream(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
|
|
1086
1335
|
}
|
|
1087
1336
|
return this.sendWithRetry(path, options, requestOptions, (parseJsonResponse));
|
|
1088
1337
|
}
|
|
@@ -1108,9 +1357,15 @@ export class RunInfra {
|
|
|
1108
1357
|
}
|
|
1109
1358
|
let body;
|
|
1110
1359
|
if (options.formData) {
|
|
1360
|
+
if (validatedRequestOptions.extraBody !== undefined) {
|
|
1361
|
+
throw invalidRequestOption("extraBody can only be used with JSON request bodies");
|
|
1362
|
+
}
|
|
1111
1363
|
body = options.formData;
|
|
1112
1364
|
}
|
|
1113
1365
|
else if (options.rawBody !== undefined) {
|
|
1366
|
+
if (validatedRequestOptions.extraBody !== undefined) {
|
|
1367
|
+
throw invalidRequestOption("extraBody can only be used with JSON request bodies");
|
|
1368
|
+
}
|
|
1114
1369
|
body = options.rawBody;
|
|
1115
1370
|
headers["Content-Type"] = options.rawContentType ?? "application/octet-stream";
|
|
1116
1371
|
if (options.accept)
|
|
@@ -1118,11 +1373,18 @@ export class RunInfra {
|
|
|
1118
1373
|
}
|
|
1119
1374
|
else if (options.body !== undefined) {
|
|
1120
1375
|
headers["Content-Type"] = "application/json";
|
|
1121
|
-
body = encodeJsonBody(options.body);
|
|
1376
|
+
body = encodeJsonBody(mergeExtraJsonBody(options.body, validatedRequestOptions.extraBody, options.typedBodyKeys));
|
|
1377
|
+
}
|
|
1378
|
+
else if (validatedRequestOptions.extraBody !== undefined) {
|
|
1379
|
+
throw invalidRequestOption("extraBody can only be used with JSON request bodies");
|
|
1122
1380
|
}
|
|
1123
1381
|
let attempt = 0;
|
|
1124
1382
|
const method = options.method ?? "POST";
|
|
1125
|
-
const hasReplayableJsonBody = options.body !== undefined &&
|
|
1383
|
+
const hasReplayableJsonBody = options.body !== undefined &&
|
|
1384
|
+
!options.stream &&
|
|
1385
|
+
!options.binary &&
|
|
1386
|
+
!options.formData &&
|
|
1387
|
+
options.idempotentReplaySafe === true;
|
|
1126
1388
|
const canRetry = method === "GET" ||
|
|
1127
1389
|
(Boolean(validatedRequestOptions.idempotencyKey) && hasReplayableJsonBody);
|
|
1128
1390
|
const maxRetries = validateNonNegativeInteger(validatedRequestOptions.maxRetries ?? this.maxRetries, "maxRetries");
|
|
@@ -1148,7 +1410,7 @@ export class RunInfra {
|
|
|
1148
1410
|
continue;
|
|
1149
1411
|
}
|
|
1150
1412
|
await raiseForStatus(response);
|
|
1151
|
-
return await consumeResponse(response);
|
|
1413
|
+
return await consumeResponse(response, [this.apiKey]);
|
|
1152
1414
|
}
|
|
1153
1415
|
catch (error) {
|
|
1154
1416
|
if (error instanceof ResponseBodyReadError) {
|
|
@@ -1157,12 +1419,12 @@ export class RunInfra {
|
|
|
1157
1419
|
await sleep(retryDelayMs(attempt, retryBaseMs));
|
|
1158
1420
|
continue;
|
|
1159
1421
|
}
|
|
1160
|
-
throw error.error;
|
|
1422
|
+
throw normalizeTransportError(error.error, error.error.requestId, [this.apiKey]);
|
|
1161
1423
|
}
|
|
1162
1424
|
if (error instanceof RunInfraError)
|
|
1163
|
-
throw error;
|
|
1425
|
+
throw normalizeTransportError(error, error.requestId, [this.apiKey]);
|
|
1164
1426
|
if (!canRetry || attempt >= maxRetries)
|
|
1165
|
-
throw normalizeTransportError(error);
|
|
1427
|
+
throw normalizeTransportError(error, undefined, [this.apiKey]);
|
|
1166
1428
|
attempt += 1;
|
|
1167
1429
|
await sleep(retryDelayMs(attempt, retryBaseMs));
|
|
1168
1430
|
}
|