pendra 0.6.1 → 0.9.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.js CHANGED
@@ -203,11 +203,78 @@ var Audio = class {
203
203
  }
204
204
  };
205
205
 
206
+ // src/_sse.ts
207
+ var DEFAULT_EVENT = "message";
208
+ function fieldValue(line, name) {
209
+ const value = line.slice(name.length + 1);
210
+ return value.startsWith(" ") ? value.slice(1) : value;
211
+ }
212
+ var SseDecoder = class {
213
+ constructor() {
214
+ this.buffer = "";
215
+ this.event = "";
216
+ this.data = [];
217
+ }
218
+ /** Feed a chunk of decoded text; returns the payloads it completed. */
219
+ push(text) {
220
+ this.buffer += text;
221
+ const lines = this.buffer.split("\n");
222
+ this.buffer = lines.pop() ?? "";
223
+ const out = [];
224
+ for (const line of lines) {
225
+ const payload = this.pushLine(line);
226
+ if (payload !== null) out.push(payload);
227
+ }
228
+ return out;
229
+ }
230
+ /**
231
+ * Release what the stream ended without terminating: the held-back partial
232
+ * line, plus any frame that never got its blank line.
233
+ *
234
+ * The spec discards an unterminated final block; we keep it, so a connection
235
+ * that drops after the last `data:` line but before its blank line still
236
+ * delivers that payload rather than silently losing it.
237
+ */
238
+ flush() {
239
+ const out = [];
240
+ if (this.buffer !== "") {
241
+ const payload = this.pushLine(this.buffer);
242
+ this.buffer = "";
243
+ if (payload !== null) out.push(payload);
244
+ }
245
+ const tail = this.endFrame();
246
+ if (tail !== null) out.push(tail);
247
+ return out;
248
+ }
249
+ pushLine(rawLine) {
250
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
251
+ if (line === "") return this.endFrame();
252
+ if (line.startsWith(":")) return null;
253
+ if (line.startsWith("event:")) {
254
+ this.event = fieldValue(line, "event");
255
+ return null;
256
+ }
257
+ if (line.startsWith("data:")) {
258
+ this.data.push(fieldValue(line, "data"));
259
+ return null;
260
+ }
261
+ return null;
262
+ }
263
+ endFrame() {
264
+ const { data, event } = this;
265
+ this.data = [];
266
+ this.event = "";
267
+ if (data.length === 0) return null;
268
+ if (event !== "" && event !== DEFAULT_EVENT) return null;
269
+ return data.join("\n");
270
+ }
271
+ };
272
+
206
273
  // src/streaming.ts
