@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/CHANGELOG.md CHANGED
@@ -3,6 +3,136 @@
3
3
  All notable changes to `@runinfra/sdk` are documented here. This project follows
4
4
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
+ ## [0.3.2] - 2026-11-25
7
+
8
+ No change to the TypeScript SDK. The version moves with the Python SDK, whose standard transport now keeps its
9
+ connections open between calls.
10
+
11
+ ## [0.3.1] - 2026-11-17
12
+
13
+ Read "Changed" before you upgrade. A stream now throws where it used to end
14
+ silently, the default timeouts are longer, and a call is no longer sent again
15
+ after a timeout.
16
+
17
+ ### Changed
18
+ - **A stream throws where it used to end silently.** Iterating a
19
+ `RunInfraStream` throws `RunInfraStreamError` when the API reports a failure
20
+ on the open stream (a frame that holds an `error` object, or a
21
+ `response.failed` event on a Responses stream), and
22
+ `RunInfraStreamIncompleteError` when the body ends without its end marker
23
+ (`[DONE]` on a chat stream, `response.completed` on a Responses stream; an
24
+ empty or missing body counts, and so does a body that ends in the middle of
25
+ an event). Every event that came first is still yielded before the throw,
26
+ and leaving the loop early throws nothing. Before, both cases ended the loop
27
+ as if the answer were complete. Wrap the loop in `try`/`catch`, and keep a
28
+ partial answer only if it is useful to you.
29
+ - **A streamed call answered with JSON yields that answer once.** A streamed
30
+ call that repeats an `Idempotency-Key` the API has already answered gets one
31
+ JSON object back instead of an event stream (`Content-Type:
32
+ application/json`, `X-RunInfra-Idempotent-Replay: true`). The stream yields
33
+ that object once, marked `_idempotent_replay: true`, and ends quietly; it is
34
+ not reported as a cut stream. Any other successful answer that is JSON
35
+ instead of an event stream is yielded once in the same way, without the
36
+ mark. Before, such an answer ended the loop with no event. Check
37
+ `_idempotent_replay` on an event before you read deltas from it.
38
+ - **New default timeouts.** With no `timeoutMs`, a non-streamed call is given
39
+ 750 seconds (was 120), and a streamed call 190 seconds to its response
40
+ headers and to each later read (was 120). The API allows a whole response up
41
+ to 740 seconds and a stream up to 180 seconds to its first token, and the old
42
+ default cut such calls off. A `timeoutMs` you set, on the client or on a
43
+ call, is used as before. A call that hangs now takes longer to fail unless
44
+ you set your own timeout.
45
+ - **On Node.js the built-in `fetch` still gives a non-streamed call at most
46
+ 300 seconds to its response headers.** It gives up when no response headers
47
+ arrive within 300 seconds, whatever `timeoutMs` says, and a non-streamed
48
+ answer can keep its headers back until it is whole. Pass the client a
49
+ `fetch` that allows more, or stream an answer that may take longer.
50
+ - **No re-send after a timeout.** A call that runs out of time throws
51
+ `RunInfraTimeoutError` and is never sent again, whatever `maxRetries` says
52
+ and whether or not it carries an `idempotencyKey`. Before, a `GET` and a
53
+ keyed non-streamed call were sent again after the SDK's own timeout, while
54
+ the API could still be working on the first send. The error carries
55
+ `clientRequestId`, the `X-Client-Request-Id` the SDK sent. The runtime's
56
+ `fetch` giving up on the response headers or the body by its own clock, as
57
+ Node's does after 300 seconds, counts as a timeout too: it throws
58
+ `RunInfraTimeoutError` where it used to throw `RunInfraConnectionError`, and
59
+ the call is not sent again. A failure to connect is still a
60
+ `RunInfraConnectionError`, and a call that is safe to send again is still
61
+ sent again after one. A timeout while an open stream is read carries
62
+ `clientRequestId` too, and so does a timeout while the body of an audio
63
+ speech answer is read.
64
+ - **The retry rule follows what the API says.** Which calls may be sent again
65
+ has not changed: a `GET`, or a non-streamed chat, Responses or batch create
66
+ call that carries an `idempotencyKey`. For those calls:
67
+ - `x-should-retry` on the response and `error.retryable` in the error body
68
+ are obeyed. `false` stops the retry of a status that used to be retried.
69
+ `true` allows the retry of a status that used not to be.
70
+ - The wait is read from `Retry-After-Ms` first, then from `Retry-After`.
71
+ Before, `Retry-After-Ms` was not read.
72
+ - A `Retry-After` in whole seconds above 9007199254740991
73
+ (`Number.MAX_SAFE_INTEGER`) names no wait: the SDK's own backoff applies,
74
+ and `retryAfterMs` stays unset. So does a `Retry-After-Ms` with more
75
+ digits than a number can hold.
76
+ - A wait above 60 seconds is raised at once, with the wait on the error.
77
+ Before, the SDK slept a short backoff instead and sent the call again
78
+ sooner than the API asked. On a batch route the line stays 5 seconds for a
79
+ `503`, and a `409` stays final.
80
+ - The error body of a failed response is read before the SDK decides, where
81
+ it used to be dropped unread. Reading it counts against the call's timeout.
82
+ - **`retryAfterMs` is on every typed error whose response named a wait**,
83
+ whatever its status. Before, only `RateLimitError` and the batch routes'
84
+ refusals carried it. Code that reads `retryAfterMs === undefined` to tell a
85
+ rate limit from another error must test the class or the status instead.
86
+ - **`content` may be `null` in the types.** `ChatMessage.content` is now
87
+ `string | Array<...> | null` and may be left out, because an assistant
88
+ message that carries only tool calls has no content, and a stream delta's
89
+ `content` may be `null`. Code that passes `message.content` where a `string`
90
+ is required needs a check to compile. Nothing changes at run time.
91
+ - The package's homepage link points at the public TypeScript guide.
92
+
93
+ ### Added
94
+ - `RunInfraStreamError` and `RunInfraStreamIncompleteError`, described above.
95
+ - `RunInfraError.retryable`: what the API said about asking again, when it
96
+ said it. `RunInfraError.clientRequestId`: set on a timeout.
97
+ - Chat request fields the API documents and the request type did not name:
98
+ `top_k`, `min_p`, `repetition_penalty`, `n`, `best_of`, `logit_bias`,
99
+ `parallel_tool_calls`, `reasoning_effort`, `reasoning`, `include_reasoning`,
100
+ `prompt_cache_key`, `service_tier`, `store`, `safety_identifier`,
101
+ `modalities`, `audio`, `prediction`, `verbosity`, `web_search_options`,
102
+ `moderation`, `functions`, and `function_call`. A request that names one is
103
+ no longer refused before it is sent. Each of them is still accepted in
104
+ `extraBody`, where it had to go before; naming one in both places is refused.
105
+ - Tool calls have a shape: `ChatMessage.tool_calls`
106
+ (`ChatCompletionMessageToolCall`), `ChatMessage.reasoning`, the `developer`
107
+ role, and `ChatToolMessage` for the message that answers a call by its
108
+ `tool_call_id`. On a stream, the delta types `tool_calls`
109
+ (`ChatCompletionStreamToolCallDelta`), `reasoning` and `role`, and each
110
+ choice types `index` and `finish_reason`.
111
+
112
+ ## [0.3.0] - 2026-11-16
113
+
114
+ ### Added
115
+ - `client.batches.create`, `client.batches.list`, `client.batches.retrieve`,
116
+ and `client.batches.cancel` for batch jobs, with the typed `BatchJob`,
117
+ `BatchJobDetail`, `BatchQuote`, and response envelopes. `create` sends
118
+ `idempotencyKey` as `Idempotency-Key`, is retried only when a key is given,
119
+ and never uses a default timeout below 30 seconds because the gateway tests
120
+ the destination before it answers.
121
+ - `verifyBatchDelivery` verifies a batch delivery posted to your own address
122
+ (Standard Webhooks signature over the raw body, compared in constant time)
123
+ and returns it as `BatchTestDelivery`, `BatchAnswerDelivery`, or
124
+ `BatchErrorDelivery`. The delivery's timestamp must be within 300 seconds of
125
+ the clock by default, so a captured delivery cannot be replayed later;
126
+ `toleranceSeconds` sets another tolerance and `toleranceSeconds: null` turns
127
+ the check off.
128
+ - Refusals of the batch routes are typed errors that keep the gateway's
129
+ `code`, `param`, and request id, plus `RunInfraError.reason` (the cause word
130
+ of `flex_not_available`) and `retryAfterMs` on every status that sends
131
+ `Retry-After`. A `409` from a batch route is a final refusal that is never
132
+ retried, and a `503` that asks for a wait above 5 seconds is raised at once
133
+ with that wait instead of being waited for. Errors and retries of every
134
+ other route are unchanged.
135
+
6
136
  ## [0.2.0] - 2026-06-15
