pendra 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -764,6 +764,18 @@ function defaultTofuPath() {
764
764
  const home = env?.HOME || env?.USERPROFILE || ".";
765
765
  return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
766
766
  }
767
+ function isFsError(e) {
768
+ const err = e;
769
+ return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
770
+ }
771
+ var warnedTofuPaths = /* @__PURE__ */ new Set();
772
+ function warnTofuUnwritable(tofuPath, e) {
773
+ if (warnedTofuPaths.has(tofuPath)) return;
774
+ warnedTofuPaths.add(tofuPath);
775
+ console.warn(
776
+ `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.`
777
+ );
778
+ }
767
779
  function b64d2(s) {
768
780
  if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
769
781
  const binary = atob(s);
@@ -855,7 +867,12 @@ var PrivateInferenceEngine = class {
855
867
  );
856
868
  }
857
869
  } else {
858
- await this.tofuTrust(fps);
870
+ try {
871
+ await this.tofuTrust(fps);
872
+ } catch (e) {
873
+ if (!isFsError(e)) throw e;
874
+ warnTofuUnwritable(this.tofuPath, e);
875
+ }
859
876
  accepted = pubs;
860
877
  }
861
878
  this.orgPubs = accepted;
@@ -879,14 +896,21 @@ var PrivateInferenceEngine = class {
879
896
  }
880
897
  }
881
898
  async loadTofu() {
899
+ const fs = await import("fs");
900
+ let raw;
882
901
  try {
883
- const fs = await import("fs");
884
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
885
- const data = JSON.parse(raw);
886
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
902
+ raw = fs.readFileSync(this.tofuPath, "utf-8");
903
+ } catch (e) {
904
+ if (e.code === "ENOENT") return {};
905
+ throw e;
906
+ }
907
+ let data;
908
+ try {
909
+ data = JSON.parse(raw);
887
910
  } catch {
888
911
  return {};
889
912
  }
913
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
890
914
  }
891
915
  async saveTofu(store) {
892
916
  const fs = await import("fs");
@@ -1037,6 +1061,201 @@ var Speech = class {
1037
1061
  }
1038
1062
  };
1039
1063
 
