pendra 0.21.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;
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;
package/dist/index.js CHANGED
@@ -810,6 +810,18 @@ function defaultTofuPath() {
810
810
  const home = env?.HOME || env?.USERPROFILE || ".";
811
811
  return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
812
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
+ }
813
825
  function b64d2(s) {
814
826
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
815
827
  const binary = atob(s);
@@ -901,7 +913,12 @@ var PrivateInferenceEngine = class {
901
913
  );
902
914
  }
903
915
  } else {
904
- 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
+ }
905
922
  accepted = pubs;
906
923
  }
907
924
  this.orgPubs = accepted;
@@ -925,14 +942,21 @@ var PrivateInferenceEngine = class {
925
942
  }
926
943
  }
927
944
  async loadTofu() {
945
+ const fs = await import("fs");
946
+ let raw;
928
947
  try {
929
- const fs = await import("fs");
930
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
931
- const data = JSON.parse(raw);
932
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
948
+ raw = fs.readFileSync(this.tofuPath, "utf-8");
949
+ } catch (e) {
950
+ if (e.code === "ENOENT") return {};
951
+ throw e;
952
+ }
953
+ let data;
954
+ try {
955
+ data = JSON.parse(raw);
933
956
  } catch {
934
957
  return {};
935
958
  }
959
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
936
960
  }
937
961
  async saveTofu(store) {
938
962
  const fs = await import("fs");
@@ -1083,6 +1107,201 @@ var Speech = class {
1083
1107
  }
1084
1108
  };
1085
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
+
1086
1305
  // src/resources/audio/transcriptions.ts
1087
1306
  var ENCODER = new TextEncoder();
1088
1307
  var DECODER = new TextDecoder();
@@ -1185,6 +1404,7 @@ var Transcriptions = class {
1185
1404
  throw new APIConnectionError(String(err));
1186
1405
  }
1187
1406
  clearTimeout(timeoutId);
1407
+ response = withIdleTimeout(response, controller, timeout);
1188
1408
  if (response.status >= 400) {
1189
1409
  const body = await readErrorBody(response);
1190
1410
  throw statusErrorFromBody(response.status, body, response.statusText, response.headers);
@@ -1256,168 +1476,6 @@ var Audio = class {
1256
1476
  }
1257
1477
  };
1258
1478
 