7
137
 
8
138
  ### Added
package/README.md CHANGED
@@ -10,7 +10,7 @@ Requires Node.js 18 or newer.
10
10
  npm install @runinfra/sdk
11
11
  ```
12
12
 
13
- ## Modality status (v0.2.0)
13
+ ## Modality status (v0.3.2)
14
14
 
15
15
  This SDK is in **beta**. The surfaces below have different verification levels:
16
16
 
@@ -23,6 +23,7 @@ This SDK is in **beta**. The surfaces below have different verification levels:
23
23
  | Audio (ASR) | `client.audio.transcriptions.create` | Preview. Available when the deployment exposes transcription. |
24
24
  | Webhooks | `client.webhooks.verifySignature`, `client.webhooks.constructEvent`, `verifyWebhookSignature`, `constructWebhookEvent` | Local verification helpers only; delivery management is outside the public SDK surface |
25
25
  | Voice pipeline | `client.voice.pipeline.create` | Preview. Pipeline-scoped helper for co-located audio-to-response deployments. |
26
+ | Batch | `client.batches.create`, `client.batches.list`, `client.batches.retrieve`, `client.batches.cancel`, `verifyBatchDelivery` | Preview, from 0.3.0. Batch jobs for models that offer batch, with signed webhook deliveries. |
26
27
 
27
28
  The dashboard only shows snippets for operations the selected deployment
28
29
  supports. If a route is unsupported for a deployment, the SDK returns a typed
@@ -84,6 +85,8 @@ pipeline-scoped key. Direct browser token flows are not supported by the public
84
85
  SDK. If you are deliberately using a controlled non-public browser-like runtime,
85
86
  pass `dangerouslyAllowBrowser: true` and own that risk.
86
87
 
88
+ CI runs the unit tests on Node.js 20, 22 and 24. On Node.js 18 it type-checks, builds, packs and smoke-tests the installed package.
89
+
87
90
  Unknown TypeScript client option keys are rejected so typos such as `baseUrl` or `api_key` do not silently change the gateway, authentication, timeout, retry, or runtime-safety behavior. Use `baseURL` for custom server-side gateway URLs.
88
91
 
89
92
  ## Responses and streaming
@@ -111,6 +114,65 @@ releases the reader lock. If you manually advance the stream iterator, call
111
114
  released. Streaming transport-level backend cancellation is best effort, and
112
115
  streaming calls are not automatically retried.
113
116
 
117
+ ### When a stream fails or is cut
118
+
119
+ A stream is complete only when it carried its end marker: `[DONE]` on a chat
120
+ stream, `response.completed` on a Responses stream. The loop ends quietly in
121
+ that case alone. Otherwise the iteration throws, after it has yielded every
122
+ event that came first:
123
+
124
+ - `RunInfraStreamError` when the API reports a failure on the open stream: a
125
+ frame that holds an `error` object, or a `response.failed` event on a
126
+ Responses stream. It keeps the API's `type` and `code`, the request id as
127
+ `requestId`, and `retryable` when the API marked the failure. Its `status` is
128
+ `0`, because the failure arrived after the HTTP status.
129
+ - `RunInfraStreamIncompleteError` when the body ends without the end marker:
130
+ the connection was cut or the stream was closed early.
131
+
132
+ Either way the answer is not whole, even though the HTTP status was 200. Keep
133
+ what was yielded only if a partial answer is useful to you. Leaving the loop
134
+ early throws nothing. Before 0.3.1 both cases ended the loop silently, as if
135
+ the answer were complete.
136
+
137
+ ```ts
138
+ import { RunInfraStreamError, RunInfraStreamIncompleteError } from "@runinfra/sdk";
139
+
140
+ const chatStream = await client.chat.completions.create({
141
+ model: "your-deployed-model-id",
142
+ messages: [{ role: "user", content: "Count from one to three." }],
143
+ stream: true,
144
+ });
145
+
146
+ let answer = "";
147
+ try {
148
+ for await (const chunk of chatStream) {
149
+ answer += chunk.choices?.[0]?.delta?.content ?? "";
150
+ }
151
+ } catch (error) {
152
+ if (error instanceof RunInfraStreamError) {
153
+ console.error("The stream failed.", error.code, error.requestId, error.retryable);
154
+ } else if (error instanceof RunInfraStreamIncompleteError) {
155
+ console.error("The stream was cut short.", error.requestId);
156
+ } else {
157
+ throw error;
158
+ }
159
+ }
160
+ ```
161
+
162
+ ### When a streamed call is answered with JSON
163
+
164
+ A streamed call that repeats an `Idempotency-Key` the API has already answered gets one JSON object back instead of an event stream: `Content-Type: application/json` and `X-RunInfra-Idempotent-Replay: true`. The SDK does not read that as a cut stream. The stream yields the object once, marked `_idempotent_replay: true` as a non-streamed answer is, and the loop ends quietly. Check the mark before you read deltas from an event: a replayed answer is not a new stream of deltas. Any other successful answer that is JSON instead of an event stream is yielded once in the same way, without the mark. A JSON body that cannot be read throws `RunInfraStreamIncompleteError`. Before 0.3.1 such an answer ended the loop with no event at all.
165
+
166
+ ```ts
167
+ for await (const event of chatStream) {
168
+ if (event._idempotent_replay) {
169
+ console.log("Already answered. This is the API's receipt for the first call.", event);
170
+ continue;
171
+ }
172
+ answer += event.choices?.[0]?.delta?.content ?? "";
173
+ }
174
+ ```
175
+
114
176
  RunInfra `/v1/responses` is a chat-completions compatibility adapter. The gateway converts supported `input` and `instructions` values into chat messages, forwards the supported request through the chat-completions serving path, and rewraps the result into a Responses-style envelope. It does not claim full OpenAI Responses state, include, reasoning, tool, conversation-item, or background-job semantics.
115
177
 
116
178
  ## Supported public routes
@@ -124,6 +186,10 @@ RunInfra `/v1/responses` is a chat-completions compatibility adapter. The gatewa
124
186
  - `audio.transcriptions.create()`
125
187
  - `images.generate()`
126
188
  - `voice.pipeline.create()`
189
+ - `batches.create()`
190
+ - `batches.list()`
191
+ - `batches.retrieve(batchId)`
192
+ - `batches.cancel(batchId)`
127
193
 
128
194
  ## OpenAI-compatible parameter scope
129
195
 
@@ -135,6 +201,15 @@ The typed native SDK subset is:
135
201
  `max_tokens`, `stop`, `presence_penalty`, `frequency_penalty`, `user`, and
136
202
  `metadata`; streaming usage chunks are covered separately with
137
203
  `stream_options.include_usage`.
204
+ - Chat Completions also types, from 0.3.1, the other request fields the API
205
+ documents: `top_k`, `min_p`, `repetition_penalty`, `n`, `best_of`,
206
+ `logit_bias`, `parallel_tool_calls`, `reasoning_effort`, `reasoning`,
207
+ `include_reasoning`, `prompt_cache_key`, `service_tier`, `store`,
208
+ `safety_identifier`, `modalities`, `audio`, `prediction`, `verbosity`,
209
+ `web_search_options`, `moderation`, `functions`, and `function_call`. They
210
+ are sent as given; whether a model accepts one depends on the model. Each of
211
+ them is still accepted in `extraBody` too, where it had to go before, as long
212
+ as the request does not name it as well.
138
213
  - Responses: `model`, `input`, `stream`, `instructions`, `temperature`,
139
214
  `top_p`, `tools`, `tool_choice`, `response_format`, and `max_output_tokens`.
140
215
  - Embeddings: `model`, `input`, `encoding_format: "float"`, and `dimensions`
@@ -164,6 +239,50 @@ request shapes, but actual support depends on the deployed backend.
164
239
  Embedding `user`, TTS `speed`, and ASR `temperature` are typed pass-through
165
240
  options for SDK parity, but actual support depends on the deployed backend.
166
241
 
242
+ ## Tool calls
243
+
244
+ `ChatMessage` types the whole tool-calling turn. An assistant message carries
245
+ the model's calls in `tool_calls`, and its `content` is `null` or left out when
246
+ it carries nothing else. Answer each call with a `tool` message
247
+ (`ChatToolMessage`) that repeats the call's `id` as `tool_call_id`. On a
248
+ stream, `delta.tool_calls` carries the pieces of each call and
249
+ `delta.reasoning` the model's thinking.
250
+
251
+ ```ts
252
+ import type { ChatMessage, ChatToolMessage } from "@runinfra/sdk";
253
+
254
+ const tools = [{
255
+ type: "function",
256
+ function: {
257
+ name: "get_weather",
258
+ description: "Get the current weather for a city",
259
+ parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
260
+ },
261
+ }];
262
+ const messages: ChatMessage[] = [{ role: "user", content: "What is the weather in Paris?" }];
263
+
264
+ const first = await client.chat.completions.create({ model: "your-deployed-model-id", messages, tools });
265
+ const asked = first.choices?.[0]?.message;
266
+ if (asked?.tool_calls?.length) {
267
+ // Send the whole assistant message back, then one tool message per call.
268
+ messages.push(asked);
269
+ for (const call of asked.tool_calls) {
270
+ const args = JSON.parse(call.function.arguments) as { city?: string };
271
+ const result: ChatToolMessage = {
272
+ role: "tool",
273
+ tool_call_id: call.id,
274
+ content: JSON.stringify({ city: args.city, temp_c: 21 }),
275
+ };
276
+ messages.push(result);
277
+ }
278
+ const second = await client.chat.completions.create({ model: "your-deployed-model-id", messages, tools });
279
+ console.log(second.choices?.[0]?.message?.content);
280
+ }
281
+ ```
282
+
283
+ The arguments of a call arrive as a JSON string the model wrote: parse and
284
+ check them before you run anything. Tool calling depends on the model.
285
+
167
286
  ## Text to speech
168
287
 
169
288
  TTS deployments can expose named voices or Base/reference-audio voice cloning.
@@ -200,6 +319,92 @@ owns `getReader()`, cancellation, and slow-consumer backpressure. The SDK does
200
319
  not auto-retry or replay binary TTS streams; use `arrayBuffer()` or `blob()` when
201
320
  you want SDK read-timeout wrapping for a finite body.
202
321
 
322
+ ## Batch jobs
323
+
324
+ Preview, from 0.3.0. A batch job takes a JSONL file of chat completion requests and posts each answer to your webhook address. A job has a window of 24 hours. Lines run when the model has spare capacity. A line the job has not run when its window ends is counted `expired` and is not charged. Batch needs a workspace-scoped key and a model that offers batch.
325
+
326
+ ```ts
327
+ const { batch } = await client.batches.create(
328
+ {
329
+ model: "deepseek-v4-1-flash-1017",
330
+ input_url: "https://example.org/batch/input.jsonl",
331
+ destination: { type: "webhook", url: "https://example.org/batch/answers" },
332
+ max_cost_cents: 100,
333
+ window_hours: 24,
334
+ name: "nightly-evals",
335
+ },
336
+ { idempotencyKey: "nightly-evals-2026-11-16" },
337
+ );
338
+
339
+ const job = await client.batches.retrieve(batch.id);
340
+ console.log(job.batch.batch_state, job.batch.errors, job.batch.cost_microcents);
341
+ ```
342
+
343
+ Sending the same create again with the same `idempotencyKey` and the same body answers the earlier job as a normal success: no error and no second job. The same key with a different body is refused with `409`.
344
+
345
+ - `model`, `input_url`, `destination`, and `max_cost_cents` are required. `max_cost_cents` is the most the job may cost, a whole number from 1 to 100,000,000. `window_hours` is 24, the only value and the default. `name` is a label of at most 64 characters.
346
+ - `input_url` is a public HTTPS link on port 443, at most 8,192 bytes, to a JSONL file of at most 50 MiB whose host serves byte ranges (signed links from the common storage services do). A signed link must stay valid until the job's window ends. `destination.url` is a public HTTPS address on port 443.
347
+ - Each line of the file is `{"custom_id": "...", "method": "POST", "url": "/v1/chat/completions", "body": {...}}`, at most 4 MiB. `custom_id` is unique in the file (1 to 512 characters) and `body` is a text-only, non-streaming chat completion body whose `model` is the job's model.
348
+ - The job starts by itself. It is answered in `batch_state` `validating` and moves through `checked` and `queued` to `running`; `completed`, `expired`, `cancelled`, and `failed` are final, and `end_reason` says why. `batches.retrieve()` adds `errors` (the lines the file check refused, by code, with their first line numbers) and `quote`.
349
+ - `failed` never includes an undelivered line, and once a job has ended the counts `succeeded`, `failed`, `expired`, `cancelled`, `undelivered`, and `lines_invalid` add up to `lines_total`.
350
+ - `batches.list({ limit, cursor, state, model })` answers `{ batches, next_cursor }`, newest first; pass `next_cursor` as `cursor` for the next page. `batches.cancel(batchId)` answers `{ batch_id, batch_state }` with `cancelled` or `cancelling`.
351
+
352
+ Before it answers, `batches.create()` posts a signed test delivery `{ "id": "bdt_...", "test": true, "value": "..." }` to `destination.url`. The address passes only when it replies 2xx with a body that contains the posted `value`, within 20 seconds; otherwise the create is refused with `destination_unreachable`. Because of that test the call's default timeout is never below 30 seconds, whatever the client's `timeoutMs`; a per-request `timeoutMs` is used as given.
353
+
354
+ `batches.create()` is sent once unless you pass `idempotencyKey`. With a key, transient failures are retried with the same key and body. `batches.cancel()` is always sent once. A `409` from a batch route is a final refusal and is never retried. A `503` that asks for a wait above 5 seconds in `Retry-After` is raised at once with `retryAfterMs` set, so a call never blocks on a long wait; a `503` that asks for 5 seconds or less is asked again by the retry rule.
355
+
356
+ Every refusal of a batch route is a typed error that keeps the gateway's `code`, the `param` it names, `reason`, `retryAfterMs` when the gateway sent `Retry-After`, and `requestId`:
357
+
358
+ ```ts
359
+ import { RunInfraError } from "@runinfra/sdk";
360
+
361
+ try {
362
+ await client.batches.cancel(batch.id);
363
+ } catch (error) {
364
+ if (error instanceof RunInfraError && error.code === "batch_ended") {
365
+ // The job had already ended.
366
+ } else if (error instanceof RunInfraError && error.code === "flex_not_available") {
367
+ console.error(error.reason); // "model", "partner", or "price"
368
+ } else {
369
+ throw error;
370
+ }
371
+ }
372
+ ```
373
+
374
+ The refusal codes are `batch_not_open` (`503`: ask again after the wait the error carries), `invalid_request`, `not_found`, `model_not_sold`, `flex_not_available`, `url_not_public`, `link_expires_too_soon`, `destination_unreachable`, `needs_funds`, `key_spend_limit_reached`, `batch_ended`, and `batches_scope_violation`. `model_not_sold` is a `ModelNotFoundError`; an unknown batch id is a plain `RunInfraError` with status `404` and code `not_found`. A `402` on a batch route is an `InsufficientCreditsError`; read `code` to tell `needs_funds` (the account has never added funds) from `key_spend_limit_reached` (this API key reached its own monthly limit; raise the key's limit or use another key). A file that is refused when it is read, after the create answered, ends the job `failed` with `check_error` `url_not_public`, `link_expires_too_soon`, `file_too_large`, `link_changed`, or `link_not_supported`.
375
+
376
+ ### Verify batch deliveries
377
+
378
+ Each answered line arrives at your address as one signed `POST`. Copy the workspace's batch signing secret from the dashboard and verify the exact raw body before you use it.
379
+
380
+ ```ts
381
+ import { verifyBatchDelivery } from "@runinfra/sdk";
382
+
383
+ const signingSecret = process.env.RUNINFRA_BATCH_SIGNING_SECRET;
384
+ if (!signingSecret?.trim()) throw new Error("Set RUNINFRA_BATCH_SIGNING_SECRET before verifying batch deliveries.");
385
+
386
+ const delivery = verifyBatchDelivery({
387
+ payload: rawBody,
388
+ headers: request.headers,
389
+ secret: signingSecret,
390
+ });
391
+
392
+ if (delivery.test) {
393
+ // The create's test delivery: reply 2xx with a body that contains delivery.value.
394
+ return new Response(delivery.value, { status: 200 });
395
+ }
396
+ if (delivery.error) {
397
+ console.error(delivery.custom_id ?? `line ${delivery.line}`, delivery.error.code);
398
+ } else {
399
+ console.log(delivery.custom_id, delivery.response, delivery.cost?.microcents);
400
+ }
401
+ return new Response(null, { status: 204 });
402
+ ```
403
+
404
+ `verifyBatchDelivery` takes the raw request body (a string or bytes, never an object you parsed and serialized again) and the request's headers in any case. It checks `webhook-signature`, which is `v1,` followed by the base64 HMAC-SHA-256 of `<webhook-id>.<webhook-timestamp>.<raw body>`, in constant time. The secret is `whsec_` followed by base64, and the HMAC key is the decoded bytes, so any Standard Webhooks library verifies the same deliveries. By default the delivery's `webhook-timestamp` must be within 300 seconds of your clock, so a captured delivery cannot be replayed later. Pass a number as `toleranceSeconds` for another tolerance, or `toleranceSeconds: null` to turn the check off; `now` sets the clock in Unix seconds. A failed check throws `WebhookVerificationError`.
405
+
406
+ The helper returns one of three typed shapes: `BatchTestDelivery` (`test: true`), `BatchAnswerDelivery` with `custom_id`, `line`, `attempt`, the chat completion in `response`, `usage`, and `cost.microcents`, or `BatchErrorDelivery` with `error.code` for a line that failed after the job started. `id` is the same for the same line and attempt. Key your own writes on it. Any 2xx acknowledges a line. Each answered line is sent to the address once: if the address does not answer 2xx in time, the line is counted `undelivered`, it is not charged, and it is not sent again. So answer 2xx first and do slow work afterwards.
407
+
203
408
  ## Timeouts and retries
204
409
 
205
410
  ```ts
