@runinfra/sdk 0.1.2 → 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/dist/index.js CHANGED
@@ -1,11 +1,86 @@
1
1
  import { createHmac, timingSafeEqual } from "node:crypto";
2
- export const RUNINFRA_SDK_VERSION = "0.1.2";
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
- constructor(message, status, requestId) {
26
- super(message, { status, type: "permission_denied", requestId });
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
- constructor(message, status, requestId) {
38
- super(message, { status, type: "insufficient_credits", requestId });
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
- constructor(response, readTimeoutMs) {
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
- constructor(response, readTimeoutMs) {
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
- if (error instanceof RunInfraError)
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,27 +430,31 @@ 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 {
346
436
  const parsed = new URL(baseURL);
347
- const lastSegment = parsed.pathname.replace(/\/+$/u, "").split("/").pop();
437
+ const lastSegment = stripTrailingSlashes(parsed.pathname).split("/").pop();
348
438
  return lastSegment === encodedPipelineId || decodeURIComponent(lastSegment ?? "") === pipelineId;
349
439
  }
350
440
  catch {
351
- const trimmed = baseURL.replace(/\/+$/u, "");
441
+ const trimmed = stripTrailingSlashes(baseURL);
352
442
  return (trimmed.endsWith(`/${encodedPipelineId}`) ||
353
443
  trimmed.endsWith(`/${pipelineId}`));
354
444
  }
355
445
  }
446
+ function stripTrailingSlashes(value) {
447
+ let end = value.length;
448
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
449
+ end -= 1;
450
+ }
451
+ return end === value.length ? value : value.slice(0, end);
452
+ }
356
453
  function validateBaseURL(baseURL) {
357
454
  if (typeof baseURL !== "string") {
358
455
  throw invalidRequestOption("baseURL must be a string");
359
456
  }
360
- const trimmed = baseURL.trim().replace(/\/+$/, "");
457
+ const trimmed = stripTrailingSlashes(baseURL.trim());
361
458
  try {
362
459
  const parsed = new URL(trimmed);
363
460
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
@@ -411,6 +508,14 @@ function normalizeBaseURL(baseURL, pipelineId) {
411
508
  return trimmed;
412
509
  return `${trimmed}/${encodeURIComponent(validatedPipelineId)}`;
413
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
+ }
414
519
  function sleep(ms) {
415
520
  return new Promise((resolve) => setTimeout(resolve, ms));
416
521
  }
@@ -451,6 +556,16 @@ function withValidatedModel(request) {
451
556
  model: validateSdkModel(request.model),
452
557
  };
453
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
+ }
454
569
  function validateNonEmptyStringField(value, name) {
455
570
  if (typeof value !== "string") {
456
571
  throw invalidRequestOption(`${name} must be a string`);
@@ -510,10 +625,24 @@ function validateEmbeddingInput(value) {
510
625
  }
511
626
  throw invalidRequestOption("input must be a non-empty string or array of strings");
512
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
+ }
513
639
  function validateBlobFile(value) {
514
640
  if (!(value instanceof Blob)) {
515
641
  throw invalidRequestOption("file must be a Blob");
516
642
  }
643
+ if (value.size === 0) {
644
+ throw invalidRequestOption("file must not be empty");
645
+ }
517
646
  return value;
518
647
  }
519
648
  function validateVoicePipelineAudio(value) {
@@ -548,12 +677,6 @@ function validateMimeType(value, fallback = "audio/wav") {
548
677
  }
549
678
  return validateSdkHeader(trimmed, "mimeType", 255);
550
679
  }
551
- function validateMultipartFieldName(value) {
552
- if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(value)) {
553
- throw invalidRequestOption("multipart field names must be ASCII tokens");
554
- }
555
- return value;
556
- }
557
680
  function validateMultipartFilename(value) {
558
681
  if (typeof value !== "string") {
559
682
  throw invalidRequestOption("filename must be a string");
@@ -578,6 +701,21 @@ function validateMultipartFieldValue(value) {
578
701
  }
579
702
  return String(value);
580
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
+ }
581
719
  const JSON_BODY_ERROR = "JSON request body must be JSON-serializable and contain only finite numbers";
582
720
  function sanitizeJsonValue(value, seen = new WeakSet()) {
583
721
  if (value === null || typeof value === "string" || typeof value === "boolean")
@@ -622,6 +760,27 @@ function sanitizeJsonValue(value, seen = new WeakSet()) {
622
760
  function encodeJsonBody(payload) {
623
761
  return JSON.stringify(sanitizeJsonValue(payload));
624
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
+ }
625
784
  function invalidRequestOption(message) {
626
785
  return new RunInfraError(message, {
627
786
  status: 0,
@@ -718,6 +877,7 @@ const REQUEST_OPTION_KEYS = new Set([
718
877
  "maxRetries",
719
878
  "retryBaseMs",
720
879
  "headers",
880
+ "extraBody",
721
881
  ]);
722
882
  function validateRequestOptions(requestOptions) {
723
883
  if (requestOptions === undefined)
@@ -748,6 +908,10 @@ function validateRunInfraOptions(options) {
748
908
  throw invalidRequestOption(`Unknown RunInfra option: ${key}`);
749
909
  }
750
910
  }
911
+ if (options.dangerouslyAllowBrowser !== undefined &&
912
+ typeof options.dangerouslyAllowBrowser !== "boolean") {
913
+ throw invalidRequestOption("dangerouslyAllowBrowser must be a boolean");
914
+ }
751
915
  }
752
916
  function generatedClientRequestId() {
753
917
  const randomUUID = globalThis.crypto?.randomUUID;
@@ -756,7 +920,23 @@ function generatedClientRequestId() {
756
920
  return `runinfra-${Date.now()}-${Math.random().toString(16).slice(2)}`;
757
921
  }
758
922
  function isBrowserRuntime() {
759
- return typeof globalThis.window === "object" && typeof globalThis.document === "object";
923
+ const runtime = globalThis;
924
+ if (typeof runtime.window === "object" &&
925
+ runtime.window !== null &&
926
+ typeof runtime.document === "object" &&
927
+ runtime.document !== null) {
928
+ return true;
929
+ }
930
+ const workerGlobalScope = runtime.WorkerGlobalScope;
931
+ if (typeof workerGlobalScope !== "function" ||
932
+ typeof runtime.self !== "object" ||
933
+ runtime.self === null) {
934
+ return false;
935
+ }
936
+ const prototype = workerGlobalScope.prototype;
937
+ return typeof prototype === "object" &&
938
+ prototype !== null &&
939
+ Object.prototype.isPrototypeOf.call(prototype, runtime.self);
760
940
  }
761
941
  function retryAfterMs(response) {
762
942
  const value = response.headers.get("retry-after");
@@ -797,11 +977,22 @@ function retryDelayMs(attempt, baseMs, response) {
797
977
  async function parseError(response) {
798
978
  try {
799
979
  const body = (await response.json());
980
+ const error = body.error ?? {};
800
981
  return {
801
- message: typeof body.error?.message === "string"
802
- ? body.error.message
982
+ message: typeof error.message === "string"
983
+ ? error.message
803
984
  : `RunInfra request failed with status ${response.status}`,
804
- type: typeof body.error?.type === "string" ? body.error.type : "api_error",
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 } : {}),
805
996
  };
806
997
  }
807
998
  catch {
@@ -822,41 +1013,48 @@ async function discardResponseBody(response) {
822
1013
  async function raiseForStatus(response) {
823
1014
  if (response.ok)
824
1015
  return;
825
- const { message, type } = await parseError(response);
1016
+ const { message, type, code, param, currentBalanceCents, requiredCents, topupUrl } = await parseError(response);
826
1017
  const requestId = response.headers.get("x-request-id") ?? undefined;
827
1018
  if (response.status === 401)
828
- throw new AuthenticationError(message, response.status, requestId);
829
- if (response.status === 403)
830
- throw new PermissionDeniedError(message, response.status, requestId);
831
- if (response.status === 402)
832
- throw new InsufficientCreditsError(message, response.status, requestId);
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
+ }
833
1032
  if (response.status === 404 || type === "model_not_found") {
834
- throw new ModelNotFoundError(message, response.status, requestId);
1033
+ throw new ModelNotFoundError(message, response.status, requestId, code, param);
835
1034
  }
836
1035
  if (response.status === 429) {
837
- throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined);
1036
+ throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined, code, param);
838
1037
  }
839
1038
  if (type === "deployment_error")
840
- throw new DeploymentError(message, response.status, requestId);
841
- 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 });
842
1041
  }
843
- async function parseJsonResponse(response) {
1042
+ async function parseJsonResponse(response, sensitiveValues = []) {
844
1043
  const requestId = response.headers.get("x-request-id") ?? undefined;
1044
+ const idempotentReplay = response.headers.get("x-runinfra-idempotent-replay")?.trim().toLowerCase() === "true";
845
1045
  let payload;
846
1046
  try {
847
1047
  payload = await response.json();
848
1048
  }
849
1049
  catch (error) {
850
- throw new ResponseBodyReadError(normalizeTransportError(error, requestId));
851
- }
852
- if (requestId &&
853
- payload &&
854
- typeof payload === "object" &&
855
- !Array.isArray(payload)) {
856
- return { ...payload, _request_id: requestId };
1050
+ throw new ResponseBodyReadError(normalizeTransportError(error, requestId, sensitiveValues));
857
1051
  }
858
1052
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
859
- return payload;
1053
+ return {
1054
+ ...payload,
1055
+ ...(requestId ? { _request_id: requestId } : {}),
1056
+ ...(idempotentReplay ? { _idempotent_replay: true } : {}),
1057
+ };
860
1058
  }
861
1059
  throw new RunInfraError(`RunInfra JSON response shape error: expected object, got ${jsonPayloadKind(payload)}.`, {
862
1060
  status: response.status,
@@ -879,17 +1077,72 @@ class ResponseBodyReadError extends Error {
879
1077
  this.error = error;
880
1078
  }
881
1079
  }
882
- function normalizeTransportError(error, requestId) {
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 = []) {
883
1136
  if (error instanceof RunInfraError)
884
- return error;
1137
+ return redactRunInfraError(error, sensitiveValues);
885
1138
  if (error instanceof DOMException &&
886
1139
  error.name === "AbortError") {
887
- return new RunInfraTimeoutError(error.message, requestId);
1140
+ return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
888
1141
  }
889
1142
  if (error instanceof Error && error.name === "AbortError") {
890
- return new RunInfraTimeoutError(error.message, requestId);
1143
+ return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
891
1144
  }
892
- const message = error instanceof Error ? error.message : String(error);
1145
+ const message = redactSensitiveValues(error instanceof Error ? error.message : String(error), sensitiveValues);
893
1146
  return new RunInfraConnectionError(message, requestId);
894
1147
  }
895
1148
  export class RunInfra {
@@ -899,28 +1152,33 @@ export class RunInfra {
899
1152
  /**
900
1153
  * Audio surfaces (text-to-speech + speech-to-text).
901
1154
  *
902
- * @experimental As of v0.1.2, these methods have NOT been verified end-to-end
903
- * against a live deployed pipeline in our canary suite. The HTTP envelope
1155
+ * Preview helpers for deployed RunInfra audio routes. The HTTP envelope
904
1156
  * matches the OpenAI Audio API contract and the request/response shapes are
905
- * stable, but you should test against your own deployed model before using
906
- * in production. Live-canary verification is tracked for v1.0.0 GA.
1157
+ * stable. Supported voices, reference-audio modes, and response formats are
1158
+ * deployment-specific.
907
1159
  */
908
1160
  audio;
909
1161
  models;
910
1162
  /**
911
1163
  * Image generation surface.
912
1164
  *
913
- * @experimental As of v0.1.2, this method has NOT been verified end-to-end
914
- * against a live deployed pipeline in our canary suite. The HTTP envelope
915
- * matches the OpenAI Images API contract, but you should test against your
916
- * own deployed model before using in production. Live-canary verification
917
- * 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.
918
1168
  */
919
1169
  images;
920
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
+ */
921
1178
  voice;
922
1179
  apiKey;
923
1180
  baseURL;
1181
+ hasPipelineScope;
924
1182
  timeoutMs;
925
1183
  maxRetries;
926
1184
  retryBaseMs;
@@ -942,7 +1200,9 @@ export class RunInfra {
942
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" });
943
1201
  }
944
1202
  this.apiKey = validatedApiKey;
945
- this.baseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
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);
946
1206
  this.timeoutMs = validatePositiveNumber(options.timeoutMs ?? 120_000, "timeoutMs");
947
1207
  this.maxRetries = validateNonNegativeInteger(options.maxRetries ?? 2, "maxRetries");
948
1208
  this.retryBaseMs = validateNonNegativeNumber(options.retryBaseMs ?? 250, "retryBaseMs");
@@ -951,12 +1211,15 @@ export class RunInfra {
951
1211
  }
952
1212
  this.fetcher = options.fetch ?? fetch;
953
1213
  const createChatCompletion = ((request, requestOptions) => {
1214
+ validateRequestFields(request, CHAT_COMPLETION_REQUEST_KEYS, "chat completion");
954
1215
  const body = withValidatedModel(request);
955
1216
  validateChatMessages(body.messages);
956
1217
  return this.request("/chat/completions", {
957
1218
  method: "POST",
958
1219
  body,
1220
+ typedBodyKeys: CHAT_COMPLETION_REQUEST_KEYS,
959
1221
  stream: body.stream === true,
1222
+ idempotentReplaySafe: true,
960
1223
  }, requestOptions);
961
1224
  });
962
1225
  this.chat = {
@@ -966,49 +1229,58 @@ export class RunInfra {
966
1229
  };
967
1230
  this.embeddings = {
968
1231
  create: (request, requestOptions) => {
1232
+ validateRequestFields(request, EMBEDDING_REQUEST_KEYS, "embedding");
969
1233
  const body = withValidatedModel(request);
970
1234
  validateEmbeddingInput(body.input);
1235
+ validateEmbeddingResponseOptions(body);
971
1236
  return this.request("/embeddings", {
972
1237
  method: "POST",
973
1238
  body,
1239
+ typedBodyKeys: EMBEDDING_REQUEST_KEYS,
974
1240
  }, requestOptions);
975
1241
  },
976
1242
  };
977
1243
  this.responses = {
978
1244
  create: ((request, requestOptions) => {
1245
+ validateRequestFields(request, RESPONSES_CREATE_REQUEST_KEYS, "responses");
979
1246
  const body = withValidatedModel(request);
980
1247
  validateResponsesInput(body.input);
981
1248
  return this.request("/responses", {
982
1249
  method: "POST",
983
1250
  body,
1251
+ typedBodyKeys: RESPONSES_CREATE_REQUEST_KEYS,
984
1252
  stream: body.stream === true,
1253
+ idempotentReplaySafe: true,
985
1254
  }, requestOptions);
986
1255
  }),
987
1256
  };
988
1257
  this.audio = {
989
1258
  speech: {
990
1259
  create: async (request, requestOptions) => {
1260
+ validateRequestFields(request, SPEECH_REQUEST_KEYS, "audio speech");
991
1261
  const body = withValidatedModel(request);
992
1262
  validateNonEmptyStringField(body.input, "input");
993
1263
  validateSpeechReference(body);
994
1264
  const response = await this.rawRequest("/audio/speech", {
995
1265
  method: "POST",
996
1266
  body,
1267
+ typedBodyKeys: SPEECH_REQUEST_KEYS,
997
1268
  binary: true,
998
1269
  }, requestOptions);
999
- return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions));
1270
+ return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
1000
1271
  },
1001
1272
  },
1002
1273
  transcriptions: {
1003
1274
  create: (request, requestOptions) => {
1275
+ validateTranscriptionRequestKeys(request);
1276
+ validateTranscriptionResponseFormat(request);
1004
1277
  const formData = new FormData();
1005
1278
  formData.append("model", validateSdkModel(request.model));
1006
1279
  formData.append("file", validateBlobFile(request.file), validateMultipartFilename(request.filename ?? "audio.wav"));
1007
- for (const [key, value] of Object.entries(request)) {
1008
- if (key === "model" || key === "file" || key === "filename")
1009
- continue;
1280
+ for (const key of ["language", "prompt", "response_format", "temperature"]) {
1281
+ const value = request[key];
1010
1282
  if (value !== undefined && value !== null) {
1011
- formData.append(validateMultipartFieldName(key), validateMultipartFieldValue(value));
1283
+ formData.append(key, validateMultipartFieldValue(value));
1012
1284
  }
1013
1285
  }
1014
1286
  return this.request("/audio/transcriptions", {
@@ -1024,23 +1296,27 @@ export class RunInfra {
1024
1296
  };
1025
1297
  this.images = {
1026
1298
  generate: (request, requestOptions) => {
1299
+ validateRequestFields(request, IMAGE_GENERATE_REQUEST_KEYS, "image generation");
1027
1300
  const body = withValidatedModel(request);
1028
1301
  validateNonEmptyStringField(body.prompt, "prompt");
1029
1302
  return this.request("/images/generations", {
1030
1303
  method: "POST",
1031
1304
  body,
1305
+ typedBodyKeys: IMAGE_GENERATE_REQUEST_KEYS,
1032
1306
  }, requestOptions);
1033
1307
  },
1034
1308
  };
1035
1309
  this.webhooks = {
1036
1310
  verifySignature: verifyWebhookSignature,
1037
1311
  constructEvent: constructWebhookEvent,
1038
- create: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
1039
- list: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
1040
1312
  };
1041
1313
  this.voice = {
1042
1314
  pipeline: {
1043
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");
1044
1320
  const audio = validateVoicePipelineAudio(request?.audio);
1045
1321
  return this.request("/pipeline", {
1046
1322
  method: "POST",
@@ -1055,7 +1331,7 @@ export class RunInfra {
1055
1331
  async request(path, options, requestOptions) {
1056
1332
  if (options.stream) {
1057
1333
  const response = await this.rawRequest(path, options, requestOptions);
1058
- return new RunInfraStream(response, this.requestTimeoutMs(requestOptions));
1334
+ return new RunInfraStream(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
1059
1335
  }
1060
1336
  return this.sendWithRetry(path, options, requestOptions, (parseJsonResponse));
1061
1337
  }
@@ -1081,9 +1357,15 @@ export class RunInfra {
1081
1357
  }
1082
1358
  let body;
1083
1359
  if (options.formData) {
1360
+ if (validatedRequestOptions.extraBody !== undefined) {
1361
+ throw invalidRequestOption("extraBody can only be used with JSON request bodies");
1362
+ }
1084
1363
  body = options.formData;
1085
1364
  }
1086
1365
  else if (options.rawBody !== undefined) {
1366
+ if (validatedRequestOptions.extraBody !== undefined) {
1367
+ throw invalidRequestOption("extraBody can only be used with JSON request bodies");
1368
+ }
1087
1369
  body = options.rawBody;
1088
1370
  headers["Content-Type"] = options.rawContentType ?? "application/octet-stream";
1089
1371
  if (options.accept)
@@ -1091,11 +1373,18 @@ export class RunInfra {
1091
1373
  }
1092
1374
  else if (options.body !== undefined) {
1093
1375
  headers["Content-Type"] = "application/json";
1094
- 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");
1095
1380
  }
1096
1381
  let attempt = 0;
1097
1382
  const method = options.method ?? "POST";
1098
- const hasReplayableJsonBody = options.body !== undefined && !options.stream && !options.binary && !options.formData;
1383
+ const hasReplayableJsonBody = options.body !== undefined &&
1384
+ !options.stream &&
1385
+ !options.binary &&
1386
+ !options.formData &&
1387
+ options.idempotentReplaySafe === true;
1099
1388
  const canRetry = method === "GET" ||
1100
1389
  (Boolean(validatedRequestOptions.idempotencyKey) && hasReplayableJsonBody);
1101
1390
  const maxRetries = validateNonNegativeInteger(validatedRequestOptions.maxRetries ?? this.maxRetries, "maxRetries");
@@ -1121,7 +1410,7 @@ export class RunInfra {
1121
1410
  continue;
1122
1411
  }
1123
1412
  await raiseForStatus(response);
1124
- return await consumeResponse(response);
1413
+ return await consumeResponse(response, [this.apiKey]);
1125
1414
  }
1126
1415
  catch (error) {
1127
1416
  if (error instanceof ResponseBodyReadError) {
@@ -1130,12 +1419,12 @@ export class RunInfra {
1130
1419
  await sleep(retryDelayMs(attempt, retryBaseMs));
1131
1420
  continue;
1132
1421
  }
1133
- throw error.error;
1422
+ throw normalizeTransportError(error.error, error.error.requestId, [this.apiKey]);
1134
1423
  }
1135
1424
  if (error instanceof RunInfraError)
1136
- throw error;
1425
+ throw normalizeTransportError(error, error.requestId, [this.apiKey]);
1137
1426
  if (!canRetry || attempt >= maxRetries)
1138
- throw normalizeTransportError(error);
1427
+ throw normalizeTransportError(error, undefined, [this.apiKey]);
1139
1428
  attempt += 1;
1140
1429
  await sleep(retryDelayMs(attempt, retryBaseMs));
1141
1430
  }