@runinfra/sdk 0.1.3 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,40 +10,35 @@ Requires Node.js 18 or newer.
10
10
  npm install @runinfra/sdk
11
11
  ```
12
12
 
13
- ## Modality status (v0.1.3)
13
+ ## Modality status (v0.3.2)
14
14
 
15
15
  This SDK is in **beta**. The surfaces below have different verification levels:
16
16
 
17
17
  | Modality | Surface | Status |
18
18
  |---|---|---|
19
- | LLM | `client.chat.completions.create`, `client.responses.create` | Beta, contract-tested |
20
- | Embeddings | `client.embeddings.create` | Beta, contract-tested |
21
- | Images | `client.images.generate` | **Experimental**, not live-canary verified |
22
- | Audio (TTS) | `client.audio.speech.create` | **Experimental**, not live-canary verified |
23
- | Audio (ASR) | `client.audio.transcriptions.create` | **Experimental**, not live-canary verified |
24
- | Webhooks | `client.webhooks.*` | Local verification helpers only; remote delivery not shipped |
25
- | Voice pipeline | `client.voice.pipeline.create` | **Experimental**, pipeline-scoped route, not live-canary verified |
26
-
27
- Experimental surfaces match their documented gateway contracts, but we have
28
- not yet completed a full end-to-end live-canary deployment for those
29
- modalities in the public gateway. They will reach GA in v1.0.0 once the
30
- canary suite covers all five model modalities plus voice pipeline. Test
31
- against your own deployed models before using experimental surfaces in
32
- production.
19
+ | LLM | `client.chat.completions.create`, `client.responses.create` | Beta. Typed helpers for verified LLM and vision-language deployments. |
20
+ | Embeddings | `client.embeddings.create` | Beta. Typed helper for verified embedding deployments. |
21
+ | Images | `client.images.generate` | Preview. Available when the deployment exposes image generation. |
22
+ | Audio (TTS) | `client.audio.speech.create` | Preview. Available when the deployment exposes speech generation. |
23
+ | Audio (ASR) | `client.audio.transcriptions.create` | Preview. Available when the deployment exposes transcription. |
24
+ | Webhooks | `client.webhooks.verifySignature`, `client.webhooks.constructEvent`, `verifyWebhookSignature`, `constructWebhookEvent` | Local verification helpers only; delivery management is outside the public SDK surface |
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. |
27
+
28
+ The dashboard only shows snippets for operations the selected deployment
29
+ supports. If a route is unsupported for a deployment, the SDK returns a typed
30
+ error instead of silently falling back to another operation.
33
31
 
34
32
  ## Create a client
35
33
 
36
34
  Use a workspace-scoped key to reach verified active deployments through the `model` field.
37
- In RunPipe, open Settings, API Keys, Create key, and keep Scope set to Workspace.
35
+ In the RunInfra dashboard, open Settings, API Keys, Create key, and keep Scope set to Workspace.
38
36
 
39
37
  The Deploy tab can create a pipeline-scoped key for one optimized pipeline.
40
38
  The one-time secret is shown once after creation. Store it as `RUNINFRA_API_KEY`
41
- for app snippets before leaving the page. For repo live canaries, keep the
42
- workspace key in `RUNINFRA_API_KEY` and put the pipeline-scoped key for
43
- `TEST_PIPELINE_ID` in `RUNINFRA_PIPELINE_API_KEY` so flat and pipeline routes
44
- are verified independently.
39
+ for app snippets before leaving the page.
45
40
 
46
- After a runbook finishes in RunPipe, choose Open Deploy from the runbook handoff.
41
+ After an optimization run finishes, open the Deploy view from the dashboard.
47
42
  Deploy only shows SDK operations that the verified endpoint supports, so copy
48
43
  the native or OpenAI-compatible snippet from there instead of guessing a route.
49
44
 
@@ -72,7 +67,7 @@ const client = new RunInfra({
72
67
 
73
68
  The default base URL is `https://api.runinfra.ai/v1`.