1064
+ // src/_sse.ts
1065
+ var DEFAULT_EVENT = "message";
1066
+ function fieldValue(line, name) {
1067
+ const value = line.slice(name.length + 1);
1068
+ return value.startsWith(" ") ? value.slice(1) : value;
1069
+ }
1070
+ var SseDecoder = class {
1071
+ constructor() {
1072
+ this.buffer = "";
1073
+ this.event = "";
1074
+ this.data = [];
1075
+ }
1076
+ /** Feed a chunk of decoded text; returns the payloads it completed. */
1077
+ push(text) {
1078
+ this.buffer += text;
1079
+ const lines = this.buffer.split("\n");
1080
+ this.buffer = lines.pop() ?? "";
1081
+ const out = [];
1082
+ for (const line of lines) {
1083
+ const payload = this.pushLine(line);
1084
+ if (payload !== null) out.push(payload);
1085
+ }
1086
+ return out;
1087
+ }
1088
+ /**
1089
+ * Release what the stream ended without terminating: the held-back partial
1090
+ * line, plus any frame that never got its blank line.
1091
+ *
1092
+ * The spec discards an unterminated final block; we keep it, so a connection
1093
+ * that drops after the last `data:` line but before its blank line still
1094
+ * delivers that payload rather than silently losing it.
1095
+ */
1096
+ flush() {
1097
+ const out = [];
1098
+ if (this.buffer !== "") {
1099
+ const payload = this.pushLine(this.buffer);
1100
+ this.buffer = "";
1101
+ if (payload !== null) out.push(payload);
1102
+ }
1103
+ const tail = this.endFrame();
1104
+ if (tail !== null) out.push(tail);
1105
+ return out;
1106
+ }
1107
+ pushLine(rawLine) {
1108
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1109
+ if (line === "") return this.endFrame();
1110
+ if (line.startsWith(":")) return null;
1111
+ if (line.startsWith("event:")) {
1112
+ this.event = fieldValue(line, "event");
1113
+ return null;
1114
+ }
1115
+ if (line.startsWith("data:")) {
1116
+ this.data.push(fieldValue(line, "data"));
1117
+ return null;
1118
+ }
1119
+ return null;
1120
+ }
1121
+ endFrame() {
1122
+ const { data, event } = this;
1123
+ this.data = [];
1124
+ this.event = "";
1125
+ if (data.length === 0) return null;
1126
+ if (event !== "" && event !== DEFAULT_EVENT) return null;
1127
+ return data.join("\n");
1128
+ }
1129
+ };
1130
+
1131
+ // src/streaming.ts
1132
+ var Stream = class {
1133
+ constructor(response, controller, idleTimeoutMs) {
1134
+ this.decoder = new TextDecoder();
1135
+ this.sse = new SseDecoder();
1136
+ this.done = false;
1137
+ this.placement = new PlacementTracker();
1138
+ if (!response.body) {
1139
+ throw new Error("Response body is null \u2014 streaming not supported");
1140
+ }
1141
+ this.reader = response.body.getReader();
1142
+ this.controller = controller;
1143
+ this.idleTimeoutMs = idleTimeoutMs;
1144
+ }
1145
+ async *[Symbol.asyncIterator]() {
1146
+ try {
1147
+ while (!this.done) {
1148
+ const { value, done: readerDone } = await readWithIdleTimeout(
1149
+ this.reader,
1150
+ this.idleTimeoutMs
1151
+ );
1152
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
1153
+ for (const data of payloads) {
1154
+ if (data === "[DONE]") {
1155
+ this.done = true;
1156
+ return;
1157
+ }
1158
+ yield this.placement.observe(parseStreamFrame(data));
1159
+ }
1160
+ if (readerDone) {
1161
+ this.done = true;
1162
+ break;
1163
+ }
1164
+ }
1165
+ } finally {
1166
+ releaseReader(this.reader, this.controller, this.done);
1167
+ }
1168
+ }
1169
+ /**
1170
+ * The worker that served this stream, or `null` until the chunk reporting it
1171
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1172
+ * old to report it). Same as that chunk's `pendra.worker`.
1173
+ */
1174
+ get worker() {
1175
+ return this.placement.worker;
1176
+ }
1177
+ /**
1178
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1179
+ * `null` until then.
1180
+ */
1181
+ get requestId() {
1182
+ return this.placement.requestId;
1183
+ }
1184
+ abort() {
1185
+ this.done = true;
1186
+ this.controller.abort();
1187
+ }
1188
+ };
1189
+ var PlacementTracker = class {
1190
+ constructor() {
1191
+ this.worker = null;
1192
+ this.requestId = null;
1193
+ }
1194
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1195
+ observe(chunk) {
1196
+ const { worker, requestId } = chunkPlacement(chunk);
1197
+ if (worker) this.worker = worker;
1198
+ if (requestId) this.requestId = requestId;
1199
+ return chunk;
1200
+ }
1201
+ };
1202
+ async function readWithIdleTimeout(reader, idleTimeoutMs, what = "Stream") {
1203
+ if (!idleTimeoutMs) return reader.read();
1204
+ let timer;
1205
+ const idle = new Promise((_, reject) => {
1206
+ timer = setTimeout(
1207
+ () => reject(new APIConnectionError(`${what} received no data for ${idleTimeoutMs}ms`)),
1208
+ idleTimeoutMs
1209
+ );
1210
+ });
1211
+ try {
1212
+ return await Promise.race([reader.read(), idle]);
1213
+ } finally {
1214
+ clearTimeout(timer);
1215
+ }
1216
+ }
1217
+ function withIdleTimeout(response, controller, idleTimeoutMs) {
1218
+ const body = response.body;
1219
+ if (!idleTimeoutMs || !body || typeof body.getReader !== "function") return response;
1220
+ if (response.status < 200 || response.status > 599) return response;
1221
+ const reader = body.getReader();
1222
+ const guarded = new ReadableStream(
1223
+ {
1224
+ async pull(sink) {
1225
+ const chunk = await readWithIdleTimeout(reader, idleTimeoutMs, "Response body").catch(
1226
+ (err) => {
1227
+ controller.abort();
1228
+ reader.cancel().catch(() => {
1229
+ });
1230
+ throw err;
1231
+ }
1232
+ );
1233
+ if (chunk.done) sink.close();
1234
+ else sink.enqueue(chunk.value);
1235
+ },
1236
+ cancel(reason) {
1237
+ controller.abort();
1238
+ return reader.cancel(reason);
1239
+ }
1240
+ },
1241
+ // Read only on demand, so no idle timer runs while nobody is reading.
1242
+ { highWaterMark: 0 }
1243
+ );
1244
+ return new Response(guarded, {
1245
+ status: response.status,
1246
+ statusText: response.statusText,
1247
+ headers: response.headers
1248
+ });
1249
+ }
1250
+ function releaseReader(reader, controller, finished) {
1251
+ if (!finished) {
1252
+ controller.abort();
1253
+ reader.cancel().catch(() => {
1254
+ });
1255
+ }
1256
+ reader.releaseLock();
1257
+ }
1258
+
1040
1259
  // src/resources/audio/transcriptions.ts
