pendra 0.20.0 → 0.21.1

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
@@ -215,11 +215,16 @@ Speech isn't available with private inference yet. On a client with
215
215
  | `baseURL` | — | `https://api.pendra.ai` |
216
216
  | `timeout` | — | `120000` (ms) |
217
217
 
218
- For a streaming request, `timeout` covers waiting for the response to start and
219
- then any gap between chunks, not the length of the whole stream, so long
220
- generations are not cut off. Breaking out of a stream's `for await` loop early
218
+ `timeout` covers waiting for the response to start and then any gap in the
219
+ data, not the length of the whole response, so long generations are not cut
220
+ off, streamed or not. Breaking out of a stream's `for await` loop early
221
221
  cancels the request.
222
222
 
223
+ With private inference on, the key fingerprints the client has trusted are
224
+ recorded in `~/.pendra/known_org_keys.json`; set `PENDRA_TOFU_PATH` to use
225
+ another file, e.g. under `/tmp` on a read-only filesystem. If the file can't be
226
+ written, requests still succeed and a warning is logged.
227
+
223
228
  ## Migrating from OpenAI
224
229
 
225
230
  ```diff
package/dist/index.d.mts CHANGED
@@ -895,9 +895,11 @@ interface PendraOptions {
895
895
  /**
896
896
  * Enable end-to-end encrypted (private) inference. When `true`, inference
897
897
  * requests (chat, embeddings, moderations and the rest) are sealed to your
898
- * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only
899
- * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint
900
- * (required in browser bundles, which cannot use the TOFU key store).
898
+ * org's workload keys and the responses are decrypted client-side — Pendra
899
+ * relays only ciphertext. By default every key the API returns for your org is
900
+ * trusted, and its fingerprint is recorded in a local key store; nothing is
901
+ * pinned. Pass `{ pinnedFingerprint }` to seal only to the fingerprints you
902
+ * list (required in browser bundles, which have no key store).
901
903
  *
902
904
  * Defaults to the `PENDRA_PRIVATE_INFERENCE` environment variable
903
905
  * (`1`/`true`/`yes`/`on` enables it).
@@ -937,6 +939,8 @@ declare class Pendra {
937
939
  headers?: Record<string, string>;
938
940
  /** Overrides the client timeout for this request (ms). */
939
941
  timeout?: number;
942
+ /** The caller reads the body as a stream, which applies its own idle timeout. */
943
+ stream?: boolean;
940
944
  }): Promise<{
941
945
  response: Response;
942
946
  controller: AbortController;
@@ -984,8 +988,21 @@ declare class APIStatusError extends APIError {
984
988
  declare class AuthenticationError extends APIStatusError {
985
989
  constructor(message?: string, options?: APIStatusErrorOptions);
986
990
  }
991
+ /**
992
+ * Raised on 429 Too Many Requests: every worker that can serve the request is
993
+ * busy, on a stream as on any other request.
994
+ *
995
+ * `retryAfter` is the seconds the API asks you to wait before retrying (its
996
+ * `Retry-After` header), `queueDepth` how many requests were already waiting
997
+ * for the model (`X-Pendra-Queue-Depth`); each is `undefined` when not sent.
998
+ */
987
999
  declare class RateLimitError extends APIStatusError {
988
- constructor(message?: string, options?: APIStatusErrorOptions);
1000
+ readonly retryAfter: number | undefined;
1001
+ readonly queueDepth: number | undefined;
1002
+ constructor(message?: string, options?: APIStatusErrorOptions & {
1003
+ retryAfter?: number;
1004
+ queueDepth?: number;
1005
+ });
989
1006
  }
990
1007
  /**
991
1008
  * Raised when a response arrives but isn't the shape the SDK expects.
@@ -1032,12 +1049,16 @@ declare class APIStreamError extends APIError {
1032
1049
  readonly requestId: string | undefined;
1033
1050
  readonly workerId: string | undefined;
1034
1051
  readonly workerName: string | undefined;
1052
+ /** Seconds to wait before retrying when the report carried one (a capacity
1053
+ * 429), else `undefined`. Same meaning as on `RateLimitError`. */
1054
+ readonly retryAfter: number | undefined;
1035
1055
  constructor(message: string, options?: {
1036
1056
  type?: string;
1037
1057
  code?: number;
1038
1058
  requestId?: string;
1039
1059
  workerId?: string;
1040
1060
  workerName?: string;
1061
+ retryAfter?: number;
1041
1062
  });
1042
1063
  }
1043
1064
 
package/dist/index.d.ts CHANGED
@@ -895,9 +895,11 @@ interface PendraOptions {
895
895
  /**
896
896
  * Enable end-to-end encrypted (private) inference. When `true`, inference
897
897
  * requests (chat, embeddings, moderations and the rest) are sealed to your
898
- * org's workload key (TOFU-pinned on first use) and the responses are decrypted client-side — Pendra relays only
899
- * ciphertext. Pass `{ pinnedFingerprint }` to hard-pin the org key fingerprint
900
- * (required in browser bundles, which cannot use the TOFU key store).
898
+ * org's workload keys and the responses are decrypted client-side — Pendra
899
+ * relays only ciphertext. By default every key the API returns for your org is
900
+ * trusted, and its fingerprint is recorded in a local key store; nothing is
901
+ * pinned. Pass `{ pinnedFingerprint }` to seal only to the fingerprints you
902
+ * list (required in browser bundles, which have no key store).
901
903
  *
902
904
  * Defaults to the `PENDRA_PRIVATE_INFERENCE` environment variable
903
905
  * (`1`/`true`/`yes`/`on` enables it).
@@ -937,6 +939,8 @@ declare class Pendra {
937
939
  headers?: Record<string, string>;
938
940
  /** Overrides the client timeout for this request (ms). */
939
941
  timeout?: number;
942
+ /** The caller reads the body as a stream, which applies its own idle timeout. */
943
+ stream?: boolean;
940
944
  }): Promise<{
941
945
  response: Response;
942
946
  controller: AbortController;
@@ -984,8 +988,21 @@ declare class APIStatusError extends APIError {
984
988
  declare class AuthenticationError extends APIStatusError {
985
989
  constructor(message?: string, options?: APIStatusErrorOptions);
986
990
  }
991
+ /**
992
+ * Raised on 429 Too Many Requests: every worker that can serve the request is
993
+ * busy, on a stream as on any other request.
994
+ *
995
+ * `retryAfter` is the seconds the API asks you to wait before retrying (its
996
+ * `Retry-After` header), `queueDepth` how many requests were already waiting
997
+ * for the model (`X-Pendra-Queue-Depth`); each is `undefined` when not sent.
998
+ */
987
999
  declare class RateLimitError extends APIStatusError {
988
- constructor(message?: string, options?: APIStatusErrorOptions);
1000
+ readonly retryAfter: number | undefined;
1001
+ readonly queueDepth: number | undefined;
1002
+ constructor(message?: string, options?: APIStatusErrorOptions & {
1003
+ retryAfter?: number;
1004
+ queueDepth?: number;
1005
+ });
989
1006
  }
990
1007
  /**
991
1008
  * Raised when a response arrives but isn't the shape the SDK expects.
@@ -1032,12 +1049,16 @@ declare class APIStreamError extends APIError {
1032
1049
  readonly requestId: string | undefined;
1033
1050
  readonly workerId: string | undefined;
1034
1051
  readonly workerName: string | undefined;
1052
+ /** Seconds to wait before retrying when the report carried one (a capacity
1053
+ * 429), else `undefined`. Same meaning as on `RateLimitError`. */
1054
+ readonly retryAfter: number | undefined;
1035
1055
  constructor(message: string, options?: {
1036
1056
  type?: string;
1037
1057
  code?: number;
1038
1058
  requestId?: string;
1039
1059
  workerId?: string;
1040
1060
  workerName?: string;
1061
+ retryAfter?: number;
1041
1062
  });
1042
1063
  }
1043
1064
 
package/dist/index.js CHANGED
@@ -77,8 +77,18 @@ var RateLimitError = class extends APIStatusError {
77
77
  constructor(message = "Rate limit exceeded", options = {}) {
78
78
  super(message, 429, options);
79
79
  this.name = "RateLimitError";
80
+ this.retryAfter = options.retryAfter;
81
+ this.queueDepth = options.queueDepth;
80
82
  }
81
83
  };
84
+ function secondsFrom(...candidates) {
85
+ for (const value of candidates) {
86
+ if (typeof value !== "number" && (typeof value !== "string" || value.trim() === "")) continue;
87
+ const n = Number(value);
88
+ if (Number.isFinite(n) && n >= 0) return n;
89
+ }
90
+ return void 0;
91
+ }
82
92
  var _APIResponseValidationError = class _APIResponseValidationError extends APIError {
83
93
  constructor(message, options = {}) {
84
94
  const { status, body } = options;
@@ -104,6 +114,7 @@ var APIStreamError = class extends APIError {
104
114
  this.requestId = options.requestId;
105
115
  this.workerId = options.workerId;
106
116
  this.workerName = options.workerName;
117
+ this.retryAfter = options.retryAfter;
107
118
  }
108
119
  };
109
120
  var LOC_SOURCES = /* @__PURE__ */ new Set(["body", "query", "path", "header", "cookie"]);
@@ -165,7 +176,7 @@ async function readErrorBody(response) {
165
176
  return raw;
166
177
  }
167
178
  }
168
- function statusErrorFromBody(status, body, fallback) {
179
+ function statusErrorFromBody(status, body, fallback, headers) {
169
180
  const detail = isRecord(body) ? body.detail : void 0;
170
181
  const err = isRecord(body) ? body.error : void 0;
171
182
  let message = (isRecord(err) ? nonEmptyString(err.message) : void 0) ?? messageFromDetail(detail) ?? (isRecord(body) ? nonEmptyString(body.message) : void 0);
@@ -177,7 +188,13 @@ function statusErrorFromBody(status, body, fallback) {
177
188
  }
178
189
  const options = { body, detail };
179
190
  if (status === 401) return new AuthenticationError(message, options);
180
- if (status === 429) return new RateLimitError(message, options);
191
+ if (status === 429) {
192
+ return new RateLimitError(message, {
193
+ ...options,
194
+ retryAfter: secondsFrom(headers?.get("Retry-After"), isRecord(err) ? err.retry_after : void 0),
195
+ queueDepth: secondsFrom(headers?.get("X-Pendra-Queue-Depth"), isRecord(err) ? err.queue_depth : void 0)
196
+ });
197
+ }
181
198
  return new APIStatusError(message, status, options);
182
199
  }
183
200
 
@@ -579,7 +596,8 @@ function throwIfInBandError(parsed, fallback = "The server reported an error mid
579
596
  code: typeof e.code === "number" ? e.code : void 0,
580
597
  requestId: asString(e.request_id),
581
598
  workerId: asString(e.worker_id),
582
- workerName: asString(e.worker_name)
599
+ workerName: asString(e.worker_name),
600
+ retryAfter: secondsFrom(e.retry_after)
583
601
  }
584
602
  );
585
603
  }
@@ -792,6 +810,18 @@ function defaultTofuPath() {
792
810
  const home = env?.HOME || env?.USERPROFILE || ".";
793
811
  return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
794
812
  }
813
+ function isFsError(e) {
814
+ const err = e;
815
+ return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
816
+ }
817
+ var warnedTofuPaths = /* @__PURE__ */ new Set();
818
+ function warnTofuUnwritable(tofuPath, e) {
819
+ if (warnedTofuPaths.has(tofuPath)) return;
820
+ warnedTofuPaths.add(tofuPath);
821
+ console.warn(
822
+ `pendra: could not update the private-inference trust store at ${tofuPath} (${e.message}). Continuing: the store only records trusted key fingerprints and requests are still encrypted. Set PENDRA_TOFU_PATH to a writable file to silence this warning.`
823
+ );
824
+ }
795
825
  function b64d2(s) {
796
826
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
797
827
  const binary = atob(s);
@@ -883,7 +913,12 @@ var PrivateInferenceEngine = class {
883
913
  );
884
914
  }
885
915
  } else {
886
- await this.tofuTrust(fps);
916
+ try {
917
+ await this.tofuTrust(fps);
918
+ } catch (e) {
919
+ if (!isFsError(e)) throw e;
920
+ warnTofuUnwritable(this.tofuPath, e);
921
+ }
887
922
  accepted = pubs;
888
923
  }
889
924
  this.orgPubs = accepted;
@@ -907,14 +942,21 @@ var PrivateInferenceEngine = class {
907
942
  }
908
943
  }
909
944
  async loadTofu() {
945
+ const fs = await import("fs");
946
+ let raw;
947
+ try {
948
+ raw = fs.readFileSync(this.tofuPath, "utf-8");
949
+ } catch (e) {
950
+ if (e.code === "ENOENT") return {};
951
+ throw e;
952
+ }
953
+ let data;
910
954
  try {
911
- const fs = await import("fs");
912
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
913
- const data = JSON.parse(raw);
914
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
955
+ data = JSON.parse(raw);
915
956
  } catch {
916
957
  return {};
917
958
  }
959
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
918
960
  }
919
961
  async saveTofu(store) {
920
962
  const fs = await import("fs");
@@ -1065,6 +1107,201 @@ var Speech = class {
1065
1107
  }
1066
1108
  };
1067
1109
 
1110
+ // src/_sse.ts
1111
+ var DEFAULT_EVENT = "message";
1112
+ function fieldValue(line, name) {
1113
+ const value = line.slice(name.length + 1);
1114
+ return value.startsWith(" ") ? value.slice(1) : value;
1115
+ }
1116
+ var SseDecoder = class {
1117
+ constructor() {
1118
+ this.buffer = "";
1119
+ this.event = "";
1120
+ this.data = [];
1121
+ }
1122
+ /** Feed a chunk of decoded text; returns the payloads it completed. */
1123
+ push(text) {
1124
+ this.buffer += text;
1125
+ const lines = this.buffer.split("\n");
1126
+ this.buffer = lines.pop() ?? "";
1127
+ const out = [];
1128
+ for (const line of lines) {
1129
+ const payload = this.pushLine(line);
1130
+ if (payload !== null) out.push(payload);
1131
+ }
1132
+ return out;
1133
+ }
1134
+ /**
1135
+ * Release what the stream ended without terminating: the held-back partial
1136
+ * line, plus any frame that never got its blank line.
1137
+ *
1138
+ * The spec discards an unterminated final block; we keep it, so a connection
1139
+ * that drops after the last `data:` line but before its blank line still
1140
+ * delivers that payload rather than silently losing it.
1141
+ */
1142
+ flush() {
1143
+ const out = [];
1144
+ if (this.buffer !== "") {
1145
+ const payload = this.pushLine(this.buffer);
1146
+ this.buffer = "";
1147
+ if (payload !== null) out.push(payload);
1148
+ }
1149
+ const tail = this.endFrame();
1150
+ if (tail !== null) out.push(tail);
1151
+ return out;
1152
+ }
1153
+ pushLine(rawLine) {
1154
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1155
+ if (line === "") return this.endFrame();
1156
+ if (line.startsWith(":")) return null;
1157
+ if (line.startsWith("event:")) {
1158
+ this.event = fieldValue(line, "event");
1159
+ return null;
1160
+ }
1161
+ if (line.startsWith("data:")) {
1162
+ this.data.push(fieldValue(line, "data"));
1163
+ return null;
1164
+ }
1165
+ return null;
1166
+ }
1167
+ endFrame() {
1168
+ const { data, event } = this;
1169
+ this.data = [];
1170
+ this.event = "";
1171
+ if (data.length === 0) return null;
1172
+ if (event !== "" && event !== DEFAULT_EVENT) return null;
1173
+ return data.join("\n");
1174
+ }
1175
+ };
1176
+
1177
+ // src/streaming.ts
1178
+ var Stream = class {
1179
+ constructor(response, controller, idleTimeoutMs) {
1180
+ this.decoder = new TextDecoder();
1181
+ this.sse = new SseDecoder();
1182
+ this.done = false;
1183
+ this.placement = new PlacementTracker();
1184
+ if (!response.body) {
1185
+ throw new Error("Response body is null \u2014 streaming not supported");
1186
+ }
1187
+ this.reader = response.body.getReader();
1188
+ this.controller = controller;
1189
+ this.idleTimeoutMs = idleTimeoutMs;
1190
+ }
1191
+ async *[Symbol.asyncIterator]() {
1192
+ try {
1193
+ while (!this.done) {
1194
+ const { value, done: readerDone } = await readWithIdleTimeout(
1195
+ this.reader,
1196
+ this.idleTimeoutMs
1197
+ );
1198
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
1199
+ for (const data of payloads) {
1200
+ if (data === "[DONE]") {
1201
+ this.done = true;
1202
+ return;
1203
+ }
1204
+ yield this.placement.observe(parseStreamFrame(data));
1205
+ }
1206
+ if (readerDone) {
1207
+ this.done = true;
1208
+ break;
1209
+ }
1210
+ }
1211
+ } finally {
1212
+ releaseReader(this.reader, this.controller, this.done);
1213
+ }
1214
+ }
1215
+ /**
1216
+ * The worker that served this stream, or `null` until the chunk reporting it
1217
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1218
+ * old to report it). Same as that chunk's `pendra.worker`.
1219
+ */
1220
+ get worker() {
1221
+ return this.placement.worker;
1222
+ }
1223
+ /**
1224
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1225
+ * `null` until then.
1226
+ */
1227
+ get requestId() {
1228
+ return this.placement.requestId;
1229
+ }
1230
+ abort() {
1231
+ this.done = true;
1232
+ this.controller.abort();
1233
+ }
1234
+ };
1235
+ var PlacementTracker = class {
1236
+ constructor() {
1237
+ this.worker = null;
1238
+ this.requestId = null;
1239
+ }
1240
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1241
+ observe(chunk) {
1242
+ const { worker, requestId } = chunkPlacement(chunk);
1243
+ if (worker) this.worker = worker;
1244
+ if (requestId) this.requestId = requestId;
1245
+ return chunk;
1246
+ }
1247
+ };
1248
+ async function readWithIdleTimeout(reader, idleTimeoutMs, what = "Stream") {
1249
+ if (!idleTimeoutMs) return reader.read();
1250
+ let timer;
1251
+ const idle = new Promise((_, reject) => {
1252
+ timer = setTimeout(
1253
+ () => reject(new APIConnectionError(`${what} received no data for ${idleTimeoutMs}ms`)),
1254
+ idleTimeoutMs
1255
+ );
1256
+ });
1257
+ try {
1258
+ return await Promise.race([reader.read(), idle]);
1259
+ } finally {
1260
+ clearTimeout(timer);
1261
+ }
1262
+ }
1263
+ function withIdleTimeout(response, controller, idleTimeoutMs) {
1264
+ const body = response.body;
1265
+ if (!idleTimeoutMs || !body || typeof body.getReader !== "function") return response;
1266
+ if (response.status < 200 || response.status > 599) return response;
1267
+ const reader = body.getReader();
1268
+ const guarded = new ReadableStream(
1269
+ {
1270
+ async pull(sink) {
1271
+ const chunk = await readWithIdleTimeout(reader, idleTimeoutMs, "Response body").catch(
1272
+ (err) => {
1273
+ controller.abort();
1274
+ reader.cancel().catch(() => {
1275
+ });
1276
+ throw err;
1277
+ }
1278
+ );
1279
+ if (chunk.done) sink.close();
1280
+ else sink.enqueue(chunk.value);
1281
+ },
1282
+ cancel(reason) {
1283
+ controller.abort();
1284
+ return reader.cancel(reason);
1285
+ }
1286
+ },
1287
+ // Read only on demand, so no idle timer runs while nobody is reading.
1288
+ { highWaterMark: 0 }
1289
+ );
1290
+ return new Response(guarded, {
1291
+ status: response.status,
1292
+ statusText: response.statusText,
1293
+ headers: response.headers
1294
+ });
1295
+ }
1296
+ function releaseReader(reader, controller, finished) {
1297
+ if (!finished) {
1298
+ controller.abort();
1299
+ reader.cancel().catch(() => {
1300
+ });
1301
+ }
1302
+ reader.releaseLock();
1303
+ }
1304
+
1068
1305
  // src/resources/audio/transcriptions.ts
1069
1306
  var ENCODER = new TextEncoder();
1070
1307
  var DECODER = new TextDecoder();
@@ -1167,9 +1404,10 @@ var Transcriptions = class {
1167
1404
  throw new APIConnectionError(String(err));
1168
1405
  }
1169
1406
  clearTimeout(timeoutId);
1407
+ response = withIdleTimeout(response, controller, timeout);
1170
1408
  if (response.status >= 400) {
1171
1409
  const body = await readErrorBody(response);
1172
- throw statusErrorFromBody(response.status, body, response.statusText);
1410
+ throw statusErrorFromBody(response.status, body, response.statusText, response.headers);
1173
1411
  }
1174
1412
  const format = params.response_format;
1175
1413
  if (format === "text" || format === "srt" || format === "vtt") {
@@ -1238,168 +1476,6 @@ var Audio = class {
1238
1476
  }
1239
1477
  };
1240
1478
 
1241
- // src/_sse.ts
1242
- var DEFAULT_EVENT = "message";
1243
- function fieldValue(line, name) {
1244
- const value = line.slice(name.length + 1);
1245
- return value.startsWith(" ") ? value.slice(1) : value;
1246
- }
1247
- var SseDecoder = class {
1248
- constructor() {
1249
- this.buffer = "";
1250
- this.event = "";
1251
- this.data = [];
1252
- }
1253
- /** Feed a chunk of decoded text; returns the payloads it completed. */
1254
- push(text) {
1255
- this.buffer += text;
1256
- const lines = this.buffer.split("\n");
1257
- this.buffer = lines.pop() ?? "";
1258
- const out = [];
1259
- for (const line of lines) {
1260
- const payload = this.pushLine(line);
1261
- if (payload !== null) out.push(payload);
1262
- }
1263
- return out;
1264
- }
1265
- /**
1266
- * Release what the stream ended without terminating: the held-back partial
1267
- * line, plus any frame that never got its blank line.
1268
- *
1269
- * The spec discards an unterminated final block; we keep it, so a connection
1270
- * that drops after the last `data:` line but before its blank line still
1271
- * delivers that payload rather than silently losing it.
1272
- */
1273
- flush() {
1274
- const out = [];
1275
- if (this.buffer !== "") {
1276
- const payload = this.pushLine(this.buffer);
1277
- this.buffer = "";
1278
- if (payload !== null) out.push(payload);
1279
- }
1280
- const tail = this.endFrame();
1281
- if (tail !== null) out.push(tail);
1282
- return out;
1283
- }
1284
- pushLine(rawLine) {
1285
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1286
- if (line === "") return this.endFrame();
1287
- if (line.startsWith(":")) return null;
1288
- if (line.startsWith("event:")) {
1289
- this.event = fieldValue(line, "event");
1290
- return null;
1291
- }
1292
- if (line.startsWith("data:")) {
1293
- this.data.push(fieldValue(line, "data"));
1294
- return null;
1295
- }
1296
- return null;
1297
- }
1298
- endFrame() {
1299
- const { data, event } = this;
1300
- this.data = [];
1301
- this.event = "";
1302
- if (data.length === 0) return null;
1303
- if (event !== "" && event !== DEFAULT_EVENT) return null;
1304
- return data.join("\n");
1305
- }
1306
- };
1307
-
1308
- // src/streaming.ts
1309
- var Stream = class {
1310
- constructor(response, controller, idleTimeoutMs) {
1311
- this.decoder = new TextDecoder();
1312
- this.sse = new SseDecoder();
1313
- this.done = false;
1314
- this.placement = new PlacementTracker();
1315
- if (!response.body) {
1316
- throw new Error("Response body is null \u2014 streaming not supported");
1317
- }
1318
- this.reader = response.body.getReader();
1319
- this.controller = controller;
1320
- this.idleTimeoutMs = idleTimeoutMs;
1321
- }
1322
- async *[Symbol.asyncIterator]() {
1323
- try {
1324
- while (!this.done) {
1325
- const { value, done: readerDone } = await readWithIdleTimeout(
1326
- this.reader,
1327
- this.idleTimeoutMs
1328
- );
1329
- const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
1330
- for (const data of payloads) {
1331
- if (data === "[DONE]") {
1332
- this.done = true;
1333
- return;
1334
- }
1335
- yield this.placement.observe(parseStreamFrame(data));
1336
- }
1337
- if (readerDone) {
1338
- this.done = true;
1339
- break;
1340
- }
1341
- }
1342
- } finally {
1343
- releaseReader(this.reader, this.controller, this.done);
1344
- }
1345
- }
1346
- /**
1347
- * The worker that served this stream, or `null` until the chunk reporting it
1348
- * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1349
- * old to report it). Same as that chunk's `pendra.worker`.
1350
- */
1351
- get worker() {
1352
- return this.placement.worker;
1353
- }
1354
- /**
1355
- * Pendra's id for this request, reported alongside {@link Stream.worker};
1356
- * `null` until then.
1357
- */
1358
- get requestId() {
1359
- return this.placement.requestId;
1360
- }
1361
- abort() {
1362
- this.done = true;
1363
- this.controller.abort();
1364
- }
1365
- };
1366
- var PlacementTracker = class {
1367
- constructor() {
1368
- this.worker = null;
1369
- this.requestId = null;
1370
- }
1371
- /** Record `chunk`'s placement, if it carries any, and hand it back. */
1372
- observe(chunk) {
1373
- const { worker, requestId } = chunkPlacement(chunk);
1374
- if (worker) this.worker = worker;
1375
- if (requestId) this.requestId = requestId;
1376
- return chunk;
1377
- }
1378
- };
1379
- async function readWithIdleTimeout(reader, idleTimeoutMs) {
1380
- if (!idleTimeoutMs) return reader.read();
1381
- let timer;
1382
- const idle = new Promise((_, reject) => {
1383
- timer = setTimeout(
1384
- () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
1385
- idleTimeoutMs
1386
- );
1387
- });
1388
- try {
1389
- return await Promise.race([reader.read(), idle]);
1390
- } finally {
1391
- clearTimeout(timer);
1392
- }
1393
- }
1394
- function releaseReader(reader, controller, finished) {
1395
- if (!finished) {
1396
- controller.abort();
1397
- reader.cancel().catch(() => {
1398
- });
1399
- }
1400
- reader.releaseLock();
1401
- }
1402
-
1403
1479
  // src/_privateStreaming.ts
1404
1480
  var DECODER2 = new TextDecoder();
1405
1481
  var EncryptedStream = class {
@@ -1542,7 +1618,7 @@ var Completions = class {
1542
1618
  if (params.stream) {
1543
1619
  const { response: response2, controller } = await this.client._fetch(
1544
1620
  "/api/v1/chat/completions",
1545
- { method: "POST", body, headers }
1621
+ { method: "POST", body, headers, stream: true }
1546
1622
  );
1547
1623
  return new Stream(response2, controller, this.client.timeout);
1548
1624
  }
@@ -1569,7 +1645,7 @@ var Completions = class {
1569
1645
  if (stream) {
1570
1646
  const { response: response2, controller } = await this.client._fetch(
1571
1647
  "/api/v1/chat/completions",
1572
- { method: "POST", body: topLevel, headers }
1648
+ { method: "POST", body: topLevel, headers, stream: true }
1573
1649
  );
1574
1650
  return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
1575
1651
  }
@@ -1957,7 +2033,7 @@ var Rerank = class {
1957
2033
  };
1958
2034
 
1959
2035
  // src/version.ts
1960
- var VERSION = "0.20.0";
2036
+ var VERSION = "0.21.1";
1961
2037
  var USER_AGENT = `pendra-node/${VERSION}`;
1962
2038
 
1963
2039
  // src/client.ts
@@ -2064,6 +2140,7 @@ var Pendra = class {
2064
2140
  } finally {
2065
2141
  clearTimeout(timeoutId);
2066
2142
  }
2143
+ response = withIdleTimeout(response, controller, this.timeout);
2067
2144
  if (response.status === 404) {
2068
2145
  const body = await readErrorBody(response);
2069
2146
  const detail = typeof body === "object" && body !== null ? body.detail : void 0;
@@ -2072,7 +2149,7 @@ var Pendra = class {
2072
2149
  );
2073
2150
  }
2074
2151
  if (!response.ok) {
2075
- throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
2152
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText, response.headers);
2076
2153
  }
2077
2154
  const json = await response.json();
2078
2155
  await engine.resolveOrgKey(json.keys ?? []);
@@ -2108,9 +2185,10 @@ var Pendra = class {
2108
2185
  );
2109
2186
  }
2110
2187
  clearTimeout(timeoutId);
2188
+ if (!options.stream || !response.ok) response = withIdleTimeout(response, controller, timeout);
2111
2189
  if (!response.ok) {
2112
2190
  this.invalidateKeyCacheIfRekeyed(response);
2113
- throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
2191
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText, response.headers);
2114
2192
  }
2115
2193
  return { response, controller };
2116
2194
  }