74
69
  `pipelineId` is trimmed and URL-encoded before it is added to the base URL. Use either `pipelineId` with the default base URL, or a pipeline-scoped `baseURL` such as `https://api.runinfra.ai/v1/pipe_123`. If both point to the same pipeline, the SDK keeps the URL scoped once.
75
- RunPipe generated native SDK snippets prefer `pipelineId` with the root `https://api.runinfra.ai/v1` base URL. OpenAI-compatible snippets use the pipeline-scoped base URL because the OpenAI SDK has no RunInfra pipeline option.
70
+ RunInfra generated native SDK snippets prefer `pipelineId` with the root `https://api.runinfra.ai/v1` base URL. OpenAI-compatible snippets use the pipeline-scoped base URL because the OpenAI SDK has no RunInfra pipeline option.
76
71
  Custom base URLs must use `http` or `https`. Other schemes and malformed URLs are rejected before a bearer API key can be sent.
77
72
  Remote custom base URLs must use `https`. Plain `http` is accepted only for local development hosts: `localhost`, `127.0.0.1`, `0.0.0.0`, and `[::1]`.
78
73
  Custom base URLs must not include usernames or passwords.
@@ -80,7 +75,17 @@ Custom base URLs must not include query strings or fragments.
80
75
 
81
76
  ## Server-side only
82
77
 
83
- The TypeScript SDK targets Node.js 18 or newer. RunInfra API keys are bearer secrets. Do not initialize this SDK in browser code with a secret API key. The SDK fails closed when it detects a browser runtime; keep calls on a Node.js server route, API service, or backend job. If you are deliberately using a controlled non-public browser-like runtime, pass `dangerouslyAllowBrowser: true` and own that risk.
78
+ The TypeScript SDK targets Node.js 18 or newer. RunInfra API keys are bearer
79
+ secrets. Do not put `RUNINFRA_API_KEY` in browser code and do not initialize
80
+ this SDK in public client bundles with a secret API key. The SDK fails closed
81
+ when it detects a browser runtime; keep calls on a Node.js server route,
82
+ backend proxy, API service, or backend job. Browser apps should call your own
83
+ server first, then your server calls RunInfra with the workspace or
84
+ pipeline-scoped key. Direct browser token flows are not supported by the public
85
+ SDK. If you are deliberately using a controlled non-public browser-like runtime,
86
+ pass `dangerouslyAllowBrowser: true` and own that risk.
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.
84
89
 
85
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.
86
91
 