1041
1260
  var ENCODER = new TextEncoder();
1042
1261
  var DECODER = new TextDecoder();
@@ -1139,6 +1358,7 @@ var Transcriptions = class {
1139
1358
  throw new APIConnectionError(String(err));
1140
1359
  }
1141
1360
  clearTimeout(timeoutId);
1361
+ response = withIdleTimeout(response, controller, timeout);
1142
1362
  if (response.status >= 400) {
1143
1363
  const body = await readErrorBody(response);
1144
1364
  throw statusErrorFromBody(response.status, body, response.statusText, response.headers);
@@ -1210,168 +1430,6 @@ var Audio = class {
1210
1430
  }
1211
1431
  };
1212
1432
 
1213
- // src/_sse.ts
1214
- var DEFAULT_EVENT = "message";
1215
- function fieldValue(line, name) {
1216
- const value = line.slice(name.length + 1);
1217
- return value.startsWith(" ") ? value.slice(1) : value;
1218
- }
1219
- var SseDecoder = class {
1220
- constructor() {
1221
- this.buffer = "";
1222
- this.event = "";
1223
- this.data = [];
1224
- }
1225
- /** Feed a chunk of decoded text; returns the payloads it completed. */
1226
- push(text) {
1227
- this.buffer += text;
1228
- const lines = this.buffer.split("\n");
1229
- this.buffer = lines.pop() ?? "";
1230
- const out = [];
1231
- for (const line of lines) {
1232
- const payload = this.pushLine(line);
1233
- if (payload !== null) out.push(payload);
1234
- }
1235
- return out;
1236
- }
1237
- /**
1238
- * Release what the stream ended without terminating: the held-back partial
1239
- * line, plus any frame that never got its blank line.
1240
- *
1241
- * The spec discards an unterminated final block; we keep it, so a connection
1242
- * that drops after the last `data:` line but before its blank line still
1243
- * delivers that payload rather than silently losing it.
1244
- */
1245
- flush() {
1246
- const out = [];
1247
- if (this.buffer !== "") {
1248
- const payload = this.pushLine(this.buffer);
1249
- this.buffer = "";
1250
- if (payload !== null) out.push(payload);
1251
- }
1252
- const tail = this.endFrame();
1253
- if (tail !== null) out.push(tail);
1254
- return out;
1255
- }
1256
- pushLine(rawLine) {
1257
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
1258
- if (line === "") return this.endFrame();
1259
- if (line.startsWith(":")) return null;
1260
- if (line.startsWith("event:")) {
1261
- this.event = fieldValue(line, "event");
1262
- return null;
1263
- }
1264
- if (line.startsWith("data:")) {
1265
- this.data.push(fieldValue(line, "data"));
1266
- return null;
1267
- }
1268
- return null;
1269
- }
1270
- endFrame() {
1271
- const { data, event } = this;
1272
- this.data = [];
1273
- this.event = "";
1274
- if (data.length === 0) return null;
1275
- if (event !== "" && event !== DEFAULT_EVENT) return null;
1276
- return data.join("\n");
1277
- }
1278
- };
1279
-
1280
- // src/streaming.ts
1281
- var Stream = class {
1282
- constructor(response, controller, idleTimeoutMs) {
1283
- this.decoder = new TextDecoder();
1284
- this.sse = new SseDecoder();
1285
- this.done = false;
1286
- this.placement = new PlacementTracker();
1287
- if (!response.body) {
1288
- throw new Error("Response body is null \u2014 streaming not supported");
1289
- }
1290
- this.reader = response.body.getReader();
1291
- this.controller = controller;
1292
- this.idleTimeoutMs = idleTimeoutMs;
1293
- }
1294
- async *[Symbol.asyncIterator]() {
1295
- try {
1296
- while (!this.done) {
1297
- const { value, done: readerDone } = await readWithIdleTimeout(
1298
- this.reader,
1299
- this.idleTimeoutMs
1300
- );
1301
- const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
1302
- for (const data of payloads) {
1303
- if (data === "[DONE]") {
1304
- this.done = true;
1305
- return;
1306
- }
1307
- yield this.placement.observe(parseStreamFrame(data));
1308
- }
1309
- if (readerDone) {
1310
- this.done = true;
1311
- break;
1312
- }
1313
- }
1314
- } finally {
1315
- releaseReader(this.reader, this.controller, this.done);
1316
- }
1317
- }
1318
- /**
1319
- * The worker that served this stream, or `null` until the chunk reporting it
1320
- * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1321
- * old to report it). Same as that chunk's `pendra.worker`.
1322
- */
1323
- get worker() {
1324
- return this.placement.worker;
1325
- }
1326
- /**
1327
- * Pendra's id for this request, reported alongside {@link Stream.worker};
1328
- * `null` until then.
1329
- */
1330
- get requestId() {
1331
- return this.placement.requestId;
1332
- }
1333
- abort() {
1334
- this.done = true;
1335
- this.controller.abort();
1336
- }
1337
- };
1338
- var PlacementTracker = class {
1339
- constructor() {
1340
- this.worker = null;
1341
- this.requestId = null;
1342
- }
1343
- /** Record `chunk`'s placement, if it carries any, and hand it back. */
1344
- observe(chunk) {
1345
- const { worker, requestId } = chunkPlacement(chunk);
1346
- if (worker) this.worker = worker;
1347
- if (requestId) this.requestId = requestId;
1348
- return chunk;
1349
- }
1350
- };
1351
- async function readWithIdleTimeout(reader, idleTimeoutMs) {
1352
- if (!idleTimeoutMs) return reader.read();
1353
- let timer;
1354
- const idle = new Promise((_, reject) => {
1355
- timer = setTimeout(
1356
- () => reject(new APIConnectionError(`Stream received no data for ${idleTimeoutMs}ms`)),
1357
- idleTimeoutMs
1358
- );
1359
- });
1360
- try {
1361
- return await Promise.race([reader.read(), idle]);
1362
- } finally {
1363
- clearTimeout(timer);
1364
- }
1365
- }
1366
- function releaseReader(reader, controller, finished) {
1367
- if (!finished) {
1368
- controller.abort();
1369
- reader.cancel().catch(() => {
1370
- });
1371
- }
1372
- reader.releaseLock();
1373
- }
1374
-
1375
1433
  // src/_privateStreaming.ts
