@runinfra/sdk 0.1.3 → 0.3.2

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,170 @@
1
1
  import { createHmac, timingSafeEqual } from "node:crypto";
2
- export const RUNINFRA_SDK_VERSION = "0.1.3";
2
+ export const RUNINFRA_SDK_VERSION = "0.3.2";
3
+ /**
4
+ * The longest wait the API may name (`Retry-After-Ms`, `Retry-After`) that the
5
+ * SDK sleeps for before it asks again. A longer wait is raised at once, with
6
+ * the wait on the error.
7
+ */
3
8
  const MAX_AUTOMATIC_RETRY_AFTER_MS = 60_000;
9
+ /**
10
+ * The timeout of a non-streamed call when the caller names none. The API
11
+ * allows a whole response up to 740 seconds, so the default sits just above.
12
+ * The runtime's `fetch` may give up sooner by its own clock: Node's built-in
13
+ * `fetch` waits at most 300 seconds for the response headers.
14
+ */
15
+ const DEFAULT_TIMEOUT_MS = 750_000;
16
+ /**
17
+ * The timeout of a streamed call when the caller names none: the wait for the
18
+ * response headers, and for each later read. The API allows a stream up to
19
+ * 180 seconds to its first token, so the default sits just above.
20
+ */
21
+ const DEFAULT_STREAM_TIMEOUT_MS = 190_000;
22
+ /**
23
+ * The chat request fields that `extraBody` has always refused, because the
24
+ * request type names them.
25
+ */
26
+ const CHAT_COMPLETION_EXTRA_BODY_CLOSED_KEYS = new Set([
27
+ "model",
28
+ "messages",
29
+ "stream",
30
+ "temperature",
31
+ "top_p",
32
+ "max_tokens",
33
+ "max_completion_tokens",
34
+ "stop",
35
+ "presence_penalty",
36
+ "frequency_penalty",
37
+ "user",
38
+ "metadata",
39
+ "stream_options",
40
+ "tools",
41
+ "tool_choice",
42
+ "response_format",
43
+ "seed",
44
+ "logprobs",
45
+ "top_logprobs",
46
+ ]);
47
+ /**
48
+ * Every field a chat request may carry. The fields typed since 0.3.1 are
49
+ * accepted here and stay accepted in `extraBody`, where callers had to put
50
+ * them before; naming one in both places is refused.
51
+ */
52
+ const CHAT_COMPLETION_REQUEST_KEYS = new Set([
53
+ ...CHAT_COMPLETION_EXTRA_BODY_CLOSED_KEYS,
54
+ "top_k",
55
+ "min_p",
56
+ "repetition_penalty",
57
+ "n",
58
+ "best_of",
59
+ "logit_bias",
60
+ "parallel_tool_calls",
61
+ "reasoning_effort",
62
+ "reasoning",
63
+ "include_reasoning",
64
+ "prompt_cache_key",
65
+ "service_tier",
66
+ "store",
67
+ "safety_identifier",
68
+ "modalities",
69
+ "audio",
70
+ "prediction",
71
+ "verbosity",
72
+ "web_search_options",
73
+ "moderation",
74
+ "functions",
75
+ "function_call",
76
+ ]);
77
+ const RESPONSES_CREATE_REQUEST_KEYS = new Set([
78
+ "model",
79
+ "input",
80
+ "instructions",
81
+ "max_output_tokens",
82
+ "stream",
83
+ "temperature",
84
+ "top_p",
85
+ "tools",
86
+ "tool_choice",
87
+ "response_format",
88
+ ]);
89
+ const EMBEDDING_REQUEST_KEYS = new Set([
90
+ "model",
91
+ "input",
92
+ "encoding_format",
93
+ "dimensions",
94
+ "user",
95
+ ]);
96
+ const SPEECH_REQUEST_KEYS = new Set([
97
+ "model",
98
+ "input",
99
+ "voice",
100
+ "ref_audio",
101
+ "ref_text",
102
+ "task_type",
103
+ "response_format",
104
+ "speed",
105
+ ]);
106
+ const TRANSCRIPTION_REQUEST_KEYS = new Set([
107
+ "model",
108
+ "file",
109
+ "filename",
110
+ "language",
111
+ "prompt",
112
+ "response_format",
113
+ "temperature",
114
+ ]);
115
+ const IMAGE_GENERATE_REQUEST_KEYS = new Set([
116
+ "model",
117
+ "prompt",
118
+ "n",
119
+ "size",
120
+ "response_format",
121
+ "quality",
122
+ "style",
123
+ "user",
124
+ ]);
125
+ const VOICE_PIPELINE_REQUEST_KEYS = new Set([
126
+ "audio",
127
+ "mimeType",
128
+ ]);
129
+ const BATCH_CREATE_REQUEST_KEYS = new Set([
130
+ "model",
131
+ "input_url",
132
+ "destination",
133
+ "max_cost_cents",
134
+ "window_hours",
135
+ "name",
136
+ ]);
137
+ const BATCH_LIST_PARAM_KEYS = ["limit", "cursor", "state", "model"];
4
138
  export class RunInfraError extends Error {
5
139
  status;
6
140
  type;
7
141
  requestId;
142
+ /**
143
+ * The wait the API named with the error, in milliseconds: `Retry-After-Ms`
144
+ * when the response carries it, else `Retry-After`. Set on every error whose
145
+ * response named a wait, whatever its status.
146
+ */
8
147
  retryAfterMs;
148
+ code;
149
+ param;
150
+ /**
151
+ * The closed cause word of a batch route's refusal, when its error body
152
+ * names one (`error.reason`): `model`, `partner`, or `price` on
153
+ * `flex_not_available`. Other routes do not set it.
154
+ */
155
+ reason;
156
+ /**
157
+ * What the API said about asking again, when it said it: `x-should-retry` on
158
+ * the response, or `retryable` inside the error object. `false` means the
159
+ * same request will fail again. Left unset when the API said nothing.
160
+ */
161
+ retryable;
162
+ /**
163
+ * The `X-Client-Request-Id` the SDK sent with the call, set on a timeout.
164
+ * A call that timed out before any response has no server request id, so
165
+ * this is the id to quote to support.
166
+ */
167
+ clientRequestId;
9
168
  constructor(message, input) {
10
169
  super(message);
11
170
  this.name = "RunInfraError";
@@ -13,47 +172,79 @@ export class RunInfraError extends Error {
13
172
  this.type = input.type;
14
173
  this.requestId = input.requestId;
15
174
  this.retryAfterMs = input.retryAfterMs;
175
+ this.code = input.code;
176
+ this.param = input.param;
177
+ this.reason = input.reason;
178
+ this.retryable = input.retryable;
179
+ this.clientRequestId = input.clientRequestId;
16
180
  }
17
181
  }
18
182
  export class AuthenticationError extends RunInfraError {
19
- constructor(message, status, requestId) {
20
- super(message, { status, type: "auth_error", requestId });
183
+ constructor(message, status, requestId, code, param) {
184
+ super(message, { status, type: "auth_error", requestId, code, param });
21
185
  this.name = "AuthenticationError";
22
186
  }
23
187
  }
24
188
  export class PermissionDeniedError extends RunInfraError {
25
- constructor(message, status, requestId) {
26
- super(message, { status, type: "permission_denied", requestId });
189
+ // `type` defaults to "permission_denied" but the gateway can supply a more
190
+ // specific discriminator on the 403 body (e.g. "byoc_plan_required" when a
191
+ // workspace below the deploy tier calls a BYOC-deployed endpoint). We thread
192
+ // it onto `.type` so callers can branch — `err instanceof PermissionDeniedError
193
+ // && err.type === "byoc_plan_required"` — instead of regex-scraping the message.
194
+ constructor(message, status, requestId, code, param, type = "permission_denied") {
195
+ super(message, { status, type, requestId, code, param });
27
196
  this.name = "PermissionDeniedError";
28
197
  }
29
198
  }
30
199
  export class RateLimitError extends RunInfraError {
31
- constructor(message, status, requestId, retryAfterMs) {
32
- super(message, { status, type: "rate_limit_error", requestId, retryAfterMs });
200
+ constructor(message, status, requestId, retryAfterMs, code, param) {
201
+ super(message, { status, type: "rate_limit_error", requestId, retryAfterMs, code, param });
33
202
  this.name = "RateLimitError";
34
203
  }
35
204
  }
205
+ /**
206
+ * A `402` from the gateway. On a batch route, read `code` to tell
207
+ * `needs_funds` (the account has never added funds) from
208
+ * `key_spend_limit_reached` (this API key reached its own monthly limit;
209
+ * raise the key's limit or use another key).
210
+ */
36
211
  export class InsufficientCreditsError extends RunInfraError {
37
- constructor(message, status, requestId) {
38
- super(message, { status, type: "insufficient_credits", requestId });
212
+ /** Remaining workspace balance in cents, when the gateway reports it. */
213
+ currentBalanceCents;
214
+ /** Credits this request needed, in cents, when the gateway reports it. */
215
+ requiredCents;
216
+ /** Where to top up, when the gateway reports it. */
217
+ topupUrl;
218
+ constructor(message, status, requestId, code, param, details) {
219
+ super(message, { status, type: "insufficient_credits", requestId, code, param });
39
220
  this.name = "InsufficientCreditsError";
221
+ this.currentBalanceCents = details?.currentBalanceCents;
222
+ this.requiredCents = details?.requiredCents;
223
+ this.topupUrl = details?.topupUrl;
40
224
  }
41
225
  }
42
226
  export class DeploymentError extends RunInfraError {
43
- constructor(message, status, requestId) {
44
- super(message, { status, type: "deployment_error", requestId });
227
+ constructor(message, status, requestId, code, param) {
228
+ super(message, { status, type: "deployment_error", requestId, code, param });
45
229
  this.name = "DeploymentError";
46
230
  }
47
231
  }
48
232
  export class ModelNotFoundError extends RunInfraError {
49
- constructor(message, status, requestId) {
50
- super(message, { status, type: "model_not_found", requestId });
233
+ constructor(message, status, requestId, code, param) {
234
+ super(message, { status, type: "model_not_found", requestId, code, param });
51
235
  this.name = "ModelNotFoundError";
52
236
  }
53
237
  }
238
+ /**
239
+ * A call that ran out of time: the SDK's own timeout, or the runtime's `fetch`
240
+ * giving up on the response headers or the body by its own clock.
241
+ * `clientRequestId` holds the `X-Client-Request-Id` the SDK sent with the
242
+ * call; `requestId` is set only when a response had begun. A call is never
243
+ * sent again after a timeout: the API may still be working on it.
244
+ */
54
245
  export class RunInfraTimeoutError extends RunInfraError {
55
- constructor(message = "RunInfra request timed out", requestId) {
56
- super(message, { status: 0, type: "timeout_error", requestId });
246
+ constructor(message = "RunInfra request timed out", requestId, clientRequestId) {
247
+ super(message, { status: 0, type: "timeout_error", requestId, clientRequestId });
57
248
  this.name = "RunInfraTimeoutError";
58
249
  }
59
250
  }
@@ -69,6 +260,32 @@ export class RunInfraStreamParseError extends RunInfraError {
69
260
  this.name = "RunInfraStreamParseError";
70
261
  }
71
262
  }
263
+ /**
264
+ * The API ended an open stream with a failure: a frame that holds an `error`
265
+ * object, or a `response.failed` event on a Responses stream. `type`, `code`
266
+ * and `param` are the API's own, `retryable` is set when the API marked the
267
+ * failure, and `requestId` is the request id the frame names, else the
268
+ * stream's. `status` is `0`: the failure arrived after the HTTP status. The
269
+ * events before the failure were already yielded. The answer is not whole.
270
+ */
271
+ export class RunInfraStreamError extends RunInfraError {
272
+ constructor(message, input) {
273
+ super(message, { status: 0, ...input });
274
+ this.name = "RunInfraStreamError";
275
+ }
276
+ }
277
+ /**
278
+ * A stream's body ended without its end marker: `[DONE]` on a chat stream,
279
+ * `response.completed` on a Responses stream. The connection was cut or the
280
+ * stream was closed early, so the answer is not whole even though the HTTP
281
+ * status was 200. The events before the end were already yielded.
282
+ */
283
+ export class RunInfraStreamIncompleteError extends RunInfraError {
284
+ constructor(message = "RunInfra stream ended before its end marker; the answer is incomplete", requestId) {
285
+ super(message, { status: 0, type: "stream_incomplete_error", requestId });
286
+ this.name = "RunInfraStreamIncompleteError";
287
+ }
288
+ }
72
289
  export class UnsupportedOperationError extends RunInfraError {
73
290
  constructor(message) {
74
291
  super(message, { status: 400, type: "unsupported_operation" });
@@ -171,16 +388,168 @@ export function constructWebhookEvent(options) {
171
388
  throw new WebhookVerificationError("Webhook payload must be valid JSON.");
172
389
  }
173
390
  }
391
+ const BATCH_DELIVERY_SECRET_PREFIX = "whsec_";
392
+ /** How far a delivery's timestamp may be from the clock unless the caller says otherwise, as for webhook events. */
393
+ const BATCH_DELIVERY_DEFAULT_TOLERANCE_SECONDS = 300;
394
+ function batchDeliveryHeader(headers, name) {
395
+ let value;
396
+ if (headers !== null && typeof headers === "object" && typeof headers.get === "function") {
397
+ value = headers.get(name);
398
+ }
399
+ else if (isPlainRecord(headers)) {
400
+ const matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);
401
+ if (matches.length > 1) {
402
+ throw new WebhookVerificationError(`Batch delivery header ${name} is present more than once.`);
403
+ }
404
+ const found = matches[0]?.[1];
405
+ if (Array.isArray(found) && found.length > 1) {
406
+ throw new WebhookVerificationError(`Batch delivery header ${name} is present more than once.`);
407
+ }
408
+ value = Array.isArray(found) ? found[0] : found;
409
+ }
410
+ else {
411
+ throw new WebhookVerificationError("Batch delivery headers must be a Headers object or a plain object.");
412
+ }
413
+ if (typeof value !== "string" || !value.trim()) {
414
+ throw new WebhookVerificationError(`Batch delivery header ${name} is missing.`);
415
+ }
416
+ if (value.length > WEBHOOK_SIGNATURE_HEADER_MAX_LENGTH) {
417
+ throw new WebhookVerificationError(`Batch delivery header ${name} is too large.`);
418
+ }
419
+ return value.trim();
420
+ }
421
+ function batchDeliverySecretKey(secret) {
422
+ if (typeof secret !== "string" || !secret.trim()) {
423
+ throw new WebhookVerificationError("Batch signing secret is required.");
424
+ }
425
+ const trimmed = secret.trim();
426
+ const encoded = trimmed.startsWith(BATCH_DELIVERY_SECRET_PREFIX)
427
+ ? trimmed.slice(BATCH_DELIVERY_SECRET_PREFIX.length)
428
+ : trimmed;
429
+ if (encoded.length === 0 || encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(encoded)) {
430
+ throw new WebhookVerificationError("Batch signing secret must be whsec_ followed by base64.");
431
+ }
432
+ return Buffer.from(encoded, "base64");
433
+ }
434
+ function timingSafeTextEqual(a, b) {
435
+ const left = Buffer.from(a, "utf8");
436
+ const right = Buffer.from(b, "utf8");
437
+ return left.length === right.length && timingSafeEqual(left, right);
438
+ }
439
+ /**
440
+ * Verifies one batch delivery posted to your own address and returns it parsed
441
+ * and typed: the test delivery of `batches.create()`, one line's answer, or
442
+ * one line's error.
443
+ *
444
+ * Pass the RAW request body, exactly the bytes that arrived, and the request's
445
+ * headers in any case. The signature is the Standard Webhooks one: header
446
+ * `webhook-signature` holds `v1,` followed by the base64 HMAC-SHA-256 of
447
+ * `<webhook-id>.<webhook-timestamp>.<raw body>`, compared in constant time.
448
+ * Parsing the body and serializing it again changes the bytes and fails the
449
+ * check.
450
+ *
451
+ * `secret` is the workspace's batch signing secret as the dashboard shows it:
452
+ * `whsec_` followed by base64. The HMAC key is the base64-DECODED bytes after
453
+ * the prefix, not the text. Header `x-rightnow-signature-version` names the
454
+ * version of the secret that signed; a rotated secret stops verifying.
455
+ *
456
+ * The delivery's `webhook-timestamp` must be within 300 seconds of the clock
457
+ * by default, so a captured delivery cannot be replayed later. A number in
458
+ * `toleranceSeconds` sets another tolerance, `toleranceSeconds: null` turns
459
+ * the check off, and `now` sets the clock it is compared with.
460
+ *
461
+ * ANSWERING THE TEST DELIVERY: `batches.create()` posts
462
+ * `{ id, test: true, value }` to the destination before it answers, and the
463
+ * address passes only when it replies 2xx with a body that CONTAINS the posted
464
+ * `value`. A fixed `200 OK` fails the create with `destination_unreachable`.
465
+ * Line deliveries (`test: false`) are acknowledged by any 2xx. Each answered
466
+ * line is sent to the address once: if the address does not answer 2xx in
467
+ * time, the line is counted `undelivered`, it is not charged, and it is not
468
+ * sent again.
469
+ *
470
+ * Throws `WebhookVerificationError` when a header is missing, the signature
471
+ * does not match, the timestamp is outside the tolerance, or the body is not a
472
+ * delivery. Every failure of this helper is a `WebhookVerificationError`.
473
+ */
474
+ export function verifyBatchDelivery(options) {
475
+ try {
476
+ return verifiedBatchDelivery(options);
477
+ }
478
+ catch (error) {
479
+ if (error instanceof WebhookVerificationError)
480
+ throw error;
481
+ throw new WebhookVerificationError("Batch delivery could not be verified.");
482
+ }
483
+ }
484
+ function verifiedBatchDelivery(options) {
485
+ if (!isPlainRecord(options)) {
486
+ throw new WebhookVerificationError("Batch delivery verification options are required.");
487
+ }
488
+ const key = batchDeliverySecretKey(options.secret);
489
+ const toleranceSeconds = options.toleranceSeconds === undefined
490
+ ? BATCH_DELIVERY_DEFAULT_TOLERANCE_SECONDS
491
+ : options.toleranceSeconds;
492
+ if (toleranceSeconds !== null &&
493
+ (typeof toleranceSeconds !== "number" || !Number.isFinite(toleranceSeconds) || toleranceSeconds < 0)) {
494
+ throw new WebhookVerificationError("Batch delivery tolerance must be a non-negative number, or null to turn the check off.");
495
+ }
496
+ const id = batchDeliveryHeader(options.headers, "webhook-id");
497
+ const timestamp = batchDeliveryHeader(options.headers, "webhook-timestamp");
498
+ const signatureHeader = batchDeliveryHeader(options.headers, "webhook-signature");
499
+ if (!/^[0-9]+$/u.test(timestamp) || !Number.isSafeInteger(Number(timestamp))) {
500
+ throw new WebhookVerificationError("Batch delivery timestamp must be a non-negative integer.");
501
+ }
502
+ if (toleranceSeconds !== null) {
503
+ const now = options.now ?? Math.floor(Date.now() / 1000);
504
+ if (!Number.isFinite(now) || now < 0) {
505
+ throw new WebhookVerificationError("Batch delivery verification clock must be a non-negative finite number.");
506
+ }
507
+ if (Math.abs(now - Number(timestamp)) > toleranceSeconds) {
508
+ throw new WebhookVerificationError("Batch delivery timestamp is outside the allowed tolerance.");
509
+ }
510
+ }
511
+ const payload = webhookPayloadBytes(options.payload);
512
+ const hmac = createHmac("sha256", key);
513
+ hmac.update(`${id}.${timestamp}.`);
514
+ hmac.update(payload);
515
+ const expected = `v1,${hmac.digest("base64")}`;
516
+ // Standard Webhooks allows several space-separated signatures; one match is enough.
517
+ const candidates = signatureHeader.split(" ").filter(Boolean);
518
+ let verified = false;
519
+ for (const candidate of candidates) {
520
+ if (timingSafeTextEqual(candidate, expected))
521
+ verified = true;
522
+ }
523
+ if (!verified) {
524
+ throw new WebhookVerificationError("Batch delivery signature verification failed.");
525
+ }
526
+ let parsed;
527
+ try {
528
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload));
529
+ }
530
+ catch {
531
+ throw new WebhookVerificationError("Batch delivery payload must be valid JSON.");
532
+ }
533
+ if (!isPlainRecord(parsed) || typeof parsed.id !== "string" || typeof parsed.test !== "boolean") {
534
+ throw new WebhookVerificationError("Batch delivery payload is not a batch delivery.");
535
+ }
536
+ return parsed;
537
+ }
174
538
  export class RunInfraAudioResponse {
175
539
  contentType;
176
540
  requestId;
177
541
  response;
178
542
  readTimeoutMs;
179
- constructor(response, readTimeoutMs) {
543
+ sensitiveValues;
544
+ /** The `X-Client-Request-Id` the SDK sent with the call. A timeout while the body is read names it. */
545
+ clientRequestId;
546
+ constructor(response, readTimeoutMs, sensitiveValues = [], clientRequestId) {
180
547
  this.response = response;
181
548
  this.contentType = response.headers.get("content-type") ?? "application/octet-stream";
182
549
  this.requestId = response.headers.get("x-request-id") ?? undefined;
183
550
  this.readTimeoutMs = readTimeoutMs;
551
+ this.sensitiveValues = sensitiveValues;
552
+ this.clientRequestId = clientRequestId;
184
553
  }
185
554
  arrayBuffer() {
186
555
  return this.readBody(() => this.response.arrayBuffer(), "RunInfra audio response timed out while reading body");
@@ -199,7 +568,7 @@ export class RunInfraAudioResponse {
199
568
  return await bodyRead;
200
569
  }
201
570
  catch (error) {
202
- throw normalizeTransportError(error, this.requestId);
571
+ throw this.bodyReadFailure(error);
203
572
  }
204
573
  }
205
574
  let timeout;
@@ -215,42 +584,126 @@ export class RunInfraAudioResponse {
215
584
  ]);
216
585
  }
217
586
  catch (error) {
218
- throw normalizeTransportError(error, this.requestId);
587
+ throw this.bodyReadFailure(error);
219
588
  }
220
589
  finally {
221
590
  if (timeout !== undefined)
222
591
  clearTimeout(timeout);
223
592
  }
224
593
  }
594
+ /** A failed body read as the SDK's error. A timeout names the request id the SDK sent. */
595
+ bodyReadFailure(error) {
596
+ const failure = normalizeTransportError(error, this.requestId, this.sensitiveValues);
597
+ return failure instanceof RunInfraTimeoutError
598
+ ? withErrorFacts(failure, { clientRequestId: this.clientRequestId })
599
+ : failure;
600
+ }
601
+ }
602
+ /**
603
+ * The failure an open stream reported, read from one parsed event: a frame
604
+ * with a top-level `error` object, or a Responses `response.failed` event,
605
+ * whose error sits inside `response`. `undefined` for every other event.
606
+ */
607
+ function streamFailure(event, streamRequestId) {
608
+ if (!isPlainRecord(event))
609
+ return undefined;
610
+ let failure;
611
+ if (isPlainRecord(event.error)) {
612
+ failure = event.error;
613
+ }
614
+ else if (event.type === "response.failed") {
615
+ const response = isPlainRecord(event.response) ? event.response : {};
616
+ failure = isPlainRecord(response.error) ? response.error : {};
617
+ }
618
+ if (!failure)
619
+ return undefined;
620
+ return new RunInfraStreamError(typeof failure.message === "string" && failure.message
621
+ ? failure.message
622
+ : "RunInfra stream ended with an error", {
623
+ type: typeof failure.type === "string" ? failure.type : "api_error",
624
+ requestId: typeof event.request_id === "string" && event.request_id ? event.request_id : streamRequestId,
625
+ ...(typeof failure.code === "string" ? { code: failure.code } : {}),
626
+ ...(typeof failure.param === "string" ? { param: failure.param } : {}),
627
+ ...(typeof failure.retryable === "boolean" ? { retryable: failure.retryable } : {}),
628
+ });
225
629
  }
630
+ /**
631
+ * Whether a successful answer to a streamed call is one JSON object instead of
632
+ * an event stream. The API answers this way when a streamed call repeats an
633
+ * `Idempotency-Key` it has already answered: `Content-Type: application/json`,
634
+ * `X-RunInfra-Idempotent-Replay: true` and one object.
635
+ */
636
+ function streamAnsweredWithJson(response) {
637
+ const contentType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
638
+ if (contentType === "text/event-stream")
639
+ return false;
640
+ if (contentType === "application/json" || contentType.endsWith("+json"))
641
+ return true;
642
+ return isIdempotentReplay(response);
643
+ }
644
+ /**
645
+ * The events of one streamed answer.
646
+ *
647
+ * Iterating yields each event as it arrives. The iteration ends quietly only
648
+ * when the stream carried its end marker: `[DONE]` on a chat stream,
649
+ * `response.completed` on a Responses stream. It throws instead, after
650
+ * yielding every event that came first, when the API reports a failure on the
651
+ * open stream (`RunInfraStreamError`) or when the body ends without the end
652
+ * marker (`RunInfraStreamIncompleteError`). Leaving the loop early throws
653
+ * nothing.
654
+ *
655
+ * When the API answers the call with one JSON object instead of an event
656
+ * stream, the iteration yields that object once and ends quietly. That is the
657
+ * answer to a streamed call that repeats an `Idempotency-Key`: the object
658
+ * carries `_idempotent_replay: true`, as a non-streamed answer does.
659
+ */
226
660
  export class RunInfraStream {
227
661
  response;
228
662
  requestId;
229
663
  readTimeoutMs;
230
- constructor(response, readTimeoutMs) {
664
+ sensitiveValues;
665
+ /** The `X-Client-Request-Id` the SDK sent with the call. A timeout while the stream is read names it. */
666
+ clientRequestId;
667
+ constructor(response, readTimeoutMs, sensitiveValues = [], clientRequestId) {
231
668
  this.response = response;
232
669
  this.requestId = response.headers.get("x-request-id") ?? undefined;
233
670
  this.readTimeoutMs = readTimeoutMs;
671
+ this.sensitiveValues = sensitiveValues;
672
+ this.clientRequestId = clientRequestId;
234
673
  }
235
674
  async *[Symbol.asyncIterator]() {
236
- if (!this.response.body)
237
- return;
675
+ if (!this.response.body) {
676
+ throw new RunInfraStreamIncompleteError(undefined, this.requestId);
677
+ }
238
678
  const reader = this.response.body.getReader();
239
679
  const decoder = new TextDecoder();
240
680
  let buffer = "";
241
681
  let dataLines = [];
242
682
  let readerDone = false;
683
+ // Whether the end marker arrived: `[DONE]`, or a Responses `response.completed` event.
684
+ let completed = false;
243
685
  const dispatchEvent = () => {
244
686
  const payload = dataLines.join("\n").trim();
245
687
  dataLines = [];
246
- if (!payload || payload === "[DONE]")
688
+ if (!payload)
247
689
  return null;
690
+ if (payload === "[DONE]") {
691
+ completed = true;
692
+ return null;
693
+ }
694
+ let event;
248
695
  try {
249
- return JSON.parse(payload);
696
+ event = JSON.parse(payload);
250
697
  }
251
698
  catch {
252
699
  throw new RunInfraStreamParseError(undefined, this.requestId);
253
700
  }
701
+ const failure = streamFailure(event, this.requestId);
702
+ if (failure)
703
+ throw failure;
704
+ if (isPlainRecord(event) && event.type === "response.completed")
705
+ completed = true;
706
+ return event;
254
707
  };
255
708
  const processLine = (line) => {
256
709
  const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
@@ -287,6 +740,27 @@ export class RunInfraStream {
287
740
  }
288
741
  };
289
742
  try {
743
+ if (streamAnsweredWithJson(this.response)) {
744
+ // One JSON object, not an event stream: read it whole and yield it as the only event.
745
+ while (true) {
746
+ const { done, value } = await readChunk();
747
+ if (done) {
748
+ readerDone = true;
749
+ break;
750
+ }
751
+ buffer += decoder.decode(value, { stream: true });
752
+ }
753
+ buffer += decoder.decode();
754
+ let answer;
755
+ try {
756
+ answer = JSON.parse(buffer);
757
+ }
758
+ catch {
759
+ throw new RunInfraStreamIncompleteError("RunInfra answered a streamed call with a JSON body that could not be read; the answer is incomplete", this.requestId);
760
+ }
761
+ yield jsonAnswer(answer, this.response);
762
+ return;
763
+ }
290
764
  while (true) {
291
765
  const { done, value } = await readChunk();
292
766
  if (done) {
@@ -303,21 +777,33 @@ export class RunInfraStream {
303
777
  }
304
778
  }
305
779
  buffer += decoder.decode();
306
- if (buffer) {
307
- const parsed = processLine(buffer);
308
- if (parsed)
309
- yield parsed;
780
+ // What is left was not ended by a blank line. If it cannot be read and no end marker came before it, the
781
+ // body ended inside an event: that is a cut stream, reported below, not a malformed event.
782
+ const unfinished = [];
783
+ try {
784
+ const lastLine = buffer ? processLine(buffer) : null;
785
+ if (lastLine)
786
+ unfinished.push(lastLine);
787
+ const lastEvent = dataLines.length > 0 ? dispatchEvent() : null;
788
+ if (lastEvent)
789
+ unfinished.push(lastEvent);
310
790
  }
311
- if (dataLines.length > 0) {
312
- const parsed = dispatchEvent();
313
- if (parsed)
314
- yield parsed;
791
+ catch (error) {
792
+ if (!(error instanceof RunInfraStreamParseError) || completed)
793
+ throw error;
315
794
  }
795
+ for (const event of unfinished)
796
+ yield event;
797
+ // The body is over. Without the end marker the answer was cut short, whatever the HTTP status said.
798
+ if (!completed)
799
+ throw new RunInfraStreamIncompleteError(undefined, this.requestId);
316
800
  }
317
801
  catch (error) {
318
- if (error instanceof RunInfraError)
319
- throw error;
320
- throw normalizeTransportError(error, this.requestId);
802
+ const failure = normalizeTransportError(error, this.requestId, this.sensitiveValues);
803
+ // A timeout while the stream is read names the request id the SDK sent, as a timeout before the stream opened does.
804
+ throw failure instanceof RunInfraTimeoutError
805
+ ? withErrorFacts(failure, { clientRequestId: this.clientRequestId })
806
+ : failure;
321
807
  }
322
808
  finally {
323
809
  if (!readerDone) {
@@ -337,9 +823,6 @@ export class RunInfraStream {
337
823
  }
338
824
  }
339
825
  }
340
- function unsupportedOperation(message) {
341
- return Promise.reject(new UnsupportedOperationError(message));
342
- }
343
826
  function baseUrlAlreadyHasPipelineId(baseURL, pipelineId) {
344
827
  const encodedPipelineId = encodeURIComponent(pipelineId);
345
828
  try {
@@ -418,6 +901,14 @@ function normalizeBaseURL(baseURL, pipelineId) {
418
901
  return trimmed;
419
902
  return `${trimmed}/${encodeURIComponent(validatedPipelineId)}`;
420
903
  }
904
+ function baseUrlLooksPipelineScoped(baseURL) {
905
+ const parsed = new URL(baseURL);
906
+ const segments = parsed.pathname.split("/").filter(Boolean);
907
+ const lastV1 = segments.lastIndexOf("v1");
908
+ if (lastV1 >= 0)
909
+ return segments.length > lastV1 + 1;
910
+ return segments.length > 0;
911
+ }
421
912
  function sleep(ms) {
422
913
  return new Promise((resolve) => setTimeout(resolve, ms));
423
914
  }
@@ -458,6 +949,16 @@ function withValidatedModel(request) {
458
949
  model: validateSdkModel(request.model),
459
950
  };
460
951
  }
952
+ function validateRequestFields(request, allowedKeys, label) {
953
+ if (!isPlainRecord(request)) {
954
+ throw invalidRequestOption(`${label} request must be an object`);
955
+ }
956
+ for (const key of Object.keys(request)) {
957
+ if (!allowedKeys.has(key)) {
958
+ throw invalidRequestOption(`Unknown ${label} request field: ${key}`);
959
+ }
960
+ }
961
+ }
461
962
  function validateNonEmptyStringField(value, name) {
462
963
  if (typeof value !== "string") {
463
964
  throw invalidRequestOption(`${name} must be a string`);
@@ -517,10 +1018,24 @@ function validateEmbeddingInput(value) {
517
1018
  }
518
1019
  throw invalidRequestOption("input must be a non-empty string or array of strings");
519
1020
  }
1021
+ function validateEmbeddingResponseOptions(body) {
1022
+ if (body.encoding_format !== undefined && body.encoding_format !== "float") {
1023
+ throw invalidRequestOption("embedding encoding_format must be float for native SDK typed responses");
1024
+ }
1025
+ if (body.dimensions !== undefined &&
1026
+ (typeof body.dimensions !== "number" ||
1027
+ !Number.isSafeInteger(body.dimensions) ||
1028
+ body.dimensions <= 0)) {
1029
+ throw invalidRequestOption("embedding dimensions must be a positive integer");
1030
+ }
1031
+ }
520
1032
  function validateBlobFile(value) {
521
1033
  if (!(value instanceof Blob)) {
522
1034
  throw invalidRequestOption("file must be a Blob");
523
1035
  }
1036
+ if (value.size === 0) {
1037
+ throw invalidRequestOption("file must not be empty");
1038
+ }
524
1039
  return value;
525
1040
  }
526
1041
  function validateVoicePipelineAudio(value) {
@@ -555,12 +1070,6 @@ function validateMimeType(value, fallback = "audio/wav") {
555
1070
  }
556
1071
  return validateSdkHeader(trimmed, "mimeType", 255);
557
1072
  }
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
1073
  function validateMultipartFilename(value) {
565
1074
  if (typeof value !== "string") {
566
1075
  throw invalidRequestOption("filename must be a string");
@@ -585,6 +1094,73 @@ function validateMultipartFieldValue(value) {
585
1094
  }
586
1095
  return String(value);
587
1096
  }
1097
+ function validateTranscriptionResponseFormat(body) {
1098
+ const responseFormat = body.response_format;
1099
+ if (responseFormat !== undefined &&
1100
+ responseFormat !== "json" &&
1101
+ responseFormat !== "verbose_json") {
1102
+ throw invalidRequestOption("audio transcription response_format must be json or verbose_json for native SDK typed responses");
1103
+ }
1104
+ }
1105
+ function validateTranscriptionRequestKeys(request) {
1106
+ for (const key of Object.keys(request)) {
1107
+ if (!TRANSCRIPTION_REQUEST_KEYS.has(key)) {
1108
+ throw invalidRequestOption(`Unknown audio transcription request field: ${key}`);
1109
+ }
1110
+ }
1111
+ }
1112
+ /** `batches.create()` tests the destination before it answers, which can take 20 seconds. */
1113
+ const BATCH_CREATE_MIN_DEFAULT_TIMEOUT_MS = 30_000;
1114
+ function validateBatchCreateRequest(body) {
1115
+ validateNonEmptyStringField(body.input_url, "input_url");
1116
+ const destination = body.destination;
1117
+ if (!isPlainRecord(destination)) {
1118
+ throw invalidRequestOption("destination must be an object");
1119
+ }
1120
+ validateNonEmptyStringField(destination.type, "destination.type");
1121
+ validateNonEmptyStringField(destination.url, "destination.url");
1122
+ if (typeof body.max_cost_cents !== "number" || !Number.isSafeInteger(body.max_cost_cents)) {
1123
+ throw invalidRequestOption("max_cost_cents must be an integer");
1124
+ }
1125
+ if (body.window_hours !== undefined &&
1126
+ (typeof body.window_hours !== "number" || !Number.isSafeInteger(body.window_hours))) {
1127
+ throw invalidRequestOption("window_hours must be an integer");
1128
+ }
1129
+ if (body.name !== undefined && typeof body.name !== "string") {
1130
+ throw invalidRequestOption("name must be a string");
1131
+ }
1132
+ }
1133
+ function batchListQuery(params) {
1134
+ if (params === undefined)
1135
+ return "";
1136
+ if (!isPlainRecord(params)) {
1137
+ throw invalidRequestOption("batch list params must be an object");
1138
+ }
1139
+ for (const key of Object.keys(params)) {
1140
+ if (!BATCH_LIST_PARAM_KEYS.includes(key)) {
1141
+ throw invalidRequestOption(`Unknown batch list param: ${key}`);
1142
+ }
1143
+ }
1144
+ const query = new URLSearchParams();
1145
+ for (const key of BATCH_LIST_PARAM_KEYS) {
1146
+ const value = params[key];
1147
+ if (value === undefined)
1148
+ continue;
1149
+ if (key === "limit") {
1150
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
1151
+ throw invalidRequestOption("limit must be an integer");
1152
+ }
1153
+ query.set(key, String(value));
1154
+ continue;
1155
+ }
1156
+ query.set(key, validateNonEmptyStringField(value, key));
1157
+ }
1158
+ const text = query.toString();
1159
+ return text ? `?${text}` : "";
1160
+ }
1161
+ function batchPath(batchId, suffix = "") {
1162
+ return `/batches/${encodeURIComponent(validateSdkIdentifierHeader(batchId, "batchId"))}${suffix}`;
1163
+ }
588
1164
  const JSON_BODY_ERROR = "JSON request body must be JSON-serializable and contain only finite numbers";
589
1165
  function sanitizeJsonValue(value, seen = new WeakSet()) {
590
1166
  if (value === null || typeof value === "string" || typeof value === "boolean")
@@ -629,6 +1205,27 @@ function sanitizeJsonValue(value, seen = new WeakSet()) {
629
1205
  function encodeJsonBody(payload) {
630
1206
  return JSON.stringify(sanitizeJsonValue(payload));
631
1207
  }
1208
+ function mergeExtraJsonBody(payload, extraBody, typedKeys = new Set()) {
1209
+ if (extraBody === undefined)
1210
+ return payload;
1211
+ if (!isPlainRecord(extraBody)) {
1212
+ throw invalidRequestOption("extraBody must be an object");
1213
+ }
1214
+ if (!isPlainRecord(payload)) {
1215
+ throw invalidRequestOption("extraBody can only be used with JSON object request bodies");
1216
+ }
1217
+ const merged = { ...payload };
1218
+ for (const [key, value] of Object.entries(extraBody)) {
1219
+ if (!key.trim()) {
1220
+ throw invalidRequestOption("extraBody keys must be non-empty strings");
1221
+ }
1222
+ if (typedKeys.has(key) || key in payload) {
1223
+ throw invalidRequestOption(`extraBody must not override typed request field: ${key}`);
1224
+ }
1225
+ merged[key] = value;
1226
+ }
1227
+ return merged;
1228
+ }
632
1229
  function invalidRequestOption(message) {
633
1230
  return new RunInfraError(message, {
634
1231
  status: 0,
@@ -725,6 +1322,7 @@ const REQUEST_OPTION_KEYS = new Set([
725
1322
  "maxRetries",
726
1323
  "retryBaseMs",
727
1324
  "headers",
1325
+ "extraBody",
728
1326
  ]);
729
1327
  function validateRequestOptions(requestOptions) {
730
1328
  if (requestOptions === undefined)
@@ -785,13 +1383,26 @@ function isBrowserRuntime() {
785
1383
  prototype !== null &&
786
1384
  Object.prototype.isPrototypeOf.call(prototype, runtime.self);
787
1385
  }
788
- function retryAfterMs(response) {
1386
+ /** `Retry-After-Ms`: the wait in milliseconds, a plain non-negative number. */
1387
+ function retryAfterMsHeader(response) {
1388
+ const value = response.headers.get("retry-after-ms");
1389
+ if (!value)
1390
+ return null;
1391
+ const trimmed = value.trim();
1392
+ if (!/^[0-9]+(?:\.[0-9]+)?$/u.test(trimmed))
1393
+ return null;
1394
+ const milliseconds = Number(trimmed);
1395
+ return Number.isFinite(milliseconds) ? Math.ceil(milliseconds) : null;
1396
+ }
1397
+ /** `Retry-After`: whole seconds, or an HTTP date. */
1398
+ function retryAfterHeader(response) {
789
1399
  const value = response.headers.get("retry-after");
790
1400
  if (!value)
791
1401
  return null;
792
1402
  const trimmed = value.trim();
793
1403
  if (/^[0-9]+$/.test(trimmed)) {
794
1404
  const seconds = Number(trimmed);
1405
+ // A value above the largest safe integer names no wait: the SDK's own backoff applies.
795
1406
  if (Number.isSafeInteger(seconds))
796
1407
  return seconds * 1000;
797
1408
  return null;
@@ -803,32 +1414,80 @@ function retryAfterMs(response) {
803
1414
  return Math.max(0, dateMs - Date.now());
804
1415
  return null;
805
1416
  }
806
- function automaticRetryAfterMs(response) {
807
- const delay = retryAfterMs(response);
808
- if (delay === null || delay > MAX_AUTOMATIC_RETRY_AFTER_MS)
809
- return null;
810
- return delay;
1417
+ /**
1418
+ * The wait the API named with a response, in milliseconds. `Retry-After-Ms` is
1419
+ * read first, because it can name a wait shorter than a second; `Retry-After`
1420
+ * is read when the millisecond header is missing or malformed.
1421
+ */
1422
+ function retryAfterMs(response) {
1423
+ return retryAfterMsHeader(response) ?? retryAfterHeader(response);
1424
+ }
1425
+ /**
1426
+ * What the API said about asking again: the `x-should-retry` header, and
1427
+ * `retryable` inside the error object. An explicit `false` from either wins.
1428
+ * `undefined` when the API said nothing.
1429
+ */
1430
+ function retryMarker(response, bodyRetryable) {
1431
+ const header = response.headers.get("x-should-retry")?.trim().toLowerCase();
1432
+ const headerRetryable = header === "true" ? true : header === "false" ? false : undefined;
1433
+ if (headerRetryable === false || bodyRetryable === false)
1434
+ return false;
1435
+ if (headerRetryable === true || bodyRetryable === true)
1436
+ return true;
1437
+ return undefined;
811
1438
  }
812
- function retryDelayMs(attempt, baseMs, response) {
813
- if (response) {
814
- const retryAfter = automaticRetryAfterMs(response);
815
- if (retryAfter !== null)
816
- return retryAfter;
817
- }
1439
+ /** The SDK's own wait before it asks again when the API named none: exponential, with jitter, at most 30 seconds. */
1440
+ function backoffDelayMs(attempt, baseMs) {
818
1441
  if (baseMs <= 0)
819
1442
  return 0;
820
1443
  const exponential = baseMs * 2 ** Math.max(0, attempt - 1);
821
1444
  const jitter = Math.random() * baseMs;
822
1445
  return Math.min(30_000, exponential + jitter);
823
1446
  }
1447
+ /** The longest `Retry-After` a batch route's 503 is waited for. A longer wait is the caller's to plan. */
1448
+ const BATCH_MAX_AUTOMATIC_RETRY_AFTER_MS = 5_000;
1449
+ /**
1450
+ * Whether a failed response may be asked again, for a call that is safe to
1451
+ * send again. The API's own word decides when it gave one: `false` never,
1452
+ * `true` whatever the status. Without it the status decides. A 409 from a
1453
+ * batch route is always final.
1454
+ */
1455
+ function failedResponseMayBeAskedAgain(response, retryable, batch) {
1456
+ if (batch && response.status === 409)
1457
+ return false;
1458
+ if (retryable !== undefined)
1459
+ return retryable;
1460
+ return isRetryableStatus(response.status);
1461
+ }
1462
+ /**
1463
+ * The longest wait named by the API that the SDK sleeps for before it asks
1464
+ * again. A wait above it is raised at once with the wait on the error, so a
1465
+ * call never blocks for minutes and never asks again sooner than it was told.
1466
+ */
1467
+ function maxAutomaticRetryAfterMs(response, batch) {
1468
+ return batch && response.status === 503 ? BATCH_MAX_AUTOMATIC_RETRY_AFTER_MS : MAX_AUTOMATIC_RETRY_AFTER_MS;
1469
+ }
824
1470
  async function parseError(response) {
825
1471
  try {
826
1472
  const body = (await response.json());
1473
+ const error = body.error ?? {};
827
1474
  return {
828
- message: typeof body.error?.message === "string"
829
- ? body.error.message
1475
+ message: typeof error.message === "string"
1476
+ ? error.message
830
1477
  : `RunInfra request failed with status ${response.status}`,
831
- type: typeof body.error?.type === "string" ? body.error.type : "api_error",
1478
+ type: typeof error.type === "string" ? error.type : "api_error",
1479
+ ...(typeof error.code === "string" ? { code: error.code } : {}),
1480
+ ...(typeof error.param === "string" ? { param: error.param } : {}),
1481
+ ...(typeof error.reason === "string" ? { reason: error.reason } : {}),
1482
+ ...(typeof error.retryable === "boolean" ? { retryable: error.retryable } : {}),
1483
+ // Structured remediation fields the gateway ships on 402 insufficient_credits.
1484
+ ...(typeof error.current_balance_cents === "number" && Number.isFinite(error.current_balance_cents)
1485
+ ? { currentBalanceCents: error.current_balance_cents }
1486
+ : {}),
1487
+ ...(typeof error.required_cents === "number" && Number.isFinite(error.required_cents)
1488
+ ? { requiredCents: error.required_cents }
1489
+ : {}),
1490
+ ...(typeof error.topup_url === "string" ? { topupUrl: error.topup_url } : {}),
832
1491
  };
833
1492
  }
834
1493
  catch {
@@ -838,52 +1497,141 @@ async function parseError(response) {
838
1497
  };
839
1498
  }
840
1499
  }
1500
+ /**
1501
+ * Reads a failed response's error body, giving up when the call's own timeout
1502
+ * fires first. The body is read before the SDK decides whether to ask again,
1503
+ * because the API can mark a failure as retryable or not inside it.
1504
+ */
1505
+ async function parseErrorWithin(response, signal) {
1506
+ if (signal.aborted)
1507
+ throw new DOMException("The operation was aborted.", "AbortError");
1508
+ let onAbort;
1509
+ try {
1510
+ return await Promise.race([
1511
+ parseError(response),
1512
+ new Promise((_, reject) => {
1513
+ onAbort = () => reject(new DOMException("The operation was aborted.", "AbortError"));
1514
+ signal.addEventListener("abort", onAbort, { once: true });
1515
+ }),
1516
+ ]);
1517
+ }
1518
+ finally {
1519
+ if (onAbort)
1520
+ signal.removeEventListener("abort", onAbort);
1521
+ }
1522
+ }
841
1523
  async function discardResponseBody(response) {
842
1524
  try {
843
1525
  await response.body?.cancel();
844
1526
  }
845
1527
  catch {
846
- // Best-effort cleanup before retrying a failed response.
1528
+ // Best-effort cleanup: the body may already be read, locked or closed.
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Sets what an error carries beyond its class: the wait the API named, what
1533
+ * the API said about asking again, a batch refusal's cause word, and the
1534
+ * request id the SDK sent. Assigned after construction so no error class
1535
+ * changes its constructor.
1536
+ */
1537
+ function withErrorFacts(error, facts) {
1538
+ const target = error;
1539
+ if (facts.reason !== undefined)
1540
+ target.reason = facts.reason;
1541
+ if (facts.retryAfterMs !== undefined)
1542
+ target.retryAfterMs = facts.retryAfterMs;
1543
+ if (facts.retryable !== undefined)
1544
+ target.retryable = facts.retryable;
1545
+ if (facts.clientRequestId !== undefined)
1546
+ target.clientRequestId = facts.clientRequestId;
1547
+ return error;
1548
+ }
1549
+ /**
1550
+ * A batch route's refusal as the SDK's typed error. The class follows the HTTP
1551
+ * status as on every route, with one difference: only `model_not_sold` is a
1552
+ * `ModelNotFoundError` (an unknown batch id is a plain 404 `RunInfraError`
1553
+ * that keeps the gateway's own type).
1554
+ */
1555
+ function batchRefusalError(response, parsed, requestId) {
1556
+ const { message, type, code, param, currentBalanceCents, requiredCents, topupUrl } = parsed;
1557
+ const status = response.status;
1558
+ if (status === 401)
1559
+ return new AuthenticationError(message, status, requestId, code, param);
1560
+ if (status === 403) {
1561
+ return new PermissionDeniedError(message, status, requestId, code, param, type !== "api_error" ? type : "permission_denied");
1562
+ }
1563
+ if (status === 402) {
1564
+ return new InsufficientCreditsError(message, status, requestId, code, param, {
1565
+ currentBalanceCents,
1566
+ requiredCents,
1567
+ topupUrl,
1568
+ });
847
1569
  }
1570
+ if (status === 404 && code === "model_not_sold") {
1571
+ return new ModelNotFoundError(message, status, requestId, code, param);
1572
+ }
1573
+ if (status === 429)
1574
+ return new RateLimitError(message, status, requestId, undefined, code, param);
1575
+ return new RunInfraError(message, { status, type, requestId, code, param });
848
1576
  }
849
- async function raiseForStatus(response) {
850
- if (response.ok)
851
- return;
852
- const { message, type } = await parseError(response);
853
- const requestId = response.headers.get("x-request-id") ?? undefined;
1577
+ function routeError(response, parsed, requestId) {
1578
+ const { message, type, code, param, currentBalanceCents, requiredCents, topupUrl } = parsed;
854
1579
  if (response.status === 401)
855
- throw new AuthenticationError(message, response.status, requestId);
856
- if (response.status === 403)
857
- throw new PermissionDeniedError(message, response.status, requestId);
858
- if (response.status === 402)
859
- throw new InsufficientCreditsError(message, response.status, requestId);
1580
+ return new AuthenticationError(message, response.status, requestId, code, param);
1581
+ if (response.status === 403) {
1582
+ // Keep a more specific gateway discriminator (e.g. "byoc_plan_required")
1583
+ // on `.type` so callers can branch instead of regex-scraping the message.
1584
+ return new PermissionDeniedError(message, response.status, requestId, code, param, type !== "api_error" ? type : "permission_denied");
1585
+ }
1586
+ if (response.status === 402) {
1587
+ return new InsufficientCreditsError(message, response.status, requestId, code, param, {
1588
+ currentBalanceCents,
1589
+ requiredCents,
1590
+ topupUrl,
1591
+ });
1592
+ }
860
1593
  if (response.status === 404 || type === "model_not_found") {
861
- throw new ModelNotFoundError(message, response.status, requestId);
1594
+ return new ModelNotFoundError(message, response.status, requestId, code, param);
862
1595
  }
863
1596
  if (response.status === 429) {
864
- throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined);
1597
+ return new RateLimitError(message, response.status, requestId, undefined, code, param);
865
1598
  }
866
1599
  if (type === "deployment_error")
867
- throw new DeploymentError(message, response.status, requestId);
868
- throw new RunInfraError(message, { status: response.status, type, requestId });
1600
+ return new DeploymentError(message, response.status, requestId, code, param);
1601
+ return new RunInfraError(message, { status: response.status, type, requestId, code, param });
1602
+ }
1603
+ /**
1604
+ * A failed response as the SDK's typed error. Whatever its class and status,
1605
+ * the error keeps the wait the API named (`Retry-After-Ms`, else
1606
+ * `Retry-After`) and what the API said about asking again (`x-should-retry`,
1607
+ * `error.retryable`). A batch route's refusal also keeps its cause word.
1608
+ */
1609
+ function errorFromResponse(response, parsed, batch) {
1610
+ const requestId = response.headers.get("x-request-id") ?? undefined;
1611
+ const error = batch ? batchRefusalError(response, parsed, requestId) : routeError(response, parsed, requestId);
1612
+ return withErrorFacts(error, {
1613
+ reason: batch ? parsed.reason : undefined,
1614
+ retryAfterMs: retryAfterMs(response) ?? undefined,
1615
+ retryable: retryMarker(response, parsed.retryable),
1616
+ });
1617
+ }
1618
+ /** Whether the response says it is a replay: the answer to a call that repeats an `Idempotency-Key` already answered. */
1619
+ function isIdempotentReplay(response) {
1620
+ return response.headers.get("x-runinfra-idempotent-replay")?.trim().toLowerCase() === "true";
869
1621
  }
870
- async function parseJsonResponse(response) {
1622
+ /**
1623
+ * A parsed JSON answer as the SDK returns it: the object, with `_request_id`
1624
+ * and `_idempotent_replay` when the response headers carry them. An answer
1625
+ * that is not an object is a shape error.
1626
+ */
1627
+ function jsonAnswer(payload, response) {
871
1628
  const requestId = response.headers.get("x-request-id") ?? undefined;
872
- let payload;
873
- try {
874
- payload = await response.json();
875
- }
876
- 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 };
884
- }
885
1629
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
886
- return payload;
1630
+ return {
1631
+ ...payload,
1632
+ ...(requestId ? { _request_id: requestId } : {}),
1633
+ ...(isIdempotentReplay(response) ? { _idempotent_replay: true } : {}),
1634
+ };
887
1635
  }
888
1636
  throw new RunInfraError(`RunInfra JSON response shape error: expected object, got ${jsonPayloadKind(payload)}.`, {
889
1637
  status: response.status,
@@ -891,6 +1639,17 @@ async function parseJsonResponse(response) {
891
1639
  requestId,
892
1640
  });
893
1641
  }
1642
+ async function parseJsonResponse(response, sensitiveValues = []) {
1643
+ const requestId = response.headers.get("x-request-id") ?? undefined;
1644
+ let payload;
1645
+ try {
1646
+ payload = await response.json();
1647
+ }
1648
+ catch (error) {
1649
+ throw new ResponseBodyReadError(normalizeTransportError(error, requestId, sensitiveValues));
1650
+ }
1651
+ return jsonAnswer(payload, response);
1652
+ }
894
1653
  function jsonPayloadKind(payload) {
895
1654
  if (payload === null)
896
1655
  return "null";
@@ -906,19 +1665,117 @@ class ResponseBodyReadError extends Error {
906
1665
  this.error = error;
907
1666
  }
908
1667
  }
909
- function normalizeTransportError(error, requestId) {
1668
+ function redactSensitiveValues(message, sensitiveValues = []) {
1669
+ let redacted = message;
1670
+ for (const value of sensitiveValues) {
1671
+ if (value)
1672
+ redacted = redacted.split(value).join("[redacted]");
1673
+ }
1674
+ return redacted;
1675
+ }
1676
+ function redactRunInfraError(error, sensitiveValues) {
1677
+ const redacted = redactedRunInfraErrorCopy(error, sensitiveValues);
1678
+ // The wait, the retry marker, a batch refusal's cause and the request id the SDK sent ride every error
1679
+ // class; the copy rebuilds each class from its own constructor, which names none of them for most.
1680
+ return withErrorFacts(redacted, {
1681
+ reason: error.reason === undefined ? undefined : redactSensitiveValues(error.reason, sensitiveValues),
1682
+ retryAfterMs: redacted.retryAfterMs === undefined ? error.retryAfterMs : undefined,
1683
+ retryable: redacted.retryable === undefined ? error.retryable : undefined,
1684
+ clientRequestId: redacted.clientRequestId === undefined ? error.clientRequestId : undefined,
1685
+ });
1686
+ }
1687
+ function redactedRunInfraErrorCopy(error, sensitiveValues) {
1688
+ const message = redactSensitiveValues(error.message, sensitiveValues);
1689
+ const code = error.code === undefined ? undefined : redactSensitiveValues(error.code, sensitiveValues);
1690
+ const param = error.param === undefined ? undefined : redactSensitiveValues(error.param, sensitiveValues);
1691
+ if (error instanceof AuthenticationError) {
1692
+ return new AuthenticationError(message, error.status, error.requestId, code, param);
1693
+ }
1694
+ if (error instanceof PermissionDeniedError) {
1695
+ // Preserve the gateway discriminator (e.g. "byoc_plan_required") through redaction.
1696
+ return new PermissionDeniedError(message, error.status, error.requestId, code, param, error.type);
1697
+ }
1698
+ if (error instanceof RateLimitError) {
1699
+ return new RateLimitError(message, error.status, error.requestId, error.retryAfterMs, code, param);
1700
+ }
1701
+ if (error instanceof InsufficientCreditsError) {
1702
+ // Carry the structured top-up fields through redaction (they hold no secrets).
1703
+ return new InsufficientCreditsError(message, error.status, error.requestId, code, param, {
1704
+ currentBalanceCents: error.currentBalanceCents,
1705
+ requiredCents: error.requiredCents,
1706
+ topupUrl: error.topupUrl,
1707
+ });
1708
+ }
1709
+ if (error instanceof DeploymentError) {
1710
+ return new DeploymentError(message, error.status, error.requestId, code, param);
1711
+ }
1712
+ if (error instanceof ModelNotFoundError) {
1713
+ return new ModelNotFoundError(message, error.status, error.requestId, code, param);
1714
+ }
1715
+ if (error instanceof RunInfraTimeoutError)
1716
+ return new RunInfraTimeoutError(message, error.requestId);
1717
+ if (error instanceof RunInfraConnectionError)
1718
+ return new RunInfraConnectionError(message, error.requestId);
1719
+ if (error instanceof RunInfraStreamParseError)
1720
+ return new RunInfraStreamParseError(message, error.requestId);
1721
+ if (error instanceof RunInfraStreamIncompleteError) {
1722
+ return new RunInfraStreamIncompleteError(message, error.requestId);
1723
+ }
1724
+ if (error instanceof RunInfraStreamError) {
1725
+ return new RunInfraStreamError(message, { type: error.type, requestId: error.requestId, code, param });
1726
+ }
1727
+ if (error instanceof UnsupportedOperationError)
1728
+ return new UnsupportedOperationError(message);
1729
+ if (error instanceof WebhookVerificationError)
1730
+ return new WebhookVerificationError(message);
1731
+ return new RunInfraError(message, {
1732
+ status: error.status,
1733
+ type: error.type,
1734
+ requestId: error.requestId,
1735
+ retryAfterMs: error.retryAfterMs,
1736
+ code,
1737
+ param,
1738
+ });
1739
+ }
1740
+ function normalizeTransportError(error, requestId, sensitiveValues = []) {
910
1741
  if (error instanceof RunInfraError)
911
- return error;
1742
+ return redactRunInfraError(error, sensitiveValues);
912
1743
  if (error instanceof DOMException &&
913
1744
  error.name === "AbortError") {
914
- return new RunInfraTimeoutError(error.message, requestId);
1745
+ return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
915
1746
  }
916
1747
  if (error instanceof Error && error.name === "AbortError") {
917
- return new RunInfraTimeoutError(error.message, requestId);
1748
+ return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
1749
+ }
1750
+ // The runtime's fetch ran out of its own time for the response headers or the body. The request was sent,
1751
+ // so this is a timeout like the SDK's own and never a connection failure that is sent again. A connect
1752
+ // timeout is not one of these: nothing was sent, so it stays a connection failure.
1753
+ const runtimeCode = runtimeFetchFailureCode(error);
1754
+ if (runtimeCode === "UND_ERR_HEADERS_TIMEOUT") {
1755
+ return new RunInfraTimeoutError("RunInfra request timed out: the runtime's fetch stopped waiting for the response headers", requestId);
1756
+ }
1757
+ if (runtimeCode === "UND_ERR_BODY_TIMEOUT") {
1758
+ return new RunInfraTimeoutError("RunInfra request timed out: the runtime's fetch stopped waiting for the response body", requestId);
918
1759
  }
919
- const message = error instanceof Error ? error.message : String(error);
1760
+ const message = redactSensitiveValues(error instanceof Error ? error.message : String(error), sensitiveValues);
920
1761
  return new RunInfraConnectionError(message, requestId);
921
1762
  }
1763
+ /**
1764
+ * The code of a failure the runtime's `fetch` reports, when it names one.
1765
+ * Node's built-in `fetch` rejects with a `TypeError` (`fetch failed`, or
1766
+ * `terminated` once the body had begun) and names the code on `error.cause`.
1767
+ */
1768
+ function runtimeFetchFailureCode(error) {
1769
+ if (typeof error !== "object" || error === null)
1770
+ return undefined;
1771
+ const { code, cause } = error;
1772
+ if (typeof code === "string")
1773
+ return code;
1774
+ if (typeof cause !== "object" || cause === null)
1775
+ return undefined;
1776
+ const causeCode = cause.code;
1777
+ return typeof causeCode === "string" ? causeCode : undefined;
1778
+ }
922
1779
  export class RunInfra {
923
1780
  chat;
924
1781
  embeddings;
@@ -926,28 +1783,44 @@ export class RunInfra {
926
1783
  /**
927
1784
  * Audio surfaces (text-to-speech + speech-to-text).
928
1785
  *
929
- * @experimental As of v0.1.3, these methods have NOT been verified end-to-end
930
- * against a live deployed pipeline in our canary suite. The HTTP envelope
1786
+ * Preview helpers for deployed RunInfra audio routes. The HTTP envelope
931
1787
  * matches the OpenAI Audio API contract and the request/response shapes are
932
- * stable, but you should test against your own deployed model before using
933
- * in production. Live-canary verification is tracked for v1.0.0 GA.
1788
+ * stable. Supported voices, reference-audio modes, and response formats are
1789
+ * deployment-specific.
934
1790
  */
935
1791
  audio;
936
1792
  models;
937
1793
  /**
938
1794
  * Image generation surface.
939
1795
  *
940
- * @experimental As of v0.1.3, this method has NOT been verified end-to-end
941
- * against a live deployed pipeline in our canary suite. The HTTP envelope
942
- * matches the OpenAI Images API contract, but you should test against your
943
- * own deployed model before using in production. Live-canary verification
944
- * is tracked for v1.0.0 GA.
1796
+ * Preview helper for deployed RunInfra image routes. The HTTP envelope
1797
+ * matches the OpenAI Images API contract. Supported size, response format,
1798
+ * quality, style, and user fields depend on the selected deployment.
945
1799
  */
946
1800
  images;
1801
+ /**
1802
+ * Batch jobs.
1803
+ *
1804
+ * Preview. A job takes a JSONL file of chat completion requests and posts
1805
+ * each answer, signed, to your webhook address. A job has a window of 24
1806
+ * hours. Lines run when the model has spare capacity. A line the job has
1807
+ * not run when its window ends is counted `expired` and is not charged. Use
1808
+ * a workspace-scoped key; verify deliveries with `verifyBatchDelivery`.
1809
+ */
1810
+ batches;
947
1811
  webhooks;
1812
+ /**
1813
+ * Voice pipeline surface.
1814
+ *
1815
+ * Preview helper for co-located voice pipelines. It requires a
1816
+ * pipeline-scoped client and posts binary audio to `/pipeline`; transcript
1817
+ * and response behavior depends on the selected deployment.
1818
+ */
948
1819
  voice;
949
1820
  apiKey;
950
1821
  baseURL;
1822
+ hasPipelineScope;
1823
+ /** The caller's own client timeout. Left unset, each call uses the default of its kind. */
951
1824
  timeoutMs;
952
1825
  maxRetries;
953
1826
  retryBaseMs;
@@ -969,8 +1842,12 @@ export class RunInfra {
969
1842
  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
1843
  }
971
1844
  this.apiKey = validatedApiKey;
972
- this.baseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
973
- this.timeoutMs = validatePositiveNumber(options.timeoutMs ?? 120_000, "timeoutMs");
1845
+ const normalizedBaseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
1846
+ this.baseURL = normalizedBaseURL;
1847
+ this.hasPipelineScope = Boolean(options.pipelineId) || baseUrlLooksPipelineScoped(normalizedBaseURL);
1848
+ this.timeoutMs = options.timeoutMs === undefined || options.timeoutMs === null
1849
+ ? undefined
1850
+ : validatePositiveNumber(options.timeoutMs, "timeoutMs");
974
1851
  this.maxRetries = validateNonNegativeInteger(options.maxRetries ?? 2, "maxRetries");
975
1852
  this.retryBaseMs = validateNonNegativeNumber(options.retryBaseMs ?? 250, "retryBaseMs");
976
1853
  if (options.fetch !== undefined && typeof options.fetch !== "function") {
@@ -978,12 +1855,15 @@ export class RunInfra {
978
1855
  }
979
1856
  this.fetcher = options.fetch ?? fetch;
980
1857
  const createChatCompletion = ((request, requestOptions) => {
1858
+ validateRequestFields(request, CHAT_COMPLETION_REQUEST_KEYS, "chat completion");
981
1859
  const body = withValidatedModel(request);
982
1860
  validateChatMessages(body.messages);
983
1861
  return this.request("/chat/completions", {
984
1862
  method: "POST",
985
1863
  body,
1864
+ typedBodyKeys: CHAT_COMPLETION_EXTRA_BODY_CLOSED_KEYS,
986
1865
  stream: body.stream === true,
1866
+ idempotentReplaySafe: true,
987
1867
  }, requestOptions);
988
1868
  });
989
1869
  this.chat = {
@@ -993,49 +1873,58 @@ export class RunInfra {
993
1873
  };
994
1874
  this.embeddings = {
995
1875
  create: (request, requestOptions) => {
1876
+ validateRequestFields(request, EMBEDDING_REQUEST_KEYS, "embedding");
996
1877
  const body = withValidatedModel(request);
997
1878
  validateEmbeddingInput(body.input);
1879
+ validateEmbeddingResponseOptions(body);
998
1880
  return this.request("/embeddings", {
999
1881
  method: "POST",
1000
1882
  body,
1883
+ typedBodyKeys: EMBEDDING_REQUEST_KEYS,
1001
1884
  }, requestOptions);
1002
1885
  },
1003
1886
  };
1004
1887
  this.responses = {
1005
1888
  create: ((request, requestOptions) => {
1889
+ validateRequestFields(request, RESPONSES_CREATE_REQUEST_KEYS, "responses");
1006
1890
  const body = withValidatedModel(request);
1007
1891
  validateResponsesInput(body.input);
1008
1892
  return this.request("/responses", {
1009
1893
  method: "POST",
1010
1894
  body,
1895
+ typedBodyKeys: RESPONSES_CREATE_REQUEST_KEYS,
1011
1896
  stream: body.stream === true,
1897
+ idempotentReplaySafe: true,
1012
1898
  }, requestOptions);
1013
1899
  }),
1014
1900
  };
1015
1901
  this.audio = {
1016
1902
  speech: {
1017
1903
  create: async (request, requestOptions) => {
1904
+ validateRequestFields(request, SPEECH_REQUEST_KEYS, "audio speech");
1018
1905
  const body = withValidatedModel(request);
1019
1906
  validateNonEmptyStringField(body.input, "input");
1020
1907
  validateSpeechReference(body);
1021
- const response = await this.rawRequest("/audio/speech", {
1908
+ // The answer is handed the X-Client-Request-Id the SDK sent, so a timeout while its body is read can name it.
1909
+ return this.sendWithRetry("/audio/speech", {
1022
1910
  method: "POST",
1023
1911
  body,
1912
+ typedBodyKeys: SPEECH_REQUEST_KEYS,
1024
1913
  binary: true,
1025
- }, requestOptions);
1026
- return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions));
1914
+ }, requestOptions, async (response, sensitiveValues, clientRequestId) => new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions), sensitiveValues, clientRequestId));
1027
1915
  },
1028
1916
  },
1029
1917
  transcriptions: {
1030
1918
  create: (request, requestOptions) => {
1919
+ validateTranscriptionRequestKeys(request);
1920
+ validateTranscriptionResponseFormat(request);
1031
1921
  const formData = new FormData();
1032
1922
  formData.append("model", validateSdkModel(request.model));
1033
1923
  formData.append("file", validateBlobFile(request.file), validateMultipartFilename(request.filename ?? "audio.wav"));
1034
- for (const [key, value] of Object.entries(request)) {
1035
- if (key === "model" || key === "file" || key === "filename")
1036
- continue;
1924
+ for (const key of ["language", "prompt", "response_format", "temperature"]) {
1925
+ const value = request[key];
1037
1926
  if (value !== undefined && value !== null) {
1038
- formData.append(validateMultipartFieldName(key), validateMultipartFieldValue(value));
1927
+ formData.append(key, validateMultipartFieldValue(value));
1039
1928
  }
1040
1929
  }
1041
1930
  return this.request("/audio/transcriptions", {
@@ -1051,23 +1940,45 @@ export class RunInfra {
1051
1940
  };
1052
1941
  this.images = {
1053
1942
  generate: (request, requestOptions) => {
1943
+ validateRequestFields(request, IMAGE_GENERATE_REQUEST_KEYS, "image generation");
1054
1944
  const body = withValidatedModel(request);
1055
1945
  validateNonEmptyStringField(body.prompt, "prompt");
1056
1946
  return this.request("/images/generations", {
1057
1947
  method: "POST",
1058
1948
  body,
1949
+ typedBodyKeys: IMAGE_GENERATE_REQUEST_KEYS,
1950
+ }, requestOptions);
1951
+ },
1952
+ };
1953
+ this.batches = {
1954
+ create: async (request, requestOptions) => {
1955
+ validateRequestFields(request, BATCH_CREATE_REQUEST_KEYS, "batch");
1956
+ const body = withValidatedModel(request);
1957
+ validateBatchCreateRequest(body);
1958
+ return this.request("/batches", {
1959
+ method: "POST",
1960
+ body,
1961
+ typedBodyKeys: BATCH_CREATE_REQUEST_KEYS,
1962
+ idempotentReplaySafe: true,
1963
+ batch: true,
1964
+ minDefaultTimeoutMs: BATCH_CREATE_MIN_DEFAULT_TIMEOUT_MS,
1059
1965
  }, requestOptions);
1060
1966
  },
1967
+ list: async (params, requestOptions) => this.request(`/batches${batchListQuery(params)}`, { method: "GET", batch: true }, requestOptions),
1968
+ retrieve: async (batchId, requestOptions) => this.request(batchPath(batchId), { method: "GET", batch: true }, requestOptions),
1969
+ cancel: async (batchId, requestOptions) => this.request(batchPath(batchId, "/cancel"), { method: "POST", batch: true }, requestOptions),
1061
1970
  };
1062
1971
  this.webhooks = {
1063
1972
  verifySignature: verifyWebhookSignature,
1064
1973
  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
1974
  };
1068
1975
  this.voice = {
1069
1976
  pipeline: {
1070
1977
  create: (request, requestOptions) => {
1978
+ if (!this.hasPipelineScope) {
1979
+ throw invalidRequestOption("voice pipeline requests require pipelineId or a pipeline-scoped baseURL");
1980
+ }
1981
+ validateRequestFields(request, VOICE_PIPELINE_REQUEST_KEYS, "voice pipeline");
1071
1982
  const audio = validateVoicePipelineAudio(request?.audio);
1072
1983
  return this.request("/pipeline", {
1073
1984
  method: "POST",
@@ -1081,17 +1992,22 @@ export class RunInfra {
1081
1992
  }
1082
1993
  async request(path, options, requestOptions) {
1083
1994
  if (options.stream) {
1084
- const response = await this.rawRequest(path, options, requestOptions);
1085
- return new RunInfraStream(response, this.requestTimeoutMs(requestOptions));
1995
+ // The stream is handed the X-Client-Request-Id the SDK sent, so a timeout while it is read can name it.
1996
+ return this.sendWithRetry(path, options, requestOptions, async (response, sensitiveValues, clientRequestId) => new RunInfraStream(response, this.requestTimeoutMs(requestOptions, true), sensitiveValues, clientRequestId));
1086
1997
  }
1087
1998
  return this.sendWithRetry(path, options, requestOptions, (parseJsonResponse));
1088
1999
  }
1089
- requestTimeoutMs(requestOptions = {}) {
2000
+ /**
2001
+ * The timeout of one call. The caller's own setting wins: the call's
2002
+ * `timeoutMs`, else the client's. With neither, a non-streamed call is given
2003
+ * 750 seconds for the whole call, and a streamed call 190 seconds to its
2004
+ * response headers and to each later read. `minDefaultTimeoutMs` is the
2005
+ * least a call uses when the caller names no timeout for that call.
2006
+ */
2007
+ requestTimeoutMs(requestOptions = {}, stream = false, minDefaultTimeoutMs = 0) {
1090
2008
  const validatedRequestOptions = validateRequestOptions(requestOptions);
1091
- return validatePositiveNumber(validatedRequestOptions.timeoutMs ?? this.timeoutMs, "timeoutMs");
1092
- }
1093
- async rawRequest(path, options, requestOptions = {}) {
1094
- return this.sendWithRetry(path, options, requestOptions, async (response) => response);
2009
+ const defaultTimeoutMs = stream ? DEFAULT_STREAM_TIMEOUT_MS : DEFAULT_TIMEOUT_MS;
2010
+ return validatePositiveNumber(validatedRequestOptions.timeoutMs ?? Math.max(this.timeoutMs ?? defaultTimeoutMs, minDefaultTimeoutMs), "timeoutMs");
1095
2011
  }
1096
2012
  async sendWithRetry(path, options, requestOptions = {}, consumeResponse) {
1097
2013
  const validatedRequestOptions = validateRequestOptions(requestOptions);
@@ -1108,9 +2024,15 @@ export class RunInfra {
1108
2024
  }
1109
2025
  let body;
1110
2026
  if (options.formData) {
2027
+ if (validatedRequestOptions.extraBody !== undefined) {
2028
+ throw invalidRequestOption("extraBody can only be used with JSON request bodies");
2029
+ }
1111
2030
  body = options.formData;
1112
2031
  }
1113
2032
  else if (options.rawBody !== undefined) {
2033
+ if (validatedRequestOptions.extraBody !== undefined) {
2034
+ throw invalidRequestOption("extraBody can only be used with JSON request bodies");
2035
+ }
1114
2036
  body = options.rawBody;
1115
2037
  headers["Content-Type"] = options.rawContentType ?? "application/octet-stream";
1116
2038
  if (options.accept)
@@ -1118,19 +2040,29 @@ export class RunInfra {
1118
2040
  }
1119
2041
  else if (options.body !== undefined) {
1120
2042
  headers["Content-Type"] = "application/json";
1121
- body = encodeJsonBody(options.body);
2043
+ body = encodeJsonBody(mergeExtraJsonBody(options.body, validatedRequestOptions.extraBody, options.typedBodyKeys));
2044
+ }
2045
+ else if (validatedRequestOptions.extraBody !== undefined) {
2046
+ throw invalidRequestOption("extraBody can only be used with JSON request bodies");
1122
2047
  }
1123
2048
  let attempt = 0;
1124
2049
  const method = options.method ?? "POST";
1125
- const hasReplayableJsonBody = options.body !== undefined && !options.stream && !options.binary && !options.formData;
2050
+ const hasReplayableJsonBody = options.body !== undefined &&
2051
+ !options.stream &&
2052
+ !options.binary &&
2053
+ !options.formData &&
2054
+ options.idempotentReplaySafe === true;
1126
2055
  const canRetry = method === "GET" ||
1127
2056
  (Boolean(validatedRequestOptions.idempotencyKey) && hasReplayableJsonBody);
1128
2057
  const maxRetries = validateNonNegativeInteger(validatedRequestOptions.maxRetries ?? this.maxRetries, "maxRetries");
1129
2058
  const retryBaseMs = validateNonNegativeNumber(validatedRequestOptions.retryBaseMs ?? this.retryBaseMs, "retryBaseMs");
1130
- const timeoutMs = validatePositiveNumber(validatedRequestOptions.timeoutMs ?? this.timeoutMs, "timeoutMs");
2059
+ const timeoutMs = this.requestTimeoutMs(validatedRequestOptions, options.stream === true, options.minDefaultTimeoutMs);
2060
+ const batch = options.batch === true;
1131
2061
  while (true) {
1132
2062
  const controller = new AbortController();
1133
2063
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
2064
+ let serverRequestId;
2065
+ let waitMs;
1134
2066
  try {
1135
2067
  const response = await this.fetcher(`${this.baseURL}${path}`, {
1136
2068
  method,
@@ -1138,37 +2070,63 @@ export class RunInfra {
1138
2070
  body,
1139
2071
  signal: controller.signal,
1140
2072
  });
1141
- if (canRetry &&
1142
- !response.ok &&
1143
- isRetryableStatus(response.status) &&
1144
- attempt < maxRetries) {
1145
- attempt += 1;
1146
- await discardResponseBody(response);
1147
- await sleep(retryDelayMs(attempt, retryBaseMs, response));
1148
- continue;
2073
+ serverRequestId = response.headers.get("x-request-id") ?? undefined;
2074
+ if (response.ok)
2075
+ return await consumeResponse(response, [this.apiKey], clientRequestId);
2076
+ // The error body is read before the SDK decides anything: the API can say inside it whether asking again helps.
2077
+ const parsed = await parseErrorWithin(response, controller.signal);
2078
+ await discardResponseBody(response);
2079
+ // The timer may fire just as the body read ends: a call that ran out of time is not judged by a body cut short.
2080
+ if (controller.signal.aborted)
2081
+ throw new DOMException("The operation was aborted.", "AbortError");
2082
+ const failure = errorFromResponse(response, parsed, batch);
2083
+ if (!canRetry ||
2084
+ attempt >= maxRetries ||
2085
+ !failedResponseMayBeAskedAgain(response, failure.retryable, batch)) {
2086
+ throw failure;
1149
2087
  }
1150
- await raiseForStatus(response);
1151
- return await consumeResponse(response);
2088
+ // A wait longer than the SDK sleeps for is the caller's to plan: raise now, with the wait on the error.
2089
+ if (failure.retryAfterMs !== undefined &&
2090
+ failure.retryAfterMs > maxAutomaticRetryAfterMs(response, batch)) {
2091
+ throw failure;
2092
+ }
2093
+ waitMs = failure.retryAfterMs ?? backoffDelayMs(attempt + 1, retryBaseMs);
1152
2094
  }
1153
2095
  catch (error) {
2096
+ // Whether the SDK's own timer ended this attempt.
2097
+ const timedOut = controller.signal.aborted;
2098
+ // A call that ran out of time is never sent again: the API may still be working on it, and a second
2099
+ // send could run and charge it twice. The timeout names the request id the SDK sent.
2100
+ const asTimeout = (failure) => withErrorFacts(failure instanceof RunInfraTimeoutError
2101
+ ? failure
2102
+ : new RunInfraTimeoutError(undefined, failure.requestId ?? serverRequestId), { clientRequestId });
1154
2103
  if (error instanceof ResponseBodyReadError) {
1155
- if (canRetry && attempt < maxRetries) {
1156
- attempt += 1;
1157
- await sleep(retryDelayMs(attempt, retryBaseMs));
1158
- continue;
1159
- }
1160
- throw error.error;
2104
+ const bodyError = normalizeTransportError(error.error, error.error.requestId, [this.apiKey]);
2105
+ if (timedOut || bodyError instanceof RunInfraTimeoutError)
2106
+ throw asTimeout(bodyError);
2107
+ if (!canRetry || attempt >= maxRetries)
2108
+ throw bodyError;
2109
+ waitMs = backoffDelayMs(attempt + 1, retryBaseMs);
2110
+ }
2111
+ else if (error instanceof RunInfraError) {
2112
+ // The API's own answer, or an error the injected fetch raised as the SDK's: final either way.
2113
+ const raised = normalizeTransportError(error, error.requestId, [this.apiKey]);
2114
+ throw raised instanceof RunInfraTimeoutError ? asTimeout(raised) : raised;
2115
+ }
2116
+ else {
2117
+ const transportError = normalizeTransportError(error, serverRequestId, [this.apiKey]);
2118
+ if (timedOut || transportError instanceof RunInfraTimeoutError)
2119
+ throw asTimeout(transportError);
2120
+ if (!canRetry || attempt >= maxRetries)
2121
+ throw transportError;
2122
+ waitMs = backoffDelayMs(attempt + 1, retryBaseMs);
1161
2123
  }
1162
- if (error instanceof RunInfraError)
1163
- throw error;
1164
- if (!canRetry || attempt >= maxRetries)
1165
- throw normalizeTransportError(error);
1166
- attempt += 1;
1167
- await sleep(retryDelayMs(attempt, retryBaseMs));
1168
2124
  }
1169
2125
  finally {
1170
2126
  clearTimeout(timeout);
1171
2127
  }
2128
+ attempt += 1;
2129
+ await sleep(waitMs);
1172
2130
  }
1173
2131
  }
1174
2132
  }