207
274
  var Stream = class {
208
275
  constructor(response, controller) {
209
276
  this.decoder = new TextDecoder();
210
- this.buffer = "";
277
+ this.sse = new SseDecoder();
211
278
  this.done = false;
212
279
  if (!response.body) {
213
280
  throw new Error("Response body is null \u2014 streaming not supported");
@@ -219,18 +286,8 @@ var Stream = class {
219
286
  try {
220
287
  while (!this.done) {
221
288
  const { value, done: readerDone } = await this.reader.read();
222
- if (readerDone) {
223
- this.done = true;
224
- break;
225
- }
226
- this.buffer += this.decoder.decode(value, { stream: true });
227
- const lines = this.buffer.split("\n");
228
- this.buffer = lines.pop() ?? "";
229
- for (const line of lines) {
230
- const trimmed = line.trim();
231
- if (!trimmed || trimmed.startsWith(":")) continue;
232
- if (!trimmed.startsWith("data: ")) continue;
233
- const data = trimmed.slice(6);
289
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
290
+ for (const data of payloads) {
234
291
  if (data === "[DONE]") {
235
292
  this.done = true;
236
293
  return;
@@ -240,6 +297,10 @@ var Stream = class {
240
297
  } catch {
241
298
  }
242
299
  }
300
+ if (readerDone) {
301
+ this.done = true;
302
+ break;
303
+ }
243
304
  }
244
305
  } finally {
245
306
  this.reader.releaseLock();
@@ -255,7 +316,8 @@ var Stream = class {
255
316
  var DECODER = new TextDecoder();
256
317
  var EncryptedStream = class {
257
318
  constructor(response, controller, decryptor) {
258
- this.buffer = "";
319
+ this.decoder = new TextDecoder();
320
+ this.sse = new SseDecoder();
259
321
  this.done = false;
260
322
  if (!response.body) {
261
323
  throw new Error("Response body is null \u2014 streaming not supported");
@@ -268,18 +330,8 @@ var EncryptedStream = class {
268
330
  try {
269
331
  while (!this.done) {
270
332
  const { value, done: readerDone } = await this.reader.read();
271
- if (readerDone) {
272
- this.done = true;
273
- break;
274
- }
275
- this.buffer += DECODER.decode(value, { stream: true });
276
- const lines = this.buffer.split("\n");
277
- this.buffer = lines.pop() ?? "";
278
- for (const line of lines) {
279
- const trimmed = line.trim();
280
- if (!trimmed || trimmed.startsWith(":") || trimmed.startsWith("event:")) continue;
281
- if (!trimmed.startsWith("data:")) continue;
282
- const data = trimmed.slice("data:".length).trimStart();
333
+ const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
334
+ for (const data of payloads) {
283
335
  if (data === "[DONE]") {
284
336
  this.done = true;
285
337
  return;
@@ -309,6 +361,10 @@ var EncryptedStream = class {
309
361
  } catch {
310
362
  }
311
363
  }
364
+ if (readerDone) {
365
+ this.done = true;
366
+ break;
367
+ }
312
368
  }
313
369
  } finally {
314
370
  this.reader.releaseLock();
@@ -336,7 +392,19 @@ var Completions = class {
336
392
  if (params.temperature != null) body.temperature = params.temperature;
337
393
  if (params.max_tokens != null) body.max_tokens = params.max_tokens;
338
394
  if (params.top_p != null) body.top_p = params.top_p;
395
+ if (params.top_k != null) body.top_k = params.top_k;
396
+ if (params.min_p != null) body.min_p = params.min_p;
397
+ if (params.frequency_penalty != null)
398
+ body.frequency_penalty = params.frequency_penalty;
399
+ if (params.presence_penalty != null)
400
+ body.presence_penalty = params.presence_penalty;
401
+ if (params.repeat_penalty != null) body.repeat_penalty = params.repeat_penalty;
402
+ if (params.seed != null) body.seed = params.seed;
339
403
  if (params.stop != null) body.stop = params.stop;
404
+ if (params.tools != null) body.tools = params.tools;
405
+ if (params.tool_choice != null) body.tool_choice = params.tool_choice;
406
+ if (params.parallel_tool_calls != null)
407
+ body.parallel_tool_calls = params.parallel_tool_calls;
340
408
  const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
341
409
  if (this.client.privateInferenceEnabled) {
342
410
  return this.createEncrypted(params, body, headers);
@@ -614,12 +682,12 @@ var Rerank = class {
614
682
  };
615
683
 
616
684
  // src/_hpke.ts
617
- var import_ed25519 = require("@noble/curves/ed25519");
618
- var import_chacha = require("@noble/ciphers/chacha");
619
- var import_sha256 = require("@noble/hashes/sha256");
620
- var import_hmac = require("@noble/hashes/hmac");
621
- var import_hkdf = require("@noble/hashes/hkdf");
622
- var import_utils = require("@noble/hashes/utils");
685
+ var import_ed25519 = require("@noble/curves/ed25519.js");
686
+ var import_chacha = require("@noble/ciphers/chacha.js");
687
+ var import_sha2 = require("@noble/hashes/sha2.js");
688
+ var import_hmac = require("@noble/hashes/hmac.js");
689
+ var import_hkdf = require("@noble/hashes/hkdf.js");
690
+ var import_utils = require("@noble/hashes/utils.js");
623
691
  var KEM_ID = 32;
624
692
  var KDF_ID = 1;
625
693
  var AEAD_ID = 3;
@@ -655,10 +723,10 @@ var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
655
723
  var HPKE_VERSION = bytes("HPKE-v1");
656
724
  function hkdfExtract(salt, ikm) {
657
725
  const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
658
- return (0, import_hkdf.extract)(import_sha256.sha256, ikm, effectiveSalt);
726
+ return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
659
727
  }
660
728
  function hkdfExpand(prk, info, length) {
661
- return (0, import_hkdf.expand)(import_sha256.sha256, prk, info, length);
729
+ return (0, import_hkdf.expand)(import_sha2.sha256, prk, info, length);
662
730
  }
663
731
  function labeledExtract(salt, label, ikm, suiteId) {
664
732
  return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
@@ -672,7 +740,7 @@ function extractAndExpand(dh, kemContext) {
672
740
  return labeledExpand(eaePrk, bytes("shared_secret"), kemContext, NSECRET, KEM_SUITE_ID);
673
741
  }
674
742
  function encap(pkR, skE) {
675
- const skEObj = skE ?? import_ed25519.x25519.utils.randomPrivateKey();
743
+ const skEObj = skE ?? import_ed25519.x25519.utils.randomSecretKey();
676
744
  const enc = import_ed25519.x25519.getPublicKey(skEObj);
677
745
  const dh = import_ed25519.x25519.getSharedSecret(skEObj, pkR);
678
746
  const kemContext = concat(enc, pkR);
@@ -733,19 +801,19 @@ function setupBaseR(skR, enc, info) {
733
801
  return keySchedule(sharedSecret, info);
734
802
  }
735
803
  function generateX25519Keypair() {
736
- const priv = import_ed25519.x25519.utils.randomPrivateKey();
804
+ const priv = import_ed25519.x25519.utils.randomSecretKey();
737
805
  return { priv, pub: import_ed25519.x25519.getPublicKey(priv) };
738
806
  }
739
807
  function randomBytes(n) {
740
808
  return (0, import_utils.randomBytes)(n);
741
809
  }
742
810
  function sha256Hex(data) {
743
- return Array.from((0, import_sha256.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
811
+ return Array.from((0, import_sha2.sha256)(data)).map((b) => b.toString(16).padStart(2, "0")).join("");
744
812
  }
745
813
 
746
814
  // src/_privateInference.ts
747
- var import_chacha2 = require("@noble/ciphers/chacha");
748
- var import_hkdf2 = require("@noble/hashes/hkdf");
815
+ var import_chacha2 = require("@noble/ciphers/chacha.js");
816
+ var import_hkdf2 = require("@noble/hashes/hkdf.js");
749
817
  var ENVELOPE_VERSION = 1;
750
818
  var TEXT_ENCODER2 = new TextEncoder();
751
819
  var TEXT_DECODER = new TextDecoder();
@@ -809,18 +877,35 @@ function seqNonce(seq) {
809
877
  }
810
878
  return nonce;
811
879
  }
812
- function sealRequest(orgPub, body, opts) {
880
+ function sealRequest(orgPubs, body, opts) {
881
+ const pubs = Array.isArray(orgPubs) ? orgPubs : [orgPubs];
882
+ if (pubs.length === 0) {
883
+ throw new Error("sealRequest: no org public keys to seal to");
884
+ }
885
+ const seen = /* @__PURE__ */ new Set();
886
+ const uniquePubs = [];
887
+ for (const p of pubs) {
888
+ const fp = fingerprint(p);
889
+ if (!seen.has(fp)) {
890
+ seen.add(fp);
891
+ uniquePubs.push(p);
892
+ }
893
+ }
813
894
  const { priv: respPriv, pub: respPub } = generateX25519Keypair();
814
895
  const respPkB64 = b64(respPub);
815
896
  const dek = randomBytes(32);
816
897
  const nonce = randomBytes(12);
817
898
  const aad = buildAad(opts.model, opts.stream, opts.taskType, respPkB64);
818
899
  const ciphertext = (0, import_chacha2.chacha20poly1305)(dek, nonce, aad).encrypt(body);
819
- const { enc, ctx: sealer } = setupBaseS(orgPub, SUITE_INFO);
820
- const sealedDek = sealer.seal(new Uint8Array(0), dek);
900
+ const recipients = [];
901
+ for (const pub of uniquePubs) {
902
+ const { enc, ctx: sealer } = setupBaseS(pub, SUITE_INFO);
903
+ const sealedDek = sealer.seal(new Uint8Array(0), dek);
904
+ recipients.push({ kid: fingerprint(pub), enc: b64(enc), sealed_dek: b64(sealedDek) });
905
+ }
821
906
  const envelope = {
822
907
  v: ENVELOPE_VERSION,
823
- recipients: [{ kid: fingerprint(orgPub), enc: b64(enc), sealed_dek: b64(sealedDek) }],
908
+ recipients,
824
909
  nonce: b64(nonce),
825
910
  ciphertext: b64(ciphertext),
826
911
  response_pk: respPkB64
@@ -869,8 +954,8 @@ var ResponseDecryptor = class {
869
954
  }
870
955
  };
871
956
  function deriveSalt(rawApiKey) {
872
- const prk = (0, import_hkdf2.extract)(import_sha256.sha256, utf8(rawApiKey), new Uint8Array(32));
873
- return (0, import_hkdf2.expand)(import_sha256.sha256, prk, AFFINITY_SALT_INFO, 32);
957
+ const prk = (0, import_hkdf2.extract)(import_sha2.sha256, utf8(rawApiKey), new Uint8Array(32));
958
+ return (0, import_hkdf2.expand)(import_sha2.sha256, prk, AFFINITY_SALT_INFO, 32);
874
959
  }
875
960
  function canonicalJson(value) {
876
961
  if (value === null) return "null";
@@ -944,7 +1029,7 @@ function affinityKey(rawApiKey, model, messages, saltOverride) {
944
1029
  }
945
1030
  if (!sawUser) return null;
946
1031
  const salt = saltOverride != null ? saltOverride : deriveSalt(rawApiKey);
947
- const mac = import_hmac.hmac(import_sha256.sha256, salt, utf8(parts.join("\0")));
1032
+ const mac = import_hmac.hmac(import_sha2.sha256, salt, utf8(parts.join("\0")));
948
1033
  return toHex(mac);
949
1034
  }
950
1035
 
@@ -970,72 +1055,88 @@ function b64d2(s) {
970
1055
  }
971
1056
  var PrivateInferenceEngine = class {
972
1057
  constructor(opts) {
973
- this.orgPub = null;
1058
+ this.orgPubs = null;
974
1059
  this.baseUrl = opts.baseUrl.replace(/\/$/, "");
975
1060
  this.apiKey = opts.apiKey;
976
- const pin = (opts.pinnedFingerprint || "").trim().toLowerCase();
977
- this.pinnedFingerprint = pin || null;
1061
+ const fps = (opts.pinnedFingerprint || "").split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1062
+ this.pinnedFingerprints = fps.length > 0 ? new Set(fps) : null;
978
1063
  this.affinitySalt = opts.affinitySalt ?? null;
979
1064
  this.tofuPath = opts.tofuPath || defaultTofuPath();
980
1065
  }
981
1066
  // --- key resolution ---
1067
+ cachedOrgPublicKeys() {
1068
+ return this.orgPubs;
1069
+ }
982
1070
  cachedOrgPublicKey() {
983
- return this.orgPub;
1071
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
984
1072
  }
985
1073
  tofuIdentity() {
986
1074
  const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
987
1075
  return `${this.baseUrl}|${digest}`;
988
1076
  }
989
1077
  /**
990
- * Validate the key(s) returned by GET /v1/private-inference/key against the
991
- * pin or TOFU record, cache the accepted public key, and return it. Throws
992
- * PrivateInferenceError on absence or a fingerprint mismatch.
1078
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1079
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1080
+ * them (newest-seen first). The client seals to **all** of the returned keys
1081
+ * so any worker holding any of them can serve the request. Throws
1082
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1083
+ * intersection with the pin set.
993
1084
  */
994
1085
  async resolveOrgKey(fetchedKeys) {
995
- if (this.orgPub !== null) return this.orgPub;
1086
+ if (this.orgPubs !== null) return this.orgPubs;
996
1087
  if (!fetchedKeys || fetchedKeys.length === 0) {
997
1088
  throw new PrivateInferenceError(
998
1089
  "No private-inference workload key is registered for this organisation. Run `pendra keygen --save` on your worker(s), then reconnect them."
999
1090
  );
1000
1091
  }
1001
- const newest = fetchedKeys[0];
1002
- let orgPub;
1003
- try {
1004
- orgPub = b64d2(newest.public_key);
1005
- } catch (e) {
1006
- throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1007
- }
1008
- if (orgPub.length !== 32) {
1009
- throw new PrivateInferenceError(
1010
- `Workload key from the server is ${orgPub.length} bytes; expected a 32-byte X25519 key.`
1011
- );
1092
+ const pubs = [];
1093
+ const fps = [];
1094
+ for (const entry of fetchedKeys) {
1095
+ let pub;
1096
+ try {
1097
+ pub = b64d2(entry.public_key);
1098
+ } catch (e) {
1099
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1100
+ }
1101
+ if (pub.length !== 32) {
1102
+ throw new PrivateInferenceError(
1103
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1104
+ );
1105
+ }
1106
+ pubs.push(pub);
1107
+ fps.push(fingerprint(pub));
1012
1108
  }
1013
- const fp = fingerprint(orgPub);
1014
- if (this.pinnedFingerprint !== null) {
1015
- if (fp !== this.pinnedFingerprint) {
1109
+ let accepted;
1110
+ if (this.pinnedFingerprints !== null) {
1111
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1112
+ if (accepted.length === 0) {
1113
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
1016
1114
  throw new PrivateInferenceError(
1017
- `Workload key fingerprint ${fp} does not match your pinned fingerprint ${this.pinnedFingerprint}. Refusing to use it (possible man-in-the-middle). Verify the fingerprint from \`pendra keygen\` and update the pin if you rotated keys.`
1115
+ `None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). Verify the fingerprint(s) from \`pendra keygen\` and update the pin if you rotated keys.`
1018
1116
  );
1019
1117
  }
1020
1118
  } else {
1021
- await this.checkTofu(fp);
1119
+ await this.tofuTrust(fps);
1120
+ accepted = pubs;
1022
1121
  }
1023
- this.orgPub = orgPub;
1024
- return orgPub;
1122
+ this.orgPubs = accepted;
1123
+ return accepted;
1025
1124
  }
1026
- async checkTofu(fp) {
1125
+ async tofuTrust(fps) {
1027
1126
  const store = await this.loadTofu();
1028
1127
  const identity = this.tofuIdentity();
1029
1128
  const known = store[identity];
1030
- if (known === void 0) {
1031
- store[identity] = fp;
1032
- await this.saveTofu(store);
1033
- return;
1129
+ const trusted = /* @__PURE__ */ new Set();
1130
+ if (typeof known === "string") {
1131
+ trusted.add(known);
1132
+ } else if (Array.isArray(known)) {
1133
+ for (const f of known) if (typeof f === "string") trusted.add(f);
1034
1134
  }
1035
- if (known !== fp) {
1036
- throw new PrivateInferenceError(
1037
- `Workload key fingerprint changed for ${this.baseUrl}: pinned ${known}, server now returns ${fp}. If you rotated your org key this is expected \u2014 verify the new fingerprint out-of-band (from \`pendra keygen\`) and delete the entry in ${this.tofuPath} to re-pin. If you did NOT rotate, this may be a man-in-the-middle and the request has been refused.`
1038
- );
1135
+ const before = trusted.size;
1136
+ for (const f of fps) trusted.add(f);
1137
+ if (trusted.size !== before || !Array.isArray(known)) {
1138
+ store[identity] = Array.from(trusted).sort();
1139
+ await this.saveTofu(store);
1039
1140
  }
1040
1141
  }
1041
1142
  async loadTofu() {
@@ -1075,7 +1176,7 @@ var PrivateInferenceEngine = class {
1075
1176
  * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
1076
1177
  */
1077
1178
  seal(args) {
1078
- if (this.orgPub === null) {
1179
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
1079
1180
  throw new PrivateInferenceError(
1080
1181
  "private inference: org key not resolved yet (call resolveOrgKey first)"
1081
1182
  );
@@ -1084,7 +1185,7 @@ var PrivateInferenceEngine = class {
1084
1185
  if (args.messages != null) {
1085
1186
  affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1086
1187
  }
1087
- const { envelope, responsePriv } = sealRequest(this.orgPub, args.body, {
1188
+ const { envelope, responsePriv } = sealRequest(this.orgPubs, args.body, {
1088
1189
  model: args.model,
1089
1190
  stream: args.stream,
1090
1191
  taskType: args.taskType,
@@ -1164,7 +1265,7 @@ var Pendra = class {
1164
1265
  if (!this._piEngine) {
1165
1266
  throw new PrivateInferenceError("private inference is not enabled on this client");
1166
1267
  }
1167
- if (this._piEngine.cachedOrgPublicKey() !== null) {
1268
+ if (this._piEngine.cachedOrgPublicKeys() !== null) {
1168
1269
  return this._piEngine;
1169
1270
  }
1170
1271
  if (!this._piKeyFetch) {