1376
1434
  var DECODER2 = new TextDecoder();
1377
1435
  var EncryptedStream = class {
@@ -1514,7 +1572,7 @@ var Completions = class {
1514
1572
  if (params.stream) {
1515
1573
  const { response: response2, controller } = await this.client._fetch(
1516
1574
  "/api/v1/chat/completions",
1517
- { method: "POST", body, headers }
1575
+ { method: "POST", body, headers, stream: true }
1518
1576
  );
1519
1577
  return new Stream(response2, controller, this.client.timeout);
1520
1578
  }
@@ -1541,7 +1599,7 @@ var Completions = class {
1541
1599
  if (stream) {
1542
1600
  const { response: response2, controller } = await this.client._fetch(
1543
1601
  "/api/v1/chat/completions",
1544
- { method: "POST", body: topLevel, headers }
1602
+ { method: "POST", body: topLevel, headers, stream: true }
1545
1603
  );
1546
1604
  return new EncryptedStream(response2, controller, decryptor, this.client.timeout);
1547
1605
  }
@@ -1929,7 +1987,7 @@ var Rerank = class {
1929
1987
  };
1930
1988
 
1931
1989
  // src/version.ts
1932
- var VERSION = "0.21.0";
1990
+ var VERSION = "0.22.0";
1933
1991
  var USER_AGENT = `pendra-node/${VERSION}`;
1934
1992
 
1935
1993
  // src/client.ts
@@ -2036,6 +2094,7 @@ var Pendra = class {
2036
2094
  } finally {
2037
2095
  clearTimeout(timeoutId);
2038
2096
  }
2097
+ response = withIdleTimeout(response, controller, this.timeout);
2039
2098
  if (response.status === 404) {
2040
2099
  const body = await readErrorBody(response);
2041
2100
  const detail = typeof body === "object" && body !== null ? body.detail : void 0;
@@ -2080,6 +2139,7 @@ var Pendra = class {
2080
2139
  );
2081
2140
  }
2082
2141
  clearTimeout(timeoutId);
2142
+ if (!options.stream || !response.ok) response = withIdleTimeout(response, controller, timeout);
2083
2143
  if (!response.ok) {
2084
2144
  this.invalidateKeyCacheIfRekeyed(response);
2085
2145
  throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText, response.headers);