1259
- // src/_sse.ts
1260
- var DEFAULT_EVENT = "message";
1261
- function fieldValue(line, name) {
1262
- const value = line.slice(name.length + 1);
1263
- return value.startsWith(" ") ? value.slice(1) : value;
1264
- }
1265
- var SseDecoder = class {
1266
- constructor() {
1267
- this.buffer = "";
1268
- this.event = "";
1269
- this.data = [];
1270
- }
1271
- /** Feed a chunk of decoded text; returns the payloads it completed. */
1272
- push(text) {
1273
- this.buffer += text;
1274
- const lines = this.buffer.split("\n");
1275
- this.buffer = lines.pop() ?? "";
1276
- const out = [];
1277
- for (const line of lines) {
1278
- const payload = this.pushLine(line);
1279
- if (payload !== null) out.push(payload);
1280
- }
1281
- return out;
1282
- }
1283
- /**
1284
- * Release what the stream ended without terminating: the held-back partial
1285
- * line, plus any frame that never got its blank line.
1286
- *
1287
- * The spec discards an unterminated final block; we keep it, so a connection
1288
- * that drops after the last `data:` line but before its blank line still
1289
- * delivers that payload rather than silently losing it.
1290
- */
1291
- flush() {
1292
- const out = [];
1293
- if (this.buffer !== "") {
1294
- const payload = this.pushLine(this.buffer);
1295
- this.buffer = "";
1296
- if (payload !== null) out.push(payload);
1297
- }
1298
- const tail = this.endFrame();
1299
- if (tail !== null) out.push(tail);
1300
- return out;
1301
- }
1302
- pushLine(rawLine) {
1303
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1304
- if (line === "") return this.endFrame();
1305
- if (line.startsWith(":")) return null;
1306
- if (line.startsWith("event:")) {
1307
- this.event = fieldValue(line, "event");
1308
- return null;
1309
- }
1310
- if (line.startsWith("data:")) {
1311
- this.data.push(fieldValue(line, "data"));
1312
- return null;
1313
- }
1314
- return null;
1315
- }
1316
- endFrame() {
1317
- const { data, event } = this;
1318
- this.data = [];
1319
- this.event = "";
1320
- if (data.length === 0) return null;
1321
- if (event !== "" && event !== DEFAULT_EVENT) return null;
1322
- return data.join("\n");
1323
- }
1324
- };
1325
-
1326
- // src/streaming.ts
1327
- var Stream = class {
1328
- constructor(response, controller, idleTimeoutMs) {
1329
- this.decoder = new TextDecoder();
1330
- this.sse = new SseDecoder();
1331
- this.done = false;
1332
- this.placement = new PlacementTracker();
1333
- if (!response.body) {
1334
- throw new Error("Response body is null \u2014 streaming not supported");
1335
- }
1336
- this.reader = response.body.getReader();
1337
- this.controller = controller;
1338
- this.idleTimeoutMs = idleTimeoutMs;
1339
- }
1340
- async *[Symbol.asyncIterator]() {
1341
- try {
1342
- while (!this.done) {
1343
- const { value, done: readerDone } = await readWithIdleTimeout(
1344
- this.reader,
1345
- this.idleTimeoutMs
1346
- );
1347
- const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
1348
- for (const data of payloads) {
1349
- if (data === "[DONE]") {
1350
- this.done = true;
1351
- return;
1352
- }
1353
- yield this.placement.observe(parseStreamFrame(data));
1354
- }
1355
- if (readerDone) {
1356
- this.done = true;
1357
- break;
1358
- }
1359
- }
1360
- } finally {
1361
- releaseReader(this.reader, this.controller, this.done);
1362
- }
1363
- }
1364
- /**
1365
- * The worker that served this stream, or `null` until the chunk reporting it
1366
- * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1367
- * old to report it). Same as that chunk's `pendra.worker`.
1368
- */
1369
- get worker() {
1370
- return this.placement.worker;
1371
- }
1372
- /**
1373
- * Pendra's id for this request, reported alongside {@link Stream.worker};
1374
- * `null` until then.
1375
- */
1376
- get requestId() {
1377
- return this.placement.requestId;
1378
- }
1379
- abort() {
1380
- this.done = true;
1381
- this.controller.abort();
1382
- }
1383
- };
1384
- var PlacementTracker = class {
1385
- constructor() {
1386
- this.worker = null;
1387
- this.requestId = null;
1388
- }
1389
- /** Record `chunk`'s placement, if it carries any, and hand it back. */
1390
- observe(chunk) {
1391
- const { worker, requestId } = chunkPlacement(chunk);
1392
- if (worker) this.worker = worker;
1393
- if (requestId) this.requestId = requestId;
1394
- return chunk;
1395
- }
1396
- };
1397
- async function readWithIdleTimeout(reader, idleTimeoutMs) {
1398
- if (!idleTimeoutMs) return reader.read();
1399
- let timer;
1400
- const idle = new Promise((_, reject) => {
1401
- timer = setTimeout(
1402
- () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
1403
- idleTimeoutMs
1404
- );
1405
- });
1406
- try {
1407
- return await Promise.race([reader.read(), idle]);
1408
- } finally {
1409
- clearTimeout(timer);
1410
- }
1411
- }
1412
- function releaseReader(reader, controller, finished) {
1413
- if (!finished) {
1414
- controller.abort();
1415
- reader.cancel().catch(() => {
1416
- });
1417
- }
1418
- reader.releaseLock();
1419
- }
1420
-
1421
1479
  // src/_privateStreaming.ts
1422
1480
  var DECODER2 = new TextDecoder();
1423
1481
  var EncryptedStream = class {
@@ -1560,7 +1618,7 @@ var Completions = class {
1560
1618
  if (params.stream) {
1561
1619
  const { response: response2, controller } = await this.client._fetch(
1562
1620
  "/api/v1/chat/completions",
1563
- { method: "POST", body, headers }
1621
+ { method: "POST", body, headers, stream: true }
1564
1622
  );
1565
1623
  return new Stream(response2, controller, this.client.timeout);
1566
1624
  }
@@ -1587,7 +1645,7 @@ var Completions = class {
1587
1645
  if (stream) {
1588
1646
  const { response: response2, controller } = await this.client._fetch(
1589
1647
  "/api/v1/chat/completions",
1590
- { method: "POST", body: topLevel, headers }
1648
+ { method: "POST", body: topLevel, headers, stream: true }
1591
1649
  );
1592
1650
  return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
1593
1651
  }
@@ -1975,7 +2033,7 @@ var Rerank = class {
1975
2033
  };
1976
2034
 
1977
2035
  // src/version.ts
1978
- var VERSION = "0.21.0";
2036
+ var VERSION = "0.21.1";
1979
2037
  var USER_AGENT = `pendra-node/${VERSION}`;
1980
2038
 
1981
2039
  // src/client.ts
@@ -2082,6 +2140,7 @@ var Pendra = class {
2082
2140
  } finally {
2083
2141
  clearTimeout(timeoutId);
2084
2142
  }
2143
+ response = withIdleTimeout(response, controller, this.timeout);
2085
2144
  if (response.status === 404) {
2086
2145
  const body = await readErrorBody(response);
2087
2146
  const detail = typeof body === "object" && body !== null ? body.detail : void 0;
@@ -2126,6 +2185,7 @@ var Pendra = class {
2126
2185
  );
2127
2186
  }
2128
2187
  clearTimeout(timeoutId);
2188
+ if (!options.stream || !response.ok) response = withIdleTimeout(response, controller, timeout);
2129
2189
  if (!response.ok) {
2130
2190
  this.invalidateKeyCacheIfRekeyed(response);
2131
2191
  throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText, response.headers);