@@ -214,7 +419,27 @@ const client = new RunInfra({
214
419
  });
215
420
  ```
216
421
 
217
- The SDK retries transient transport failures and `408`, `409`, `429`, `500`, `502`, `503`, and `504` responses for safe `GET` requests. Charge-bearing `POST` inference requests retry only when you provide `idempotencyKey`, and automatic POST retries are limited to non-streaming JSON calls whose gateway responses can be replayed safely. Only `responses.create()` and non-streaming `chat.completions.create()` are currently auto-retry replay-safe. Embeddings, images, streaming calls, binary TTS responses, and multipart ASR uploads are sent once even when you provide an idempotency key. Keep `maxRetries: 0` for any cost-sensitive operation whose replay behavior is not documented as safe. Automatic retries honor reasonable `Retry-After` values up to 60 seconds when the header is a plain integer second value or HTTP-date, then fall back to bounded exponential backoff. The SDK does not retry authentication errors, insufficient credits, or unsupported operations.
422
+ ### Timeouts
423
+
424
+ When you set no `timeoutMs`, a non-streamed call is given 750 seconds for the whole call, and a streamed call is given 190 seconds to its response headers and to each later read. The API allows a whole response up to 740 seconds and a stream up to 180 seconds to its first token, so the defaults sit just above both. Your own setting wins: `timeoutMs` on the client applies to every call, and `timeoutMs` in a call's options wins over the client's. Before 0.3.1 the default was 120 seconds for every call, so a long answer the API was still writing was cut off by the SDK.
425
+
426
+ On Node.js the built-in `fetch` has a limit of its own: it gives up when no response headers arrive within 300 seconds, and a non-streamed answer can keep its headers back until it is whole. So with the built-in `fetch` a non-streamed call gets at most 300 seconds to its response headers, whatever `timeoutMs` says, unless you pass the client a `fetch` that allows more. Stream an answer that may take longer.
427
+
428
+ A call is never sent again after a timeout, even when it carries an `idempotencyKey` and retries are left: the API may still be working on the first send. The call throws `RunInfraTimeoutError`. Its `clientRequestId` is the `X-Client-Request-Id` the SDK sent, so the call can be found; `requestId` is set only when a response had begun. The same holds when the runtime's `fetch` gives up on the response headers or the body by its own clock, as Node's does after 300 seconds: the SDK throws `RunInfraTimeoutError`, not `RunInfraConnectionError`, and does not send the call again. Before 0.3.1 a `GET` and a keyed call were sent again after the SDK's own timeout.
429
+
430
+ ### Retries
431
+
432
+ The SDK retries transient transport failures and `408`, `409`, `429`, `500`, `502`, `503`, and `504` responses for safe `GET` requests. Charge-bearing `POST` inference requests retry only when you provide `idempotencyKey`, and automatic POST retries are limited to non-streaming JSON calls whose gateway responses can be replayed safely. Only `responses.create()` and non-streaming `chat.completions.create()` are currently auto-retry replay-safe. Embeddings, images, streaming calls, binary TTS responses, and multipart ASR uploads are sent once even when you provide an idempotency key. Keep `maxRetries: 0` for any cost-sensitive operation whose replay behavior is not documented as safe. The SDK does not retry authentication errors, insufficient credits, or unsupported operations.
433
+
434
+ For a call that is safe to send again, what the API says comes first:
435
+
436
+ - `x-should-retry` on the response and `error.retryable` in the error body are obeyed when present. `false` from either means the call is not sent again, whatever its status. `true` allows another send, whatever its status. When the API says nothing, the status decides, as listed above.
437
+ - The wait is read from `Retry-After-Ms` first, then from `Retry-After` (whole seconds or an HTTP date), and the SDK sleeps that long.
438
+ - A wait above 60 seconds is not slept. The error is raised at once with the wait as `retryAfterMs`, so the call never blocks for minutes and you can plan the next attempt yourself. Before 0.3.1 such a wait was replaced by a short backoff, and the call was sent again sooner than the API asked.
439
+ - When the API names no wait, the SDK backs off exponentially from `retryBaseMs`, with jitter, for at most 30 seconds.
440
+ - The error body of a failed response is read before the SDK decides, because the API can mark the failure inside it.
441
+
442
+ Every typed error whose response named a wait carries it as `retryAfterMs`, whatever its status, and `retryable` holds what the API said about asking again.
218
443
 
219
444
  For replay-safe operations, if the gateway successfully finishes a request but the response body is too large to replay from the idempotency cache, later calls with the same `idempotencyKey` return `idempotency_replay_unavailable` without running or charging the inference again.
220
445
 
@@ -245,18 +470,21 @@ await client.responses.create(
245
470
 
246
471
  ## Typed errors
247
472
 
248
- The SDK exposes `AuthenticationError`, `PermissionDeniedError`, `RateLimitError`, `InsufficientCreditsError`, `DeploymentError`, `ModelNotFoundError`, `RunInfraTimeoutError`, `RunInfraConnectionError`, and `RunInfraStreamParseError`. `UnsupportedOperationError` remains exported for compatibility with older v0.1.x code, but current public helpers do not raise it.
249
- `RateLimitError` includes `retryAfterMs` when the gateway returns `Retry-After`.
473
+ The SDK exposes `AuthenticationError`, `PermissionDeniedError`, `RateLimitError`, `InsufficientCreditsError`, `DeploymentError`, `ModelNotFoundError`, `RunInfraTimeoutError`, `RunInfraConnectionError`, `RunInfraStreamParseError`, `RunInfraStreamError`, and `RunInfraStreamIncompleteError`. `UnsupportedOperationError` remains exported for compatibility with older v0.1.x code, but current public helpers do not raise it.
474
+ Every typed error includes `retryAfterMs` when its response named a wait (`Retry-After-Ms`, else `Retry-After`), and `retryable` when the API said whether asking again helps. Before 0.3.1 only `RateLimitError` and the batch routes' refusals carried the wait.
475
+ `RunInfraStreamError` and `RunInfraStreamIncompleteError` are thrown while a stream is read; see "When a stream fails or is cut".
476
+ `RunInfraTimeoutError` includes `clientRequestId`, the `X-Client-Request-Id` the SDK sent with the call that timed out.
250
477
  `PermissionDeniedError.type` preserves a specific gateway discriminator on `403` responses when one is present (for example `byoc_plan_required` when a workspace below the deploy tier calls a BYOC-deployed endpoint); it falls back to `permission_denied`. Branch on `err.type` instead of matching the message string.
251
478
  `InsufficientCreditsError` includes `currentBalanceCents`, `requiredCents`, and `topupUrl` when the gateway returns them on a `402` response, so you can render an exact top-up prompt without parsing the message.
252
479
  `RunInfraStreamParseError` includes `requestId` when a malformed SSE frame came from a traced gateway response.
253
- `RunInfraTimeoutError` also covers stalled streaming reads, stalled non-streaming JSON body reads, and stalled binary audio `arrayBuffer()` / `blob()` reads after headers arrive, and includes `requestId` when the response was traced.
480
+ `RunInfraTimeoutError` also covers stalled streaming reads, stalled non-streaming JSON body reads, and stalled binary audio `arrayBuffer()` / `blob()` reads after headers arrive, and includes `requestId` when the response was traced. It also covers the runtime's `fetch` giving up on the response headers or the body by its own clock.
254
481
  `RunInfraConnectionError` also covers streaming body transport failures, non-streaming JSON body transport failures, and binary audio `arrayBuffer()` / `blob()` transport failures after headers arrive, and includes `requestId` when the response was traced.
255
482
 
256
483
  JSON helpers return typed response objects for the public gateway contract:
257
484
  `ModelListResponse`, `ModelObject`, `EmbeddingResponse`, `ResponsesCreateResponse`,
258
485
  `ChatCompletionResponse`, `TranscriptionResponse`, and `ImageGenerationResponse`.
259
486
  Binary TTS returns `RunInfraAudioResponse`, and streaming calls return `RunInfraStream`.
487
+ Batch helpers return `BatchCreateResponse`, `BatchRetrieveResponse`, `BatchListResponse`, and `BatchCancelResponse` around the typed `BatchJob`.
260
488
 
261
489
  ## Traceability
262
490