@runinfra/sdk 0.2.0 → 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,7 +1,29 @@
1
1
  import { createHmac, timingSafeEqual } from "node:crypto";
2
- export const RUNINFRA_SDK_VERSION = "0.2.0";
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;
4
- const CHAT_COMPLETION_REQUEST_KEYS = new Set([
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([
5
27
  "model",
6
28
  "messages",
7
29
  "stream",
@@ -22,6 +44,36 @@ const CHAT_COMPLETION_REQUEST_KEYS = new Set([
22
44
  "logprobs",
23
45
  "top_logprobs",
24
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
+ ]);
25
77
  const RESPONSES_CREATE_REQUEST_KEYS = new Set([
26
78
  "model",
27
79
  "input",
@@ -74,13 +126,45 @@ const VOICE_PIPELINE_REQUEST_KEYS = new Set([
74
126
  "audio",
75
127
  "mimeType",
76
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"];
77
138
  export class RunInfraError extends Error {
78
139
  status;
79
140
  type;
80
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
+ */
81
147
  retryAfterMs;
82
148
  code;
83
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;
84
168
  constructor(message, input) {
85
169
  super(message);
86
170
  this.name = "RunInfraError";
@@ -90,6 +174,9 @@ export class RunInfraError extends Error {
90
174
  this.retryAfterMs = input.retryAfterMs;
91
175
  this.code = input.code;
92
176
  this.param = input.param;
177
+ this.reason = input.reason;
178
+ this.retryable = input.retryable;
179
+ this.clientRequestId = input.clientRequestId;
93
180
  }
94
181
  }
95
182
  export class AuthenticationError extends RunInfraError {
@@ -115,6 +202,12 @@ export class RateLimitError extends RunInfraError {
115
202
  this.name = "RateLimitError";
116
203
  }
117
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
+ */
118
211
  export class InsufficientCreditsError extends RunInfraError {
119
212
  /** Remaining workspace balance in cents, when the gateway reports it. */
120
213
  currentBalanceCents;
@@ -142,9 +235,16 @@ export class ModelNotFoundError extends RunInfraError {
142
235
  this.name = "ModelNotFoundError";
143
236
  }
144
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
+ */
145
245
  export class RunInfraTimeoutError extends RunInfraError {
146
- constructor(message = "RunInfra request timed out", requestId) {
147
- 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 });
148
248
  this.name = "RunInfraTimeoutError";
149
249
  }
150
250
  }
@@ -160,6 +260,32 @@ export class RunInfraStreamParseError extends RunInfraError {
160
260
  this.name = "RunInfraStreamParseError";
161
261
  }
162
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
+ }
163
289
  export class UnsupportedOperationError extends RunInfraError {
164
290
  constructor(message) {
165
291
  super(message, { status: 400, type: "unsupported_operation" });
@@ -262,18 +388,168 @@ export function constructWebhookEvent(options) {
262
388
  throw new WebhookVerificationError("Webhook payload must be valid JSON.");
263
389
  }
264
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
+ }
265
538
  export class RunInfraAudioResponse {
266
539
  contentType;
267
540
  requestId;
268
541
  response;
269
542
  readTimeoutMs;
270
543
  sensitiveValues;
271
- constructor(response, readTimeoutMs, 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) {
272
547
  this.response = response;
273
548
  this.contentType = response.headers.get("content-type") ?? "application/octet-stream";
274
549
  this.requestId = response.headers.get("x-request-id") ?? undefined;
275
550
  this.readTimeoutMs = readTimeoutMs;
276
551
  this.sensitiveValues = sensitiveValues;
552
+ this.clientRequestId = clientRequestId;
277
553
  }
278
554
  arrayBuffer() {
279
555
  return this.readBody(() => this.response.arrayBuffer(), "RunInfra audio response timed out while reading body");
@@ -292,7 +568,7 @@ export class RunInfraAudioResponse {
292
568
  return await bodyRead;
293
569
  }
294
570
  catch (error) {
295
- throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
571
+ throw this.bodyReadFailure(error);
296
572
  }
297
573
  }
298
574
  let timeout;
@@ -308,44 +584,126 @@ export class RunInfraAudioResponse {
308
584
  ]);
309
585
  }
310
586
  catch (error) {
311
- throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
587
+ throw this.bodyReadFailure(error);
312
588
  }
313
589
  finally {
314
590
  if (timeout !== undefined)
315
591
  clearTimeout(timeout);
316
592
  }
317
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
+ });
318
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
+ */
319
660
  export class RunInfraStream {
320
661
  response;
321
662
  requestId;
322
663
  readTimeoutMs;
323
664
  sensitiveValues;
324
- constructor(response, readTimeoutMs, 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) {
325
668
  this.response = response;
326
669
  this.requestId = response.headers.get("x-request-id") ?? undefined;
327
670
  this.readTimeoutMs = readTimeoutMs;
328
671
  this.sensitiveValues = sensitiveValues;
672
+ this.clientRequestId = clientRequestId;
329
673
  }
330
674
  async *[Symbol.asyncIterator]() {
331
- if (!this.response.body)
332
- return;
675
+ if (!this.response.body) {
676
+ throw new RunInfraStreamIncompleteError(undefined, this.requestId);
677
+ }
333
678
  const reader = this.response.body.getReader();
334
679
  const decoder = new TextDecoder();
335
680
  let buffer = "";
336
681
  let dataLines = [];
337
682
  let readerDone = false;
683
+ // Whether the end marker arrived: `[DONE]`, or a Responses `response.completed` event.
684
+ let completed = false;
338
685
  const dispatchEvent = () => {
339
686
  const payload = dataLines.join("\n").trim();
340
687
  dataLines = [];
341
- if (!payload || payload === "[DONE]")
688
+ if (!payload)
342
689
  return null;
690
+ if (payload === "[DONE]") {
691
+ completed = true;
692
+ return null;
693
+ }
694
+ let event;
343
695
  try {
344
- return JSON.parse(payload);
696
+ event = JSON.parse(payload);
345
697
  }
346
698
  catch {
347
699
  throw new RunInfraStreamParseError(undefined, this.requestId);
348
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;
349
707
  };
350
708
  const processLine = (line) => {
351
709
  const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
@@ -382,6 +740,27 @@ export class RunInfraStream {
382
740
  }
383
741
  };
384
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
+ }
385
764
  while (true) {
386
765
  const { done, value } = await readChunk();
387
766
  if (done) {
@@ -398,19 +777,33 @@ export class RunInfraStream {
398
777
  }
399
778
  }
400
779
  buffer += decoder.decode();
401
- if (buffer) {
402
- const parsed = processLine(buffer);
403
- if (parsed)
404
- 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);
405
790
  }
406
- if (dataLines.length > 0) {
407
- const parsed = dispatchEvent();
408
- if (parsed)
409
- yield parsed;
791
+ catch (error) {
792
+ if (!(error instanceof RunInfraStreamParseError) || completed)
793
+ throw error;
410
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);
411
800
  }
412
801
  catch (error) {
413
- throw normalizeTransportError(error, this.requestId, this.sensitiveValues);
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;
414
807
  }
415
808
  finally {
416
809
  if (!readerDone) {
@@ -716,6 +1109,58 @@ function validateTranscriptionRequestKeys(request) {
716
1109
  }
717
1110
  }
718
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
+ }
719
1164
  const JSON_BODY_ERROR = "JSON request body must be JSON-serializable and contain only finite numbers";
720
1165
  function sanitizeJsonValue(value, seen = new WeakSet()) {
721
1166
  if (value === null || typeof value === "string" || typeof value === "boolean")
@@ -938,13 +1383,26 @@ function isBrowserRuntime() {
938
1383
  prototype !== null &&
939
1384
  Object.prototype.isPrototypeOf.call(prototype, runtime.self);
940
1385
  }
941
- 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) {
942
1399
  const value = response.headers.get("retry-after");
943
1400
  if (!value)
944
1401
  return null;
945
1402
  const trimmed = value.trim();
946
1403
  if (/^[0-9]+$/.test(trimmed)) {
947
1404
  const seconds = Number(trimmed);
1405
+ // A value above the largest safe integer names no wait: the SDK's own backoff applies.
948
1406
  if (Number.isSafeInteger(seconds))
949
1407
  return seconds * 1000;
950
1408
  return null;
@@ -956,24 +1414,59 @@ function retryAfterMs(response) {
956
1414
  return Math.max(0, dateMs - Date.now());
957
1415
  return null;
958
1416
  }
959
- function automaticRetryAfterMs(response) {
960
- const delay = retryAfterMs(response);
961
- if (delay === null || delay > MAX_AUTOMATIC_RETRY_AFTER_MS)
962
- return null;
963
- 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;
964
1438
  }
965
- function retryDelayMs(attempt, baseMs, response) {
966
- if (response) {
967
- const retryAfter = automaticRetryAfterMs(response);
968
- if (retryAfter !== null)
969
- return retryAfter;
970
- }
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) {
971
1441
  if (baseMs <= 0)
972
1442
  return 0;
973
1443
  const exponential = baseMs * 2 ** Math.max(0, attempt - 1);
974
1444
  const jitter = Math.random() * baseMs;
975
1445
  return Math.min(30_000, exponential + jitter);
976
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
+ }
977
1470
  async function parseError(response) {
978
1471
  try {
979
1472
  const body = (await response.json());
@@ -985,6 +1478,8 @@ async function parseError(response) {
985
1478
  type: typeof error.type === "string" ? error.type : "api_error",
986
1479
  ...(typeof error.code === "string" ? { code: error.code } : {}),
987
1480
  ...(typeof error.param === "string" ? { param: error.param } : {}),
1481
+ ...(typeof error.reason === "string" ? { reason: error.reason } : {}),
1482
+ ...(typeof error.retryable === "boolean" ? { retryable: error.retryable } : {}),
988
1483
  // Structured remediation fields the gateway ships on 402 insufficient_credits.
989
1484
  ...(typeof error.current_balance_cents === "number" && Number.isFinite(error.current_balance_cents)
990
1485
  ? { currentBalanceCents: error.current_balance_cents }
@@ -1002,58 +1497,140 @@ async function parseError(response) {
1002
1497
  };
1003
1498
  }
1004
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
+ }
1005
1523
  async function discardResponseBody(response) {
1006
1524
  try {
1007
1525
  await response.body?.cancel();
1008
1526
  }
1009
1527
  catch {
1010
- // 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
+ });
1569
+ }
1570
+ if (status === 404 && code === "model_not_sold") {
1571
+ return new ModelNotFoundError(message, status, requestId, code, param);
1011
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 });
1012
1576
  }
1013
- async function raiseForStatus(response) {
1014
- if (response.ok)
1015
- return;
1016
- const { message, type, code, param, currentBalanceCents, requiredCents, topupUrl } = await parseError(response);
1017
- 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;
1018
1579
  if (response.status === 401)
1019
- throw new AuthenticationError(message, response.status, requestId, code, param);
1580
+ return new AuthenticationError(message, response.status, requestId, code, param);
1020
1581
  if (response.status === 403) {
1021
1582
  // Keep a more specific gateway discriminator (e.g. "byoc_plan_required")
1022
1583
  // 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");
1584
+ return new PermissionDeniedError(message, response.status, requestId, code, param, type !== "api_error" ? type : "permission_denied");
1024
1585
  }
1025
1586
  if (response.status === 402) {
1026
- throw new InsufficientCreditsError(message, response.status, requestId, code, param, {
1587
+ return new InsufficientCreditsError(message, response.status, requestId, code, param, {
1027
1588
  currentBalanceCents,
1028
1589
  requiredCents,
1029
1590
  topupUrl,
1030
1591
  });
1031
1592
  }
1032
1593
  if (response.status === 404 || type === "model_not_found") {
1033
- throw new ModelNotFoundError(message, response.status, requestId, code, param);
1594
+ return new ModelNotFoundError(message, response.status, requestId, code, param);
1034
1595
  }
1035
1596
  if (response.status === 429) {
1036
- throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined, code, param);
1597
+ return new RateLimitError(message, response.status, requestId, undefined, code, param);
1037
1598
  }
1038
1599
  if (type === "deployment_error")
1039
- throw new DeploymentError(message, response.status, requestId, code, param);
1040
- throw new RunInfraError(message, { status: response.status, type, requestId, code, param });
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
+ });
1041
1617
  }
1042
- async function parseJsonResponse(response, sensitiveValues = []) {
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";
1621
+ }
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) {
1043
1628
  const requestId = response.headers.get("x-request-id") ?? undefined;
1044
- const idempotentReplay = response.headers.get("x-runinfra-idempotent-replay")?.trim().toLowerCase() === "true";
1045
- let payload;
1046
- try {
1047
- payload = await response.json();
1048
- }
1049
- catch (error) {
1050
- throw new ResponseBodyReadError(normalizeTransportError(error, requestId, sensitiveValues));
1051
- }
1052
1629
  if (payload && typeof payload === "object" && !Array.isArray(payload)) {
1053
1630
  return {
1054
1631
  ...payload,
1055
1632
  ...(requestId ? { _request_id: requestId } : {}),
1056
- ...(idempotentReplay ? { _idempotent_replay: true } : {}),
1633
+ ...(isIdempotentReplay(response) ? { _idempotent_replay: true } : {}),
1057
1634
  };
1058
1635
  }
1059
1636
  throw new RunInfraError(`RunInfra JSON response shape error: expected object, got ${jsonPayloadKind(payload)}.`, {
@@ -1062,6 +1639,17 @@ async function parseJsonResponse(response, sensitiveValues = []) {
1062
1639
  requestId,
1063
1640
  });
1064
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
+ }
1065
1653
  function jsonPayloadKind(payload) {
1066
1654
  if (payload === null)
1067
1655
  return "null";
@@ -1086,6 +1674,17 @@ function redactSensitiveValues(message, sensitiveValues = []) {
1086
1674
  return redacted;
1087
1675
  }
1088
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) {
1089
1688
  const message = redactSensitiveValues(error.message, sensitiveValues);
1090
1689
  const code = error.code === undefined ? undefined : redactSensitiveValues(error.code, sensitiveValues);
1091
1690
  const param = error.param === undefined ? undefined : redactSensitiveValues(error.param, sensitiveValues);
@@ -1119,6 +1718,12 @@ function redactRunInfraError(error, sensitiveValues) {
1119
1718
  return new RunInfraConnectionError(message, error.requestId);
1120
1719
  if (error instanceof RunInfraStreamParseError)
1121
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
+ }
1122
1727
  if (error instanceof UnsupportedOperationError)
1123
1728
  return new UnsupportedOperationError(message);
1124
1729
  if (error instanceof WebhookVerificationError)
@@ -1142,9 +1747,35 @@ function normalizeTransportError(error, requestId, sensitiveValues = []) {
1142
1747
  if (error instanceof Error && error.name === "AbortError") {
1143
1748
  return new RunInfraTimeoutError(redactSensitiveValues(error.message, sensitiveValues), requestId);
1144
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);
1759
+ }
1145
1760
  const message = redactSensitiveValues(error instanceof Error ? error.message : String(error), sensitiveValues);
1146
1761
  return new RunInfraConnectionError(message, requestId);
1147
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
+ }
1148
1779
  export class RunInfra {
1149
1780
  chat;
1150
1781
  embeddings;
@@ -1167,6 +1798,16 @@ export class RunInfra {
1167
1798
  * quality, style, and user fields depend on the selected deployment.
1168
1799
  */
1169
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;
1170
1811
  webhooks;
1171
1812
  /**
1172
1813
  * Voice pipeline surface.
@@ -1179,6 +1820,7 @@ export class RunInfra {
1179
1820
  apiKey;
1180
1821
  baseURL;
1181
1822
  hasPipelineScope;
1823
+ /** The caller's own client timeout. Left unset, each call uses the default of its kind. */
1182
1824
  timeoutMs;
1183
1825
  maxRetries;
1184
1826
  retryBaseMs;
@@ -1203,7 +1845,9 @@ export class RunInfra {
1203
1845
  const normalizedBaseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
1204
1846
  this.baseURL = normalizedBaseURL;
1205
1847
  this.hasPipelineScope = Boolean(options.pipelineId) || baseUrlLooksPipelineScoped(normalizedBaseURL);
1206
- this.timeoutMs = validatePositiveNumber(options.timeoutMs ?? 120_000, "timeoutMs");
1848
+ this.timeoutMs = options.timeoutMs === undefined || options.timeoutMs === null
1849
+ ? undefined
1850
+ : validatePositiveNumber(options.timeoutMs, "timeoutMs");
1207
1851
  this.maxRetries = validateNonNegativeInteger(options.maxRetries ?? 2, "maxRetries");
1208
1852
  this.retryBaseMs = validateNonNegativeNumber(options.retryBaseMs ?? 250, "retryBaseMs");
1209
1853
  if (options.fetch !== undefined && typeof options.fetch !== "function") {
@@ -1217,7 +1861,7 @@ export class RunInfra {
1217
1861
  return this.request("/chat/completions", {
1218
1862
  method: "POST",
1219
1863
  body,
1220
- typedBodyKeys: CHAT_COMPLETION_REQUEST_KEYS,
1864
+ typedBodyKeys: CHAT_COMPLETION_EXTRA_BODY_CLOSED_KEYS,
1221
1865
  stream: body.stream === true,
1222
1866
  idempotentReplaySafe: true,
1223
1867
  }, requestOptions);
@@ -1261,13 +1905,13 @@ export class RunInfra {
1261
1905
  const body = withValidatedModel(request);
1262
1906
  validateNonEmptyStringField(body.input, "input");
1263
1907
  validateSpeechReference(body);
1264
- 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", {
1265
1910
  method: "POST",
1266
1911
  body,
1267
1912
  typedBodyKeys: SPEECH_REQUEST_KEYS,
1268
1913
  binary: true,
1269
- }, requestOptions);
1270
- return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
1914
+ }, requestOptions, async (response, sensitiveValues, clientRequestId) => new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions), sensitiveValues, clientRequestId));
1271
1915
  },
1272
1916
  },
1273
1917
  transcriptions: {
@@ -1306,6 +1950,24 @@ export class RunInfra {
1306
1950
  }, requestOptions);
1307
1951
  },
1308
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,
1965
+ }, requestOptions);
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),
1970
+ };
1309
1971
  this.webhooks = {
1310
1972
  verifySignature: verifyWebhookSignature,
1311
1973
  constructEvent: constructWebhookEvent,
@@ -1330,17 +1992,22 @@ export class RunInfra {
1330
1992
  }
1331
1993
  async request(path, options, requestOptions) {
1332
1994
  if (options.stream) {
1333
- const response = await this.rawRequest(path, options, requestOptions);
1334
- return new RunInfraStream(response, this.requestTimeoutMs(requestOptions), [this.apiKey]);
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));
1335
1997
  }
1336
1998
  return this.sendWithRetry(path, options, requestOptions, (parseJsonResponse));
1337
1999
  }
1338
- 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) {
1339
2008
  const validatedRequestOptions = validateRequestOptions(requestOptions);
1340
- return validatePositiveNumber(validatedRequestOptions.timeoutMs ?? this.timeoutMs, "timeoutMs");
1341
- }
1342
- async rawRequest(path, options, requestOptions = {}) {
1343
- 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");
1344
2011
  }
1345
2012
  async sendWithRetry(path, options, requestOptions = {}, consumeResponse) {
1346
2013
  const validatedRequestOptions = validateRequestOptions(requestOptions);
@@ -1389,10 +2056,13 @@ export class RunInfra {
1389
2056
  (Boolean(validatedRequestOptions.idempotencyKey) && hasReplayableJsonBody);
1390
2057
  const maxRetries = validateNonNegativeInteger(validatedRequestOptions.maxRetries ?? this.maxRetries, "maxRetries");
1391
2058
  const retryBaseMs = validateNonNegativeNumber(validatedRequestOptions.retryBaseMs ?? this.retryBaseMs, "retryBaseMs");
1392
- 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;
1393
2061
  while (true) {
1394
2062
  const controller = new AbortController();
1395
2063
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
2064
+ let serverRequestId;
2065
+ let waitMs;
1396
2066
  try {
1397
2067
  const response = await this.fetcher(`${this.baseURL}${path}`, {
1398
2068
  method,
@@ -1400,37 +2070,63 @@ export class RunInfra {
1400
2070
  body,
1401
2071
  signal: controller.signal,
1402
2072
  });
1403
- if (canRetry &&
1404
- !response.ok &&
1405
- isRetryableStatus(response.status) &&
1406
- attempt < maxRetries) {
1407
- attempt += 1;
1408
- await discardResponseBody(response);
1409
- await sleep(retryDelayMs(attempt, retryBaseMs, response));
1410
- 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;
1411
2087
  }
1412
- await raiseForStatus(response);
1413
- return await consumeResponse(response, [this.apiKey]);
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);
1414
2094
  }
1415
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 });
1416
2103
  if (error instanceof ResponseBodyReadError) {
1417
- if (canRetry && attempt < maxRetries) {
1418
- attempt += 1;
1419
- await sleep(retryDelayMs(attempt, retryBaseMs));
1420
- continue;
1421
- }
1422
- throw normalizeTransportError(error.error, error.error.requestId, [this.apiKey]);
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);
1423
2123
  }
1424
- if (error instanceof RunInfraError)
1425
- throw normalizeTransportError(error, error.requestId, [this.apiKey]);
1426
- if (!canRetry || attempt >= maxRetries)
1427
- throw normalizeTransportError(error, undefined, [this.apiKey]);
1428
- attempt += 1;
1429
- await sleep(retryDelayMs(attempt, retryBaseMs));
1430
2124
  }
1431
2125
  finally {
1432
2126
  clearTimeout(timeout);
1433
2127
  }
2128
+ attempt += 1;
2129
+ await sleep(waitMs);
1434
2130
  }
1435
2131
  }
1436
2132
  }