@@ -103,6 +108,73 @@ for await (const event of stream) {
103
108
  console.log(stream.requestId);
104
109
  ```
105
110
 
111
+ Breaking out of the `for await` loop cancels the underlying SSE reader and
112
+ releases the reader lock. If you manually advance the stream iterator, call
113
+ `return()` on that iterator when you stop early so local response resources are
114
+ released. Streaming transport-level backend cancellation is best effort, and
115
+ streaming calls are not automatically retried.
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
+
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.
177
+
106
178
  ## Supported public routes
107
179
 
108
180
  - `models.list()`
@@ -114,6 +186,102 @@ console.log(stream.requestId);
114
186
  - `audio.transcriptions.create()`
115
187
  - `images.generate()`
116
188
  - `voice.pipeline.create()`
189
+ - `batches.create()`
190
+ - `batches.list()`
191
+ - `batches.retrieve(batchId)`
192
+ - `batches.cancel(batchId)`
193
+
194
+ ## OpenAI-compatible parameter scope
195
+
196
+ The native SDK validates the minimum request fields locally, then forwards
197
+ OpenAI-style JSON or multipart fields that preserve the typed response shape.
198
+ The typed native SDK subset is:
199
+
200
+ - Chat Completions: `model`, `messages`, `stream`, `temperature`, `top_p`,
201
+ `max_tokens`, `stop`, `presence_penalty`, `frequency_penalty`, `user`, and
202
+ `metadata`; streaming usage chunks are covered separately with
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.
213
+ - Responses: `model`, `input`, `stream`, `instructions`, `temperature`,
214
+ `top_p`, `tools`, `tool_choice`, `response_format`, and `max_output_tokens`.
215
+ - Embeddings: `model`, `input`, `encoding_format: "float"`, and `dimensions`
216
+ when the deployed embedding backend advertises dimension control.
217
+ - Images: `model`, `prompt`, `n`, plus optional `size` and `response_format`
218
+ when the deployed image backend advertises them.
219
+ - Image `quality`, `style`, and `user` are typed pass-through OpenAI-style
220
+ options when the deployed image backend supports them.
221
+ - Audio speech: `model`, `input`, `voice` or `ref_audio` plus `ref_text`, and
222
+ optional `task_type` and `response_format`.
223
+ - Audio transcriptions: `model`, `file`, `filename`, optional `language`,
224
+ optional `prompt`, and JSON response formats only.
225
+
226
+ The native typed helpers do not claim GA support for tool calls, structured
227
+ JSON schema outputs, logprobs, seeds, service tiers, parallel tool calls,
228
+ Responses state/include/reasoning controls, embedding base64 output, image
229
+ streaming or partial images, audio streaming, audio translations, or direct
230
+ browser API-key use. Embedding
231
+ `encoding_format` values other than `"float"` and transcription
232
+ `response_format` values other than `"json"` or `"verbose_json"` are rejected
233
+ locally because they would not match the typed native SDK response objects.
234
+ Unsupported OpenAI-style body parameters must fail with a clear traced 4xx
235
+ gateway error.
236
+
237
+ LLM pass-through options are typed for parity with the Python SDK and OpenAI-style
238
+ request shapes, but actual support depends on the deployed backend.
239
+ Embedding `user`, TTS `speed`, and ASR `temperature` are typed pass-through
240
+ options for SDK parity, but actual support depends on the deployed backend.
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.
117
285
 
118
286
  ## Text to speech
119
287
 
@@ -145,6 +313,98 @@ const audio = await client.audio.speech.create({
145
313
  });
146
314
  ```
147
315
 
316
+ `RunInfraAudioResponse.stream()` exposes the native `ReadableStream<Uint8Array>`
317
+ from `fetch` without buffering it. Use it for large TTS responses when the caller
318
+ owns `getReader()`, cancellation, and slow-consumer backpressure. The SDK does
319
+ not auto-retry or replay binary TTS streams; use `arrayBuffer()` or `blob()` when
320
+ you want SDK read-timeout wrapping for a finite body.
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
+
148
408
  ## Timeouts and retries
149
409
 
150
410
  ```ts
@@ -159,17 +419,38 @@ const client = new RunInfra({
159
419
  });
160
420
  ```
161
421
 
162
- 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. That covers `responses.create()`, non-streaming `chat.completions.create()`, `embeddings.create()`, and `images.generate()`. Streaming calls, binary TTS responses, and multipart ASR uploads are sent once even when you provide an idempotency key. The gateway still binds idempotency keys for TTS and ASR, so a manual retry with the same key will not run or charge a second inference after the first request settles. 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.
163
443
 
164
- 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.
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.
165
445
 
166
446
  `timeoutMs` must be positive, `maxRetries` must be a non-negative integer, and `retryBaseMs` must be non-negative. Unknown per-request option keys are rejected so typos do not silently disable idempotency, tracing, timeout, or retry behavior. Invalid values throw `RunInfraError` with `type: "invalid_request_options"` before any network request is sent.
167
447
 
168
448
  ## Request validation
169
449
 
170
- Required request fields are validated before any network request is sent. The model must be a non-blank string, chat messages must be a non-empty array, each chat message must be an object with a non-empty role, Responses input must be a non-empty string or array, Responses input array items must be objects, JSON request bodies must be serializable and contain only finite numbers, embedding input must be a non-empty string or array of non-empty strings, TTS input and image prompts must be non-empty strings, and ASR file must be a Blob. ASR multipart filenames and extra form field names and values are validated before the FormData body is built. Invalid request values throw `RunInfraError` with `type: "invalid_request_options"` and do not reach the gateway or billing path.
450
+ Required request fields are validated before any network request is sent. The model must be a non-blank string, chat messages must be a non-empty array, each chat message must be an object with a non-empty role, Responses input must be a non-empty string or array, Responses input array items must be objects, JSON request bodies must be serializable and contain only finite numbers, embedding input must be a non-empty string or array of non-empty strings, TTS input and image prompts must be non-empty strings, and ASR file must be a non-empty Blob. ASR multipart filenames are validated before the FormData body is built. Invalid request values throw `RunInfraError` with `type: "invalid_request_options"` and do not reach the gateway or billing path.
171
451
 
172
452
  Use per-request options when a call needs a shorter timeout, a trace ID, or a retry-safe idempotency key.
453
+ TypeScript request interfaces are closed around typed fields, and unknown direct request fields are rejected before any network request is sent. Use `extraBody` in request options for deliberate JSON body extensions, such as an unsupported-parameter probe. `extraBody` is only accepted on JSON body requests. `extraBody` cannot override typed request fields and is validated before the request is sent.
173
454
  Custom headers are for app metadata only. They cannot override SDK-controlled headers such as `Authorization`, `Content-Type`, `X-Client-Request-Id`, `Idempotency-Key`, `X-RunInfra-SDK`, or `X-RunInfra-SDK-Version`, and they cannot set transport or credential headers such as `Host`, `Cookie`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Proxy-Authorization`, `Api-Key`, `X-API-Key`, `X-Auth-Token`, or `X-Access-Token`.
174
455
 
175
456
  ```ts
@@ -189,16 +470,21 @@ await client.responses.create(
189
470
 
190
471
  ## Typed errors
191
472
 
192
- The SDK exposes `AuthenticationError`, `PermissionDeniedError`, `RateLimitError`, `InsufficientCreditsError`, `DeploymentError`, `ModelNotFoundError`, `RunInfraTimeoutError`, `RunInfraConnectionError`, `RunInfraStreamParseError`, and `UnsupportedOperationError`.
193
- `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.
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.
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.
194
479
  `RunInfraStreamParseError` includes `requestId` when a malformed SSE frame came from a traced gateway response.
195
- `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.
196
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.
197
482
 
198
483
  JSON helpers return typed response objects for the public gateway contract:
199
484
  `ModelListResponse`, `ModelObject`, `EmbeddingResponse`, `ResponsesCreateResponse`,
200
485
  `ChatCompletionResponse`, `TranscriptionResponse`, and `ImageGenerationResponse`.
201
486
  Binary TTS returns `RunInfraAudioResponse`, and streaming calls return `RunInfraStream`.
487
+ Batch helpers return `BatchCreateResponse`, `BatchRetrieveResponse`, `BatchListResponse`, and `BatchCancelResponse` around the typed `BatchJob`.
202
488
 
203
489
  ## Traceability
204
490
 
@@ -206,11 +492,11 @@ Every request includes `X-RunInfra-SDK: typescript`, `X-RunInfra-SDK-Version`, a
206
492
 
207
493
  When `idempotencyKey` is provided, the SDK sends it as `Idempotency-Key`. Use a unique value for each logical retry-safe operation. Idempotency keys must be non-blank, ASCII, 255 characters or less, and must not contain secrets or personal data.
208
494
 
209
- Successful JSON object responses include `_request_id` when the gateway returns `x-request-id`. Streaming responses expose the same value as `stream.requestId`, malformed stream frames raise `RunInfraStreamParseError` with that request id, and binary audio responses expose it as `response.requestId`. Log that value with production errors and customer support reports.
495
+ Successful JSON object responses include `_request_id` when the gateway returns `x-request-id`. Streaming responses expose the same value as `stream.requestId`, malformed stream frames raise `RunInfraStreamParseError` with that request id, and binary audio responses expose it as `response.requestId`. Gateway errors expose `requestId`, `type`, and, when returned by the API, OpenAI-style `code` and `param` metadata such as `unsupported_parameter` and `dimensions`. Log the request id with production errors and customer support reports.
210
496
 
211
497
  ## Webhook verification
212
498
 
213
- Public webhook delivery routes are not shipped yet, but the SDK includes local verification helpers for signed RunInfra webhook deliveries once you receive them in your own server. Always verify the exact raw body before parsing JSON. The `RunInfra-Signature` timestamp must be a non-negative integer Unix second.
499
+ Webhook delivery management is outside the public SDK surface. The SDK includes local verification helpers for signed RunInfra webhook deliveries once you receive them in your own server. Always verify the exact raw body before parsing JSON. The `RunInfra-Signature` timestamp must be a non-negative integer Unix second.
214
500
 
215
501
  ```ts
216
502
  import {
@@ -247,48 +533,12 @@ const client = new OpenAI({
247
533
  });
248
534
  ```
249
535
 
250
- ## Production promotion
251
-
252
- Local package tests prove SDK shape, retry behavior, streaming parsing, typed
253
- errors, package contents, version sync, and trusted-publishing workflow policy.
254
- They do not prove that a newly optimized deployment is ready for customers.
255
- This extracted public repo does not define the old monorepo live-canary
256
- commands.
257
-
258
- For production promotion from this repo, run these local checks from the
259
- repository root before opening a release PR:
260
-
261
- ```bash
262
- node scripts/verify-workflow-policy.mjs
263
- node scripts/verify-version-sync.mjs
264
- pnpm --dir typescript install --lockfile=false
265
- pnpm --dir typescript exec tsc -p tsconfig.json --noEmit
266
- pnpm --dir typescript test
267
- pnpm --dir typescript build
268
- pnpm --dir typescript pack
269
- node scripts/verify-npm-package.mjs typescript/runinfra-sdk-*.tgz
270
- python -m pip install -e python pytest build twine
271
- python -m pytest python/tests -v
272
- python -m build python
273
- python scripts/verify-python-package.py python/dist
274
- python -m twine check python/dist/*
275
- ```
276
-
277
- Then trigger a GitHub dry-run publish from `main`:
278
-
279
- ```bash
280
- gh workflow run publish.yml --repo RightNow-AI/runinfra-sdk --ref main -f package=both -f dry_run=true
281
- ```
282
-
283
- Actual publishing must use the same workflow with `dry_run=false` after CI,
284
- review, and environment approval. Do not use npm or PyPI tokens. OIDC trusted
285
- publishing is the only supported publish path.
536
+ ## Voice pipelines and webhooks
286
537
 
287
- Run live deployment canaries from RunPipe or RunInfra-Engine against the exact
288
- production gateway, workspace, pipeline keys, and RunPod inventory that will
289
- serve customers. The SDK repo only proves client artifact integrity. GA still
290
- requires live coverage for LLM, embeddings, image, TTS, ASR, and voice pipeline
291
- surfaces, plus explicit evidence that the smoke keys and temporary canary
292
- resources were removed.
538
+ Co-located voice pipelines are available through the native
539
+ `client.voice.pipeline.create()` helper on pipeline-scoped keys. The helper
540
+ posts binary audio to the pipeline-scoped `/pipeline` route and returns the JSON
541
+ transcript / response envelope.
293
542
 
294
- Co-located voice pipelines are available through the native `client.voice.pipeline.create()` helper on pipeline-scoped keys. The helper posts binary audio to the pipeline-scoped `/pipeline` route and returns the JSON transcript / response envelope. Public webhook create/list calls are intentionally unavailable until their gateway routes are verified, and the SDK throws `UnsupportedOperationError` locally for those webhook capabilities without making a request.
543
+ Webhook delivery management is handled outside the public SDK surface. Local
544
+ signature verification helpers are available now.