pendra 0.22.0 → 0.23.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
@@ -778,243 +778,9 @@ function chunkPlacement(chunk) {
778
778
  }
779
779
  var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
780
780
 
781
- // src/_privateInferenceEngine.ts
782
- var PrivateInferenceError = class extends Error {
783
- constructor(message) {
784
- super(message);
785
- this.name = "PrivateInferenceError";
786
- }
787
- };
788
- var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
789
- function parsePinnedFingerprints(pin) {
790
- if (typeof pin !== "string") {
791
- throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
792
- }
793
- const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
794
- if (fps.length === 0) {
795
- throw new PrivateInferenceError(
796
- "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
797
- );
798
- }
799
- const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
800
- if (bad.length > 0) {
801
- throw new PrivateInferenceError(
802
- `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
803
- );
804
- }
805
- return new Set(fps);
806
- }
807
- function defaultTofuPath() {
808
- const env = typeof process !== "undefined" ? process.env : void 0;
809
- if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
810
- const home = env?.HOME || env?.USERPROFILE || ".";
811
- return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
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
- }
825
- function b64d2(s) {
826
- if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
827
- const binary = atob(s);
828
- const out = new Uint8Array(binary.length);
829
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
830
- return out;
831
- }
832
- var PrivateInferenceEngine = class {
833
- constructor(opts) {
834
- this.orgPubs = null;
835
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
836
- this.apiKey = opts.apiKey;
837
- const pin = opts.pinnedFingerprint;
838
- this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
839
- this.affinitySalt = opts.affinitySalt ?? null;
840
- this.tofuPath = opts.tofuPath || defaultTofuPath();
841
- }
842
- // --- key resolution ---
843
- cachedOrgPublicKeys() {
844
- return this.orgPubs;
845
- }
846
- cachedOrgPublicKey() {
847
- return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
848
- }
849
- tofuIdentity() {
850
- const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
851
- return `${this.baseUrl}|${digest}`;
852
- }
853
- /**
854
- * Drop the cached key set so the next call re-fetches it.
855
- *
856
- * The cache is otherwise held for the whole process lifetime, which is
857
- * correct while a fleet keeps one key but fatal when it re-keys: a
858
- * long-running server would go on sealing to a fingerprint no worker holds
859
- * and fail EVERY request until someone restarted it. The API signals a re-key
860
- * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
861
- * lets the client recover on its own.
862
- *
863
- * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
864
- * allowlist, so a fetch could only return fingerprints the pin already
865
- * rejects. They surface the error instead, which is what pinning means.
866
- */
867
- invalidateOrgKey() {
868
- this.orgPubs = null;
869
- }
870
- /** Whether this client seals only to an explicit fingerprint allowlist. */
871
- get isPinned() {
872
- return this.pinnedFingerprints !== null;
873
- }
874
- /**
875
- * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
876
- * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
877
- * them (newest-seen first). The client seals to **all** of the returned keys
878
- * so any worker holding any of them can serve the request. Throws
879
- * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
880
- * intersection with the pin set.
881
- */
882
- async resolveOrgKey(fetchedKeys) {
883
- if (this.orgPubs !== null) return this.orgPubs;
884
- if (!fetchedKeys || fetchedKeys.length === 0) {
885
- throw new PrivateInferenceError(
886
- "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
887
- );
888
- }
889
- const pubs = [];
890
- const fps = [];
891
- for (const entry of fetchedKeys) {
892
- let pub;
893
- try {
894
- pub = b64d2(entry.public_key);
895
- } catch (e) {
896
- throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
897
- }
898
- if (pub.length !== 32) {
899
- throw new PrivateInferenceError(
900
- `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
901
- );
902
- }
903
- pubs.push(pub);
904
- fps.push(fingerprint(pub));
905
- }
906
- let accepted;
907
- if (this.pinnedFingerprints !== null) {
908
- accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
909
- if (accepted.length === 0) {
910
- const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
911
- throw new PrivateInferenceError(
912
- `None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
913
- );
914
- }
915
- } else {
916
- try {
917
- await this.tofuTrust(fps);
918
- } catch (e) {
919
- if (!isFsError(e)) throw e;
920
- warnTofuUnwritable(this.tofuPath, e);
921
- }
922
- accepted = pubs;
923
- }
924
- this.orgPubs = accepted;
925
- return accepted;
926
- }
927
- async tofuTrust(fps) {
928
- const store = await this.loadTofu();
929
- const identity = this.tofuIdentity();
930
- const known = store[identity];
931
- const trusted = /* @__PURE__ */ new Set();
932
- if (typeof known === "string") {
933
- trusted.add(known);
934
- } else if (Array.isArray(known)) {
935
- for (const f of known) if (typeof f === "string") trusted.add(f);
936
- }
937
- const before = trusted.size;
938
- for (const f of fps) trusted.add(f);
939
- if (trusted.size !== before || !Array.isArray(known)) {
940
- store[identity] = Array.from(trusted).sort();
941
- await this.saveTofu(store);
942
- }
943
- }
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;
954
- try {
955
- data = JSON.parse(raw);
956
- } catch {
957
- return {};
958
- }
959
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
960
- }
961
- async saveTofu(store) {
962
- const fs = await import("fs");
963
- const path = await import("path");
964
- const directory = path.dirname(this.tofuPath) || ".";
965
- fs.mkdirSync(directory, { recursive: true });
966
- const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
967
- try {
968
- fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
969
- try {
970
- fs.chmodSync(tmp, 384);
971
- } catch {
972
- }
973
- fs.renameSync(tmp, this.tofuPath);
974
- } catch (e) {
975
- try {
976
- fs.unlinkSync(tmp);
977
- } catch {
978
- }
979
- throw e;
980
- }
981
- }
982
- // --- sealing ---
983
- /**
984
- * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
985
- * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
986
- * `binary` (audio only) is sealed under the same data key as the body.
987
- */
988
- seal(args) {
989
- if (this.orgPubs === null || this.orgPubs.length === 0) {
990
- throw new PrivateInferenceError(
991
- "private inference: org key not resolved yet (call resolveOrgKey first)"
992
- );
993
- }
994
- let affinity = null;
995
- if (args.messages != null) {
996
- affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
997
- }
998
- const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
999
- model: args.model,
1000
- stream: args.stream,
1001
- taskType: args.taskType,
1002
- affinityKey: affinity,
1003
- binary: args.binary ?? null
1004
- });
1005
- const topLevel = {
1006
- model: args.model,
1007
- stream: args.stream,
1008
- pendra_encrypted: envelope
1009
- };
1010
- return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1011
- }
1012
- get keyFetchUrl() {
1013
- return `${this.baseUrl}/v1/private-inference/key`;
1014
- }
1015
- };
1016
-
1017
781
  // src/resources/audio/speech.ts
782
+ var ENCODER = new TextEncoder();
783
+ var DECODER = new TextDecoder();
1018
784
  var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
1019
785
  function decodeAudio(value) {
1020
786
  if (typeof value !== "string") return void 0;
@@ -1057,15 +823,15 @@ var Speech = class {
1057
823
  if (typeof params.input !== "string" || !params.input.trim()) {
1058
824
  throw new Error("input must be a non-empty string");
1059
825
  }
1060
- if (this.client.privateInferenceEnabled) {
1061
- throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
1062
- }
1063
826
  const body = { model: params.model, input: params.input };
1064
827
  if (params.voice != null) body.voice = params.voice;
1065
828
  if (params.response_format != null) body.response_format = params.response_format;
1066
829
  const headers = { Accept: "application/json" };
1067
830
  if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1068
831
  const timeout = Math.max(this.client.timeout ?? 0, 3e5);
832
+ if (this.client.privateInferenceEnabled) {
833
+ return this.createEncrypted(params, body, timeout);
834
+ }
1069
835
  const { response } = await this.client._fetch("/api/v1/audio/speech", {
1070
836
  method: "POST",
1071
837
  body,
@@ -1083,29 +849,57 @@ var Speech = class {
1083
849
  });
1084
850
  }
1085
851
  throwIfInBandError(parsed, "The server reported an error");
1086
- if (!isRecord2(parsed)) {
1087
- throw new APIResponseValidationError("Response was not a speech result", {
1088
- status: response.status,
1089
- body: text
1090
- });
1091
- }
1092
- const audio = decodeAudio(parsed.audio);
1093
- if (!audio) {
1094
- throw new APIResponseValidationError("Response did not contain decodable audio", {
1095
- status: response.status,
1096
- body: text
1097
- });
1098
- }
1099
- const result = {
1100
- audio,
1101
- format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
1102
- duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
1103
- arrayBuffer: async () => audio.slice().buffer
1104
- };
1105
- if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
1106
- return withPlacement(result, response.headers, result.pendra);
852
+ return speechFrom(parsed, text, params, response);
853
+ }
854
+ /**
855
+ * Private-inference speech. The request options are the sealed JSON body;
856
+ * the worker seals the same `{ audio, format, duration_ms }` result a
857
+ * plaintext JSON reply carries, so the audio comes back exactly as it does
858
+ * without encryption.
859
+ */
860
+ async createEncrypted(params, body, timeout) {
861
+ const engine = await this.client._privateEngine();
862
+ const { topLevel, decryptor } = engine.seal({
863
+ model: params.model,
864
+ stream: false,
865
+ taskType: "speech",
866
+ body: ENCODER.encode(JSON.stringify(body))
867
+ });
868
+ const { response } = await this.client._fetch("/api/v1/audio/speech", {
869
+ method: "POST",
870
+ body: topLevel,
871
+ headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
872
+ timeout
873
+ });
874
+ const { inner, placement } = await readSealedReply(response);
875
+ const raw = DECODER.decode(decryptor.openResult(inner));
876
+ const parsed = parseDecryptedJson(raw, response.status);
877
+ return speechFrom(parsed, raw, params, response, placement);
1107
878
  }
1108
879
  };
880
+ function speechFrom(parsed, raw, params, response, placement) {
881
+ if (!isRecord2(parsed)) {
882
+ throw new APIResponseValidationError("Response was not a speech result", {
883
+ status: response.status,
884
+ body: raw
885
+ });
886
+ }
887
+ const audio = decodeAudio(parsed.audio);
888
+ if (!audio) {
889
+ throw new APIResponseValidationError("Response did not contain decodable audio", {
890
+ status: response.status,
891
+ body: raw
892
+ });
893
+ }
894
+ const result = {
895
+ audio,
896
+ format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
897
+ duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
898
+ arrayBuffer: async () => audio.slice().buffer
899
+ };
900
+ if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
901
+ return withPlacement(result, response.headers, result.pendra, placement);
902
+ }
1109
903
 
1110
904
  // src/_sse.ts
1111
905
  var DEFAULT_EVENT = "message";
@@ -1303,8 +1097,8 @@ function releaseReader(reader, controller, finished) {
1303
1097
  }
1304
1098
 
1305
1099
  // src/resources/audio/transcriptions.ts
1306
- var ENCODER = new TextEncoder();
1307
- var DECODER = new TextDecoder();
1100
+ var ENCODER2 = new TextEncoder();
1101
+ var DECODER2 = new TextDecoder();
1308
1102
  var MAX_FILE_SIZE = 25 * 1024 * 1024;
1309
1103
  var MIME_EXT = {
1310
1104
  "audio/mpeg": "mp3",
@@ -1438,7 +1232,7 @@ var Transcriptions = class {
1438
1232
  model: params.model,
1439
1233
  stream: false,
1440
1234
  taskType: "transcription",
1441
- body: ENCODER.encode(JSON.stringify(body)),
1235
+ body: ENCODER2.encode(JSON.stringify(body)),
1442
1236
  binary: new Uint8Array(await blob.arrayBuffer())
1443
1237
  });
1444
1238
  const { response } = await this.client._fetch(
@@ -1451,7 +1245,7 @@ var Transcriptions = class {
1451
1245
  }
1452
1246
  );
1453
1247
  const { inner, placement } = await readSealedReply(response);
1454
- const raw = DECODER.decode(decryptor.openResult(inner));
1248
+ const raw = DECODER2.decode(decryptor.openResult(inner));
1455
1249
  const parsed = parseDecryptedJson(raw, response.status);
1456
1250
  const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
1457
1251
  if (typeof parsed === "string") return place({ text: parsed });
@@ -1477,7 +1271,7 @@ var Audio = class {
1477
1271
  };
1478
1272
 
1479
1273
  // src/_privateStreaming.ts
1480
- var DECODER2 = new TextDecoder();
1274
+ var DECODER3 = new TextDecoder();
1481
1275
  var EncryptedStream = class {
1482
1276
  constructor(response, controller, decryptor, idleTimeoutMs) {
1483
1277
  this.decoder = new TextDecoder();
@@ -1543,7 +1337,7 @@ var EncryptedStream = class {
1543
1337
  );
1544
1338
  }
1545
1339
  const plain = this.decryptor.openChunk(inner);
1546
- const chunkJson = DECODER2.decode(plain).trim();
1340
+ const chunkJson = DECODER3.decode(plain).trim();
1547
1341
  const first = !this.openedAny;
1548
1342
  this.openedAny = true;
1549
1343
  if (first && isStreamTerminatorDeclaration(chunkJson)) {
@@ -1597,8 +1391,8 @@ var EncryptedStream = class {
1597
1391
  };
1598
1392
 
1599
1393
  // src/resources/chat/completions.ts
1600
- var ENCODER2 = new TextEncoder();
1601
- var DECODER3 = new TextDecoder();
1394
+ var ENCODER3 = new TextEncoder();
1395
+ var DECODER4 = new TextDecoder();
1602
1396
  var Completions = class {
1603
1397
  constructor(client) {
1604
1398
  this.client = client;
@@ -1639,7 +1433,7 @@ var Completions = class {
1639
1433
  // The terminator request rides inside the sealed body, so the relay can
1640
1434
  // neither strip nor add it: it asks the worker to seal the end of the
1641
1435
  // stream (#2157).
1642
- body: ENCODER2.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
1436
+ body: ENCODER3.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
1643
1437
  messages: params.messages
1644
1438
  });
1645
1439
  if (stream) {
@@ -1655,7 +1449,7 @@ var Completions = class {
1655
1449
  );
1656
1450
  const { inner, placement } = await readSealedReply(response);
1657
1451
  const plain = decryptor.openResult(inner);
1658
- const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1452
+ const completion = parseDecryptedCompletion(DECODER4.decode(plain), response.status);
1659
1453
  return withPlacement(completion, response.headers, completion.pendra, placement);
1660
1454
  }
1661
1455
  };
@@ -1668,8 +1462,8 @@ var Chat = class {
1668
1462
  };
1669
1463
 
1670
1464
  // src/resources/embeddings.ts
1671
- var ENCODER3 = new TextEncoder();
1672
- var DECODER4 = new TextDecoder();
1465
+ var ENCODER4 = new TextEncoder();
1466
+ var DECODER5 = new TextDecoder();
1673
1467
  function validateParams(params) {
1674
1468
  if (!params.model || typeof params.model !== "string") {
1675
1469
  throw new Error("model must be a non-empty string");
@@ -1735,7 +1529,7 @@ var Embeddings = class {
1735
1529
  model,
1736
1530
  stream: false,
1737
1531
  taskType: "embeddings",
1738
- body: ENCODER3.encode(JSON.stringify(body))
1532
+ body: ENCODER4.encode(JSON.stringify(body))
1739
1533
  });
1740
1534
  const { response } = await this.client._fetch(
1741
1535
  "/api/v1/embeddings",
@@ -1743,14 +1537,14 @@ var Embeddings = class {
1743
1537
  );
1744
1538
  const { inner, placement } = await readSealedReply(response);
1745
1539
  const plain = decryptor.openResult(inner);
1746
- const result = JSON.parse(DECODER4.decode(plain));
1540
+ const result = JSON.parse(DECODER5.decode(plain));
1747
1541
  return withPlacement(result, response.headers, result.pendra, placement);
1748
1542
  }
1749
1543
  };
1750
1544
 
1751
1545
  // src/resources/images/generations.ts
1752
- var ENCODER4 = new TextEncoder();
1753
- var DECODER5 = new TextDecoder();
1546
+ var ENCODER5 = new TextEncoder();
1547
+ var DECODER6 = new TextDecoder();
1754
1548
  var SIZE_RE = /^\d+x\d+$/;
1755
1549
  function validateParams2(params) {
1756
1550
  if (!params.prompt || !params.prompt.trim()) {
@@ -1796,7 +1590,7 @@ var Generations = class {
1796
1590
  model,
1797
1591
  stream: false,
1798
1592
  taskType: "image_generation",
1799
- body: ENCODER4.encode(JSON.stringify(body))
1593
+ body: ENCODER5.encode(JSON.stringify(body))
1800
1594
  });
1801
1595
  const { response } = await this.client._fetch(
1802
1596
  "/api/v1/images/generations",
@@ -1804,11 +1598,11 @@ var Generations = class {
1804
1598
  );
1805
1599
  const { inner, placement } = await readSealedReply(response);
1806
1600
  const plain = decryptor.openResult(inner);
1807
- const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1601
+ const parsed = parseDecryptedJson(DECODER6.decode(plain), response.status);
1808
1602
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1809
1603
  throw new APIResponseValidationError("Decrypted response was not an image generation", {
1810
1604
  status: response.status,
1811
- body: DECODER5.decode(plain)
1605
+ body: DECODER6.decode(plain)
1812
1606
  });
1813
1607
  }
1814
1608
  const result = parsed;
@@ -1838,8 +1632,8 @@ var Models = class {
1838
1632
  };
1839
1633
 
1840
1634
  // src/resources/moderations.ts
1841
- var ENCODER5 = new TextEncoder();
1842
- var DECODER6 = new TextDecoder();
1635
+ var ENCODER6 = new TextEncoder();
1636
+ var DECODER7 = new TextDecoder();
1843
1637
  var MAX_INPUTS = 32;
1844
1638
  function isPlainObject2(v) {
1845
1639
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1940,7 +1734,7 @@ var Moderations = class {
1940
1734
  model,
1941
1735
  stream: false,
1942
1736
  taskType: "moderation",
1943
- body: ENCODER5.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
1737
+ body: ENCODER6.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
1944
1738
  });
1945
1739
  const { response } = await this.client._fetch(
1946
1740
  "/api/v1/moderations",
@@ -1949,7 +1743,7 @@ var Moderations = class {
1949
1743
  const { inner, placement } = await readSealedReply(response);
1950
1744
  const plain = decryptor.openResult(inner);
1951
1745
  const result = asModeration(
1952
- parseDecryptedJson(DECODER6.decode(plain), response.status),
1746
+ parseDecryptedJson(DECODER7.decode(plain), response.status),
1953
1747
  response.status,
1954
1748
  "Decrypted response"
1955
1749
  );
@@ -1958,8 +1752,8 @@ var Moderations = class {
1958
1752
  };
1959
1753
 
1960
1754
  // src/resources/rerank.ts
1961
- var ENCODER6 = new TextEncoder();
1962
- var DECODER7 = new TextDecoder();
1755
+ var ENCODER7 = new TextEncoder();
1756
+ var DECODER8 = new TextDecoder();
1963
1757
  function validateParams4(params) {
1964
1758
  if (!params.model || typeof params.model !== "string") {
1965
1759
  throw new Error("model must be a non-empty string");
@@ -2019,7 +1813,7 @@ var Rerank = class {
2019
1813
  model,
2020
1814
  stream: false,
2021
1815
  taskType: "rerank",
2022
- body: ENCODER6.encode(JSON.stringify(body))
1816
+ body: ENCODER7.encode(JSON.stringify(body))
2023
1817
  });
2024
1818
  const { response } = await this.client._fetch(
2025
1819
  "/api/v1/rerank",
@@ -2027,15 +1821,251 @@ var Rerank = class {
2027
1821
  );
2028
1822
  const { inner, placement } = await readSealedReply(response);
2029
1823
  const plain = decryptor.openResult(inner);
2030
- const result = JSON.parse(DECODER7.decode(plain));
1824
+ const result = JSON.parse(DECODER8.decode(plain));
2031
1825
  return withPlacement(result, response.headers, result.pendra, placement);
2032
1826
  }
2033
1827
  };
2034
1828
 
2035
1829
  // src/version.ts
2036
- var VERSION = "0.22.0";
1830
+ var VERSION = "0.23.0";
2037
1831
  var USER_AGENT = `pendra-node/${VERSION}`;
2038
1832
 
1833
+ // src/_privateInferenceEngine.ts
1834
+ var PrivateInferenceError = class extends Error {
1835
+ constructor(message) {
1836
+ super(message);
1837
+ this.name = "PrivateInferenceError";
1838
+ }
1839
+ };
1840
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1841
+ function parsePinnedFingerprints(pin) {
1842
+ if (typeof pin !== "string") {
1843
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1844
+ }
1845
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1846
+ if (fps.length === 0) {
1847
+ throw new PrivateInferenceError(
1848
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1849
+ );
1850
+ }
1851
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1852
+ if (bad.length > 0) {
1853
+ throw new PrivateInferenceError(
1854
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1855
+ );
1856
+ }
1857
+ return new Set(fps);
1858
+ }
1859
+ function defaultTofuPath() {
1860
+ const env = typeof process !== "undefined" ? process.env : void 0;
1861
+ if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
1862
+ const home = env?.HOME || env?.USERPROFILE || ".";
1863
+ return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
1864
+ }
1865
+ function isFsError(e) {
1866
+ const err = e;
1867
+ return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
1868
+ }
1869
+ var warnedTofuPaths = /* @__PURE__ */ new Set();
1870
+ function warnTofuUnwritable(tofuPath, e) {
1871
+ if (warnedTofuPaths.has(tofuPath)) return;
1872
+ warnedTofuPaths.add(tofuPath);
1873
+ console.warn(
1874
+ `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.`
1875
+ );
1876
+ }
1877
+ function b64d2(s) {
1878
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
1879
+ const binary = atob(s);
1880
+ const out = new Uint8Array(binary.length);
1881
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1882
+ return out;
1883
+ }
1884
+ var PrivateInferenceEngine = class {
1885
+ constructor(opts) {
1886
+ this.orgPubs = null;
1887
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1888
+ this.apiKey = opts.apiKey;
1889
+ const pin = opts.pinnedFingerprint;
1890
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1891
+ this.affinitySalt = opts.affinitySalt ?? null;
1892
+ this.tofuPath = opts.tofuPath || defaultTofuPath();
1893
+ }
1894
+ // --- key resolution ---
1895
+ cachedOrgPublicKeys() {
1896
+ return this.orgPubs;
1897
+ }
1898
+ cachedOrgPublicKey() {
1899
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
1900
+ }
1901
+ tofuIdentity() {
1902
+ const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
1903
+ return `${this.baseUrl}|${digest}`;
1904
+ }
1905
+ /**
1906
+ * Drop the cached key set so the next call re-fetches it.
1907
+ *
1908
+ * The cache is otherwise held for the whole process lifetime, which is
1909
+ * correct while a fleet keeps one key but fatal when it re-keys: a
1910
+ * long-running server would go on sealing to a fingerprint no worker holds
1911
+ * and fail EVERY request until someone restarted it. The API signals a re-key
1912
+ * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
1913
+ * lets the client recover on its own.
1914
+ *
1915
+ * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
1916
+ * allowlist, so a fetch could only return fingerprints the pin already
1917
+ * rejects. They surface the error instead, which is what pinning means.
1918
+ */
1919
+ invalidateOrgKey() {
1920
+ this.orgPubs = null;
1921
+ }
1922
+ /** Whether this client seals only to an explicit fingerprint allowlist. */
1923
+ get isPinned() {
1924
+ return this.pinnedFingerprints !== null;
1925
+ }
1926
+ /**
1927
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1928
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1929
+ * them (newest-seen first). The client seals to **all** of the returned keys
1930
+ * so any worker holding any of them can serve the request. Throws
1931
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1932
+ * intersection with the pin set.
1933
+ */
1934
+ async resolveOrgKey(fetchedKeys) {
1935
+ if (this.orgPubs !== null) return this.orgPubs;
1936
+ if (!fetchedKeys || fetchedKeys.length === 0) {
1937
+ throw new PrivateInferenceError(
1938
+ "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
1939
+ );
1940
+ }
1941
+ const pubs = [];
1942
+ const fps = [];
1943
+ for (const entry of fetchedKeys) {
1944
+ let pub;
1945
+ try {
1946
+ pub = b64d2(entry.public_key);
1947
+ } catch (e) {
1948
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1949
+ }
1950
+ if (pub.length !== 32) {
1951
+ throw new PrivateInferenceError(
1952
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1953
+ );
1954
+ }
1955
+ pubs.push(pub);
1956
+ fps.push(fingerprint(pub));
1957
+ }
1958
+ let accepted;
1959
+ if (this.pinnedFingerprints !== null) {
1960
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1961
+ if (accepted.length === 0) {
1962
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
1963
+ throw new PrivateInferenceError(
1964
+ `None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
1965
+ );
1966
+ }
1967
+ } else {
1968
+ try {
1969
+ await this.tofuTrust(fps);
1970
+ } catch (e) {
1971
+ if (!isFsError(e)) throw e;
1972
+ warnTofuUnwritable(this.tofuPath, e);
1973
+ }
1974
+ accepted = pubs;
1975
+ }
1976
+ this.orgPubs = accepted;
1977
+ return accepted;
1978
+ }
1979
+ async tofuTrust(fps) {
1980
+ const store = await this.loadTofu();
1981
+ const identity = this.tofuIdentity();
1982
+ const known = store[identity];
1983
+ const trusted = /* @__PURE__ */ new Set();
1984
+ if (typeof known === "string") {
1985
+ trusted.add(known);
1986
+ } else if (Array.isArray(known)) {
1987
+ for (const f of known) if (typeof f === "string") trusted.add(f);
1988
+ }
1989
+ const before = trusted.size;
1990
+ for (const f of fps) trusted.add(f);
1991
+ if (trusted.size !== before || !Array.isArray(known)) {
1992
+ store[identity] = Array.from(trusted).sort();
1993
+ await this.saveTofu(store);
1994
+ }
1995
+ }
1996
+ async loadTofu() {
1997
+ const fs = await import("fs");
1998
+ let raw;
1999
+ try {
2000
+ raw = fs.readFileSync(this.tofuPath, "utf-8");
2001
+ } catch (e) {
2002
+ if (e.code === "ENOENT") return {};
2003
+ throw e;
2004
+ }
2005
+ let data;
2006
+ try {
2007
+ data = JSON.parse(raw);
2008
+ } catch {
2009
+ return {};
2010
+ }
2011
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
2012
+ }
2013
+ async saveTofu(store) {
2014
+ const fs = await import("fs");
2015
+ const path = await import("path");
2016
+ const directory = path.dirname(this.tofuPath) || ".";
2017
+ fs.mkdirSync(directory, { recursive: true });
2018
+ const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
2019
+ try {
2020
+ fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
2021
+ try {
2022
+ fs.chmodSync(tmp, 384);
2023
+ } catch {
2024
+ }
2025
+ fs.renameSync(tmp, this.tofuPath);
2026
+ } catch (e) {
2027
+ try {
2028
+ fs.unlinkSync(tmp);
2029
+ } catch {
2030
+ }
2031
+ throw e;
2032
+ }
2033
+ }
2034
+ // --- sealing ---
2035
+ /**
2036
+ * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
2037
+ * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
2038
+ * `binary` (audio only) is sealed under the same data key as the body.
2039
+ */
2040
+ seal(args) {
2041
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
2042
+ throw new PrivateInferenceError(
2043
+ "private inference: org key not resolved yet (call resolveOrgKey first)"
2044
+ );
2045
+ }
2046
+ let affinity = null;
2047
+ if (args.messages != null) {
2048
+ affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
2049
+ }
2050
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
2051
+ model: args.model,
2052
+ stream: args.stream,
2053
+ taskType: args.taskType,
2054
+ affinityKey: affinity,
2055
+ binary: args.binary ?? null
2056
+ });
2057
+ const topLevel = {
2058
+ model: args.model,
2059
+ stream: args.stream,
2060
+ pendra_encrypted: envelope
2061
+ };
2062
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
2063
+ }
2064
+ get keyFetchUrl() {
2065
+ return `${this.baseUrl}/v1/private-inference/key`;
2066
+ }
2067
+ };
2068
+
2039
2069
  // src/client.ts
2040
2070
  function envTruthy(v) {
2041
2071
  if (!v) return false;