pendra 0.16.0 → 0.17.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/dist/index.js CHANGED
@@ -407,12 +407,23 @@ function sealRequest(orgPubs, body, opts) {
407
407
  }
408
408
  return { envelope, responseKeys };
409
409
  }
410
- var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
411
- function isApiTimingChunk(frame) {
410
+ var API_TRAILER_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
411
+ var API_TRAILER_PENDRA_KEYS = /* @__PURE__ */ new Set(["timing", "worker", "request_id"]);
412
+ function isApiTrailerChunk(frame) {
412
413
  if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
413
414
  const obj = frame;
414
415
  const pendra = obj.pendra;
415
- return Object.keys(obj).every((k) => API_TIMING_CHUNK_KEYS.has(k)) && Array.isArray(obj.choices) && obj.choices.length === 0 && pendra !== null && typeof pendra === "object" && Object.keys(pendra).length === 1 && "timing" in pendra;
416
+ if (!Object.keys(obj).every((k) => API_TRAILER_CHUNK_KEYS.has(k)) || !Array.isArray(obj.choices) || obj.choices.length !== 0 || pendra === null || typeof pendra !== "object" || Array.isArray(pendra)) {
417
+ return false;
418
+ }
419
+ const block = pendra;
420
+ const keys = Object.keys(block);
421
+ if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;
422
+ if ("worker" in block && (block.worker === null || typeof block.worker !== "object" || Array.isArray(block.worker))) {
423
+ return false;
424
+ }
425
+ if ("request_id" in block && typeof block.request_id !== "string") return false;
426
+ return true;
416
427
  }
417
428
  function unsealedReplyError() {
418
429
  return new Error(
@@ -550,6 +561,7 @@ function affinityKey(rawApiKey, model, messages, saltOverride) {
550
561
  const mac = import_hmac.hmac(import_sha2.sha256, salt, utf8(parts.join("\0")));
551
562
  return toHex(mac);
552
563
  }
564
+ var _internal = { b64, b64d, utf8, TEXT_DECODER };
553
565
 
554
566
  // src/_parsing.ts
555
567
  function asString(v) {
@@ -612,8 +624,14 @@ async function parseCompletion(response) {
612
624
  body
613
625
  });
614
626
  }
627
+ throwIfInBandError(parsed, "The server reported an error");
615
628
  return completionFrom(parsed, body, response.status);
616
629
  }
630
+ async function readJsonReply(response) {
631
+ const parsed = await response.json();
632
+ throwIfInBandError(parsed, "The server reported an error");
633
+ return parsed;
634
+ }
617
635
  function parseDecryptedCompletion(json, status) {
618
636
  let parsed;
619
637
  try {
@@ -645,9 +663,10 @@ async function readSealedReply(response) {
645
663
  });
646
664
  }
647
665
  throwIfInBandError(parsed, "The server reported an error");
648
- const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
666
+ const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
667
+ const inner = wrapper?.pendra_encrypted;
649
668
  if (!inner) throw unsealedReplyError();
650
- return inner;
669
+ return { inner, placement: wrapper.pendra };
651
670
  }
652
671
  function parseDecryptedJson(json, status) {
653
672
  try {
@@ -658,7 +677,393 @@ function parseDecryptedJson(json, status) {
658
677
  body: json
659
678
  });
660
679
  }
661
- }
680
+ }
681
+
682
+ // src/_placement.ts
683
+ var UTF8_EXT_PREFIX = "utf-8''";
684
+ function isPlainObject(v) {
685
+ return typeof v === "object" && v !== null && !Array.isArray(v);
686
+ }
687
+ function parseWorker(v) {
688
+ if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
689
+ return {
690
+ id: v.id,
691
+ name: typeof v.name === "string" && v.name ? v.name : null,
692
+ version: typeof v.version === "string" && v.version ? v.version : null
693
+ };
694
+ }
695
+ function placementFromBlock(block) {
696
+ if (!isPlainObject(block)) return void 0;
697
+ const worker = parseWorker(block.worker);
698
+ if (!worker) return void 0;
699
+ const requestId = block.request_id;
700
+ return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
701
+ }
702
+ function decodeWorkerNameHeader(raw) {
703
+ if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
704
+ try {
705
+ return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
706
+ } catch {
707
+ return raw;
708
+ }
709
+ }
710
+ function header(headers, name) {
711
+ if (!headers || typeof headers.get !== "function") return void 0;
712
+ return headers.get(name) || void 0;
713
+ }
714
+ function placementFromHeaders(headers) {
715
+ const id = header(headers, "X-Worker-Id");
716
+ if (!id) return void 0;
717
+ const rawName = header(headers, "X-Worker-Name");
718
+ const requestId = header(headers, "X-Request-Id");
719
+ const worker = {
720
+ id,
721
+ name: rawName ? decodeWorkerNameHeader(rawName) : null,
722
+ version: null
723
+ };
724
+ return requestId ? { worker, request_id: requestId } : { worker };
725
+ }
726
+ function sanitise(block) {
727
+ if ("worker" in block && block.worker !== null) {
728
+ const worker = parseWorker(block.worker);
729
+ if (worker) block.worker = worker;
730
+ else delete block.worker;
731
+ }
732
+ if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
733
+ delete block.request_id;
734
+ }
735
+ }
736
+ function withPlacement(result, headers, ...blocks) {
737
+ if (!isPlainObject(result)) return result;
738
+ const own = isPlainObject(result.pendra) ? result.pendra : void 0;
739
+ if (own) sanitise(own);
740
+ let placement;
741
+ for (const block of blocks) {
742
+ placement = placementFromBlock(block);
743
+ if (placement) break;
744
+ }
745
+ placement ?? (placement = placementFromHeaders(headers));
746
+ if (!placement) return result;
747
+ const merged = { ...own ?? {}, worker: placement.worker };
748
+ if (placement.request_id) merged.request_id = placement.request_id;
749
+ else delete merged.request_id;
750
+ result.pendra = merged;
751
+ return result;
752
+ }
753
+ function chunkPlacement(chunk) {
754
+ const block = chunk.pendra;
755
+ if (!isPlainObject(block)) return {};
756
+ sanitise(block);
757
+ const worker = block.worker;
758
+ const requestId = block.request_id;
759
+ return { worker: worker ?? void 0, requestId: requestId || void 0 };
760
+ }
761
+ var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
762
+
763
+ // src/_privateInferenceEngine.ts
764
+ var PrivateInferenceError = class extends Error {
765
+ constructor(message) {
766
+ super(message);
767
+ this.name = "PrivateInferenceError";
768
+ }
769
+ };
770
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
771
+ function parsePinnedFingerprints(pin) {
772
+ if (typeof pin !== "string") {
773
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
774
+ }
775
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
776
+ if (fps.length === 0) {
777
+ throw new PrivateInferenceError(
778
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
779
+ );
780
+ }
781
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
782
+ if (bad.length > 0) {
783
+ throw new PrivateInferenceError(
784
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
785
+ );
786
+ }
787
+ return new Set(fps);
788
+ }
789
+ function defaultTofuPath() {
790
+ const env = typeof process !== "undefined" ? process.env : void 0;
791
+ if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
792
+ const home = env?.HOME || env?.USERPROFILE || ".";
793
+ return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
794
+ }
795
+ function b64d2(s) {
796
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
797
+ const binary = atob(s);
798
+ const out = new Uint8Array(binary.length);
799
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
800
+ return out;
801
+ }
802
+ var PrivateInferenceEngine = class {
803
+ constructor(opts) {
804
+ this.orgPubs = null;
805
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
806
+ this.apiKey = opts.apiKey;
807
+ const pin = opts.pinnedFingerprint;
808
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
809
+ this.affinitySalt = opts.affinitySalt ?? null;
810
+ this.tofuPath = opts.tofuPath || defaultTofuPath();
811
+ }
812
+ // --- key resolution ---
813
+ cachedOrgPublicKeys() {
814
+ return this.orgPubs;
815
+ }
816
+ cachedOrgPublicKey() {
817
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
818
+ }
819
+ tofuIdentity() {
820
+ const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
821
+ return `${this.baseUrl}|${digest}`;
822
+ }
823
+ /**
824
+ * Drop the cached key set so the next call re-fetches it.
825
+ *
826
+ * The cache is otherwise held for the whole process lifetime, which is
827
+ * correct while a fleet keeps one key but fatal when it re-keys: a
828
+ * long-running server would go on sealing to a fingerprint no worker holds
829
+ * and fail EVERY request until someone restarted it. The API signals a re-key
830
+ * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
831
+ * lets the client recover on its own.
832
+ *
833
+ * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
834
+ * allowlist, so a fetch could only return fingerprints the pin already
835
+ * rejects. They surface the error instead, which is what pinning means.
836
+ */
837
+ invalidateOrgKey() {
838
+ this.orgPubs = null;
839
+ }
840
+ /** Whether this client seals only to an explicit fingerprint allowlist. */
841
+ get isPinned() {
842
+ return this.pinnedFingerprints !== null;
843
+ }
844
+ /**
845
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
846
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
847
+ * them (newest-seen first). The client seals to **all** of the returned keys
848
+ * so any worker holding any of them can serve the request. Throws
849
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
850
+ * intersection with the pin set.
851
+ */
852
+ async resolveOrgKey(fetchedKeys) {
853
+ if (this.orgPubs !== null) return this.orgPubs;
854
+ if (!fetchedKeys || fetchedKeys.length === 0) {
855
+ throw new PrivateInferenceError(
856
+ "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
857
+ );
858
+ }
859
+ const pubs = [];
860
+ const fps = [];
861
+ for (const entry of fetchedKeys) {
862
+ let pub;
863
+ try {
864
+ pub = b64d2(entry.public_key);
865
+ } catch (e) {
866
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
867
+ }
868
+ if (pub.length !== 32) {
869
+ throw new PrivateInferenceError(
870
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
871
+ );
872
+ }
873
+ pubs.push(pub);
874
+ fps.push(fingerprint(pub));
875
+ }
876
+ let accepted;
877
+ if (this.pinnedFingerprints !== null) {
878
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
879
+ if (accepted.length === 0) {
880
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
881
+ throw new PrivateInferenceError(
882
+ `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.`
883
+ );
884
+ }
885
+ } else {
886
+ await this.tofuTrust(fps);
887
+ accepted = pubs;
888
+ }
889
+ this.orgPubs = accepted;
890
+ return accepted;
891
+ }
892
+ async tofuTrust(fps) {
893
+ const store = await this.loadTofu();
894
+ const identity = this.tofuIdentity();
895
+ const known = store[identity];
896
+ const trusted = /* @__PURE__ */ new Set();
897
+ if (typeof known === "string") {
898
+ trusted.add(known);
899
+ } else if (Array.isArray(known)) {
900
+ for (const f of known) if (typeof f === "string") trusted.add(f);
901
+ }
902
+ const before = trusted.size;
903
+ for (const f of fps) trusted.add(f);
904
+ if (trusted.size !== before || !Array.isArray(known)) {
905
+ store[identity] = Array.from(trusted).sort();
906
+ await this.saveTofu(store);
907
+ }
908
+ }
909
+ async loadTofu() {
910
+ 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 : {};
915
+ } catch {
916
+ return {};
917
+ }
918
+ }
919
+ async saveTofu(store) {
920
+ const fs = await import("fs");
921
+ const path = await import("path");
922
+ const directory = path.dirname(this.tofuPath) || ".";
923
+ fs.mkdirSync(directory, { recursive: true });
924
+ const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
925
+ try {
926
+ fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
927
+ try {
928
+ fs.chmodSync(tmp, 384);
929
+ } catch {
930
+ }
931
+ fs.renameSync(tmp, this.tofuPath);
932
+ } catch (e) {
933
+ try {
934
+ fs.unlinkSync(tmp);
935
+ } catch {
936
+ }
937
+ throw e;
938
+ }
939
+ }
940
+ // --- sealing ---
941
+ /**
942
+ * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
943
+ * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
944
+ * `binary` (audio only) is sealed under the same data key as the body.
945
+ */
946
+ seal(args) {
947
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
948
+ throw new PrivateInferenceError(
949
+ "private inference: org key not resolved yet (call resolveOrgKey first)"
950
+ );
951
+ }
952
+ let affinity = null;
953
+ if (args.messages != null) {
954
+ affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
955
+ }
956
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
957
+ model: args.model,
958
+ stream: args.stream,
959
+ taskType: args.taskType,
960
+ affinityKey: affinity,
961
+ binary: args.binary ?? null
962
+ });
963
+ const topLevel = {
964
+ model: args.model,
965
+ stream: args.stream,
966
+ pendra_encrypted: envelope
967
+ };
968
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
969
+ }
970
+ get keyFetchUrl() {
971
+ return `${this.baseUrl}/v1/private-inference/key`;
972
+ }
973
+ };
974
+
975
+ // src/resources/audio/speech.ts
976
+ var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
977
+ function decodeAudio(value) {
978
+ if (typeof value !== "string") return void 0;
979
+ const s = value.replace(/\s+/g, "");
980
+ if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
981
+ if (s.includes("=") && s.length % 4 !== 0) return void 0;
982
+ let bytes2;
983
+ try {
984
+ bytes2 = _internal.b64d(s);
985
+ } catch {
986
+ return void 0;
987
+ }
988
+ return bytes2.length > 0 ? bytes2 : void 0;
989
+ }
990
+ function isRecord2(v) {
991
+ return typeof v === "object" && v !== null && !Array.isArray(v);
992
+ }
993
+ var Speech = class {
994
+ constructor(client) {
995
+ this.client = client;
996
+ }
997
+ /**
998
+ * Turn text into spoken audio (OpenAI-compatible).
999
+ *
1000
+ * @example
1001
+ * ```ts
1002
+ * import { writeFileSync } from "node:fs";
1003
+ *
1004
+ * const speech = await client.audio.speech.create({
1005
+ * model: "qwen3-tts",
1006
+ * input: "Hello from Pendra.",
1007
+ * });
1008
+ * writeFileSync("speech.wav", speech.audio);
1009
+ * ```
1010
+ */
1011
+ async create(params) {
1012
+ if (!params.model || typeof params.model !== "string") {
1013
+ throw new Error("model must be a non-empty string");
1014
+ }
1015
+ if (typeof params.input !== "string" || !params.input.trim()) {
1016
+ throw new Error("input must be a non-empty string");
1017
+ }
1018
+ if (this.client.privateInferenceEnabled) {
1019
+ throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
1020
+ }
1021
+ const body = { model: params.model, input: params.input };
1022
+ if (params.voice != null) body.voice = params.voice;
1023
+ if (params.response_format != null) body.response_format = params.response_format;
1024
+ const headers = { Accept: "application/json" };
1025
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1026
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
1027
+ const { response } = await this.client._fetch("/api/v1/audio/speech", {
1028
+ method: "POST",
1029
+ body,
1030
+ headers,
1031
+ timeout
1032
+ });
1033
+ const text = await response.text();
1034
+ let parsed;
1035
+ try {
1036
+ parsed = JSON.parse(text);
1037
+ } catch {
1038
+ throw new APIResponseValidationError("Response was not valid JSON", {
1039
+ status: response.status,
1040
+ body: text
1041
+ });
1042
+ }
1043
+ throwIfInBandError(parsed, "The server reported an error");
1044
+ if (!isRecord2(parsed)) {
1045
+ throw new APIResponseValidationError("Response was not a speech result", {
1046
+ status: response.status,
1047
+ body: text
1048
+ });
1049
+ }
1050
+ const audio = decodeAudio(parsed.audio);
1051
+ if (!audio) {
1052
+ throw new APIResponseValidationError("Response did not contain decodable audio", {
1053
+ status: response.status,
1054
+ body: text
1055
+ });
1056
+ }
1057
+ const result = {
1058
+ audio,
1059
+ format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
1060
+ duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
1061
+ arrayBuffer: async () => audio.slice().buffer
1062
+ };
1063
+ if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
1064
+ return withPlacement(result, response.headers, result.pendra);
1065
+ }
1066
+ };
662
1067
 
663
1068
  // src/resources/audio/transcriptions.ts
664
1069
  var ENCODER = new TextEncoder();
@@ -759,9 +1164,10 @@ var Transcriptions = class {
759
1164
  const format = params.response_format;
760
1165
  if (format === "text" || format === "srt" || format === "vtt") {
761
1166
  const text = await response.text();
762
- return { text };
1167
+ return withPlacement({ text }, response.headers);
763
1168
  }
764
- return await response.json();
1169
+ const result = await readJsonReply(response);
1170
+ return withPlacement(result, response.headers, result.pendra);
765
1171
  }
766
1172
  /**
767
1173
  * Private-inference transcription. There is no multipart upload: the audio
@@ -796,9 +1202,11 @@ var Transcriptions = class {
796
1202
  timeout
797
1203
  }
798
1204
  );
799
- const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
1205
+ const { inner, placement } = await readSealedReply(response);
1206
+ const raw = DECODER.decode(decryptor.openResult(inner));
800
1207
  const parsed = parseDecryptedJson(raw, response.status);
801
- if (typeof parsed === "string") return { text: parsed };
1208
+ const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
1209
+ if (typeof parsed === "string") return place({ text: parsed });
802
1210
  if (typeof parsed === "object" && parsed !== null) {
803
1211
  if (typeof parsed.text !== "string") {
804
1212
  throw new APIResponseValidationError("Decrypted response was not a transcription", {
@@ -806,9 +1214,9 @@ var Transcriptions = class {
806
1214
  body: raw
807
1215
  });
808
1216
  }
809
- return parsed;
1217
+ return place(parsed);
810
1218
  }
811
- return { text: raw };
1219
+ return place({ text: raw });
812
1220
  }
813
1221
  };
814
1222
 
@@ -816,6 +1224,7 @@ var Transcriptions = class {
816
1224
  var Audio = class {
817
1225
  constructor(client) {
818
1226
  this.transcriptions = new Transcriptions(client);
1227
+ this.speech = new Speech(client);
819
1228
  }
820
1229
  };
821
1230
 
@@ -892,6 +1301,7 @@ var Stream = class {
892
1301
  this.decoder = new TextDecoder();
893
1302
  this.sse = new SseDecoder();
894
1303
  this.done = false;
1304
+ this.placement = new PlacementTracker();
895
1305
  if (!response.body) {
896
1306
  throw new Error("Response body is null \u2014 streaming not supported");
897
1307
  }
@@ -912,7 +1322,7 @@ var Stream = class {
912
1322
  this.done = true;
913
1323
  return;
914
1324
  }
915
- yield parseStreamFrame(data);
1325
+ yield this.placement.observe(parseStreamFrame(data));
916
1326
  }
917
1327
  if (readerDone) {
918
1328
  this.done = true;
@@ -923,11 +1333,39 @@ var Stream = class {
923
1333
  releaseReader(this.reader, this.controller, this.done);
924
1334
  }
925
1335
  }
1336
+ /**
1337
+ * The worker that served this stream, or `null` until the chunk reporting it
1338
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1339
+ * old to report it). Same as that chunk's `pendra.worker`.
1340
+ */
1341
+ get worker() {
1342
+ return this.placement.worker;
1343
+ }
1344
+ /**
1345
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1346
+ * `null` until then.
1347
+ */
1348
+ get requestId() {
1349
+ return this.placement.requestId;
1350
+ }
926
1351
  abort() {
927
1352
  this.done = true;
928
1353
  this.controller.abort();
929
1354
  }
930
1355
  };
1356
+ var PlacementTracker = class {
1357
+ constructor() {
1358
+ this.worker = null;
1359
+ this.requestId = null;
1360
+ }
1361
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1362
+ observe(chunk) {
1363
+ const { worker, requestId } = chunkPlacement(chunk);
1364
+ if (worker) this.worker = worker;
1365
+ if (requestId) this.requestId = requestId;
1366
+ return chunk;
1367
+ }
1368
+ };
931
1369
  async function readWithIdleTimeout(reader, idleTimeoutMs) {
932
1370
  if (!idleTimeoutMs) return reader.read();
933
1371
  let timer;
@@ -963,6 +1401,7 @@ var EncryptedStream = class {
963
1401
  this.openedAny = false;
964
1402
  this.declared = false;
965
1403
  this.terminated = false;
1404
+ this.placement = new PlacementTracker();
966
1405
  if (!response.body) {
967
1406
  throw new Error("Response body is null \u2014 streaming not supported");
968
1407
  }
@@ -1004,9 +1443,9 @@ var EncryptedStream = class {
1004
1443
  }
1005
1444
  const inner = frame?.pendra_encrypted;
1006
1445
  if (!inner) {
1007
- if (isApiTimingChunk(frame)) {
1446
+ if (isApiTrailerChunk(frame)) {
1008
1447
  this.checkEnded();
1009
- yield parseStreamFrame(data);
1448
+ yield this.placement.observe(parseStreamFrame(data));
1010
1449
  continue;
1011
1450
  }
1012
1451
  parseStreamFrame(data);
@@ -1034,7 +1473,7 @@ var EncryptedStream = class {
1034
1473
  return;
1035
1474
  }
1036
1475
  if (!chunkJson) continue;
1037
- yield parseStreamFrame(chunkJson, "Decrypted stream frame");
1476
+ yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
1038
1477
  }
1039
1478
  if (readerDone) {
1040
1479
  this.checkEnded();
@@ -1056,6 +1495,14 @@ var EncryptedStream = class {
1056
1495
  throw truncatedStreamError();
1057
1496
  }
1058
1497
  }
1498
+ /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
1499
+ get worker() {
1500
+ return this.placement.worker;
1501
+ }
1502
+ /** Same as `Stream.requestId`. */
1503
+ get requestId() {
1504
+ return this.placement.requestId;
1505
+ }
1059
1506
  abort() {
1060
1507
  this.aborted = true;
1061
1508
  this.done = true;
@@ -1076,7 +1523,9 @@ var Completions = class {
1076
1523
  for (const [key, value] of Object.entries(rest)) {
1077
1524
  if (value != null) body[key] = value;
1078
1525
  }
1079
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1526
+ const headers = {};
1527
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1528
+ if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
1080
1529
  if (this.client.privateInferenceEnabled) {
1081
1530
  return this.createEncrypted(params, body, headers);
1082
1531
  }
@@ -1091,7 +1540,8 @@ var Completions = class {
1091
1540
  "/api/v1/chat/completions",
1092
1541
  { method: "POST", body, headers }
1093
1542
  );
1094
- return parseCompletion(response);
1543
+ const completion = await parseCompletion(response);
1544
+ return withPlacement(completion, response.headers, completion.pendra);
1095
1545
  }
1096
1546
  async createEncrypted(params, body, headers) {
1097
1547
  const engine = await this.client._privateEngine();
@@ -1117,21 +1567,10 @@ var Completions = class {
1117
1567
  "/api/v1/chat/completions",
1118
1568
  { method: "POST", body: topLevel, headers }
1119
1569
  );
1120
- const raw = await response.text();
1121
- let wrapper;
1122
- try {
1123
- wrapper = JSON.parse(raw);
1124
- } catch {
1125
- throw new APIResponseValidationError("Response was not valid JSON", {
1126
- status: response.status,
1127
- body: raw
1128
- });
1129
- }
1130
- if (!wrapper.pendra_encrypted) {
1131
- throw unsealedReplyError();
1132
- }
1133
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
1134
- return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1570
+ const { inner, placement } = await readSealedReply(response);
1571
+ const plain = decryptor.openResult(inner);
1572
+ const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1573
+ return withPlacement(completion, response.headers, completion.pendra, placement);
1135
1574
  }
1136
1575
  };
1137
1576
 
@@ -1200,7 +1639,8 @@ var Embeddings = class {
1200
1639
  "/api/v1/embeddings",
1201
1640
  { method: "POST", body, headers }
1202
1641
  );
1203
- return await response.json();
1642
+ const result = await readJsonReply(response);
1643
+ return withPlacement(result, response.headers, result.pendra);
1204
1644
  }
1205
1645
  async createEncrypted(model, body, headers) {
1206
1646
  const engine = await this.client._privateEngine();
@@ -1214,12 +1654,10 @@ var Embeddings = class {
1214
1654
  "/api/v1/embeddings",
1215
1655
  { method: "POST", body: topLevel, headers }
1216
1656
  );
1217
- const wrapper = await response.json();
1218
- if (!wrapper.pendra_encrypted) {
1219
- throw unsealedReplyError();
1220
- }
1221
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
1222
- return JSON.parse(DECODER4.decode(plain));
1657
+ const { inner, placement } = await readSealedReply(response);
1658
+ const plain = decryptor.openResult(inner);
1659
+ const result = JSON.parse(DECODER4.decode(plain));
1660
+ return withPlacement(result, response.headers, result.pendra, placement);
1223
1661
  }
1224
1662
  };
1225
1663
 
@@ -1262,7 +1700,8 @@ var Generations = class {
1262
1700
  "/api/v1/images/generations",
1263
1701
  { method: "POST", body, headers }
1264
1702
  );
1265
- return await response.json();
1703
+ const result = await readJsonReply(response);
1704
+ return withPlacement(result, response.headers, result.pendra);
1266
1705
  }
1267
1706
  async createEncrypted(model, body, headers) {
1268
1707
  const engine = await this.client._privateEngine();
@@ -1276,7 +1715,8 @@ var Generations = class {
1276
1715
  "/api/v1/images/generations",
1277
1716
  { method: "POST", body: topLevel, headers }
1278
1717
  );
1279
- const plain = decryptor.openResult(await readSealedReply(response));
1718
+ const { inner, placement } = await readSealedReply(response);
1719
+ const plain = decryptor.openResult(inner);
1280
1720
  const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1281
1721
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1282
1722
  throw new APIResponseValidationError("Decrypted response was not an image generation", {
@@ -1284,7 +1724,8 @@ var Generations = class {
1284
1724
  body: DECODER5.decode(plain)
1285
1725
  });
1286
1726
  }
1287
- return parsed;
1727
+ const result = parsed;
1728
+ return withPlacement(result, response.headers, result.pendra, placement);
1288
1729
  }
1289
1730
  };
1290
1731
 
@@ -1362,7 +1803,8 @@ var Rerank = class {
1362
1803
  "/api/v1/rerank",
1363
1804
  { method: "POST", body, headers }
1364
1805
  );
1365
- return await response.json();
1806
+ const result = await readJsonReply(response);
1807
+ return withPlacement(result, response.headers, result.pendra);
1366
1808
  }
1367
1809
  async createEncrypted(model, body, headers) {
1368
1810
  const engine = await this.client._privateEngine();
@@ -1376,231 +1818,17 @@ var Rerank = class {
1376
1818
  "/api/v1/rerank",
1377
1819
  { method: "POST", body: topLevel, headers }
1378
1820
  );
1379
- const wrapper = await response.json();
1380
- if (!wrapper.pendra_encrypted) {
1381
- throw unsealedReplyError();
1382
- }
1383
- const plain = decryptor.openResult(wrapper.pendra_encrypted);
1384
- return JSON.parse(DECODER6.decode(plain));
1821
+ const { inner, placement } = await readSealedReply(response);
1822
+ const plain = decryptor.openResult(inner);
1823
+ const result = JSON.parse(DECODER6.decode(plain));
1824
+ return withPlacement(result, response.headers, result.pendra, placement);
1385
1825
  }
1386
1826
  };
1387
1827
 
1388
1828
  // src/version.ts
1389
- var VERSION = "0.16.0";
1829
+ var VERSION = "0.17.1";
1390
1830
  var USER_AGENT = `pendra-node/${VERSION}`;
1391
1831
 
1392
- // src/_privateInferenceEngine.ts
1393
- var PrivateInferenceError = class extends Error {
1394
- constructor(message) {
1395
- super(message);
1396
- this.name = "PrivateInferenceError";
1397
- }
1398
- };
1399
- var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1400
- function parsePinnedFingerprints(pin) {
1401
- if (typeof pin !== "string") {
1402
- throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1403
- }
1404
- const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1405
- if (fps.length === 0) {
1406
- throw new PrivateInferenceError(
1407
- "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1408
- );
1409
- }
1410
- const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1411
- if (bad.length > 0) {
1412
- throw new PrivateInferenceError(
1413
- `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1414
- );
1415
- }
1416
- return new Set(fps);
1417
- }
1418
- function defaultTofuPath() {
1419
- const env = typeof process !== "undefined" ? process.env : void 0;
1420
- if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
1421
- const home = env?.HOME || env?.USERPROFILE || ".";
1422
- return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
1423
- }
1424
- function b64d2(s) {
1425
- if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
1426
- const binary = atob(s);
1427
- const out = new Uint8Array(binary.length);
1428
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1429
- return out;
1430
- }
1431
- var PrivateInferenceEngine = class {
1432
- constructor(opts) {
1433
- this.orgPubs = null;
1434
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1435
- this.apiKey = opts.apiKey;
1436
- const pin = opts.pinnedFingerprint;
1437
- this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1438
- this.affinitySalt = opts.affinitySalt ?? null;
1439
- this.tofuPath = opts.tofuPath || defaultTofuPath();
1440
- }
1441
- // --- key resolution ---
1442
- cachedOrgPublicKeys() {
1443
- return this.orgPubs;
1444
- }
1445
- cachedOrgPublicKey() {
1446
- return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
1447
- }
1448
- tofuIdentity() {
1449
- const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
1450
- return `${this.baseUrl}|${digest}`;
1451
- }
1452
- /**
1453
- * Drop the cached key set so the next call re-fetches it.
1454
- *
1455
- * The cache is otherwise held for the whole process lifetime, which is
1456
- * correct while a fleet keeps one key but fatal when it re-keys: a
1457
- * long-running server would go on sealing to a fingerprint no worker holds
1458
- * and fail EVERY request until someone restarted it. The API signals a re-key
1459
- * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
1460
- * lets the client recover on its own.
1461
- *
1462
- * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
1463
- * allowlist, so a fetch could only return fingerprints the pin already
1464
- * rejects. They surface the error instead, which is what pinning means.
1465
- */
1466
- invalidateOrgKey() {
1467
- this.orgPubs = null;
1468
- }
1469
- /** Whether this client seals only to an explicit fingerprint allowlist. */
1470
- get isPinned() {
1471
- return this.pinnedFingerprints !== null;
1472
- }
1473
- /**
1474
- * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1475
- * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1476
- * them (newest-seen first). The client seals to **all** of the returned keys
1477
- * so any worker holding any of them can serve the request. Throws
1478
- * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1479
- * intersection with the pin set.
1480
- */
1481
- async resolveOrgKey(fetchedKeys) {
1482
- if (this.orgPubs !== null) return this.orgPubs;
1483
- if (!fetchedKeys || fetchedKeys.length === 0) {
1484
- throw new PrivateInferenceError(
1485
- "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
1486
- );
1487
- }
1488
- const pubs = [];
1489
- const fps = [];
1490
- for (const entry of fetchedKeys) {
1491
- let pub;
1492
- try {
1493
- pub = b64d2(entry.public_key);
1494
- } catch (e) {
1495
- throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1496
- }
1497
- if (pub.length !== 32) {
1498
- throw new PrivateInferenceError(
1499
- `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1500
- );
1501
- }
1502
- pubs.push(pub);
1503
- fps.push(fingerprint(pub));
1504
- }
1505
- let accepted;
1506
- if (this.pinnedFingerprints !== null) {
1507
- accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1508
- if (accepted.length === 0) {
1509
- const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
1510
- throw new PrivateInferenceError(
1511
- `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.`
1512
- );
1513
- }
1514
- } else {
1515
- await this.tofuTrust(fps);
1516
- accepted = pubs;
1517
- }
1518
- this.orgPubs = accepted;
1519
- return accepted;
1520
- }
1521
- async tofuTrust(fps) {
1522
- const store = await this.loadTofu();
1523
- const identity = this.tofuIdentity();
1524
- const known = store[identity];
1525
- const trusted = /* @__PURE__ */ new Set();
1526
- if (typeof known === "string") {
1527
- trusted.add(known);
1528
- } else if (Array.isArray(known)) {
1529
- for (const f of known) if (typeof f === "string") trusted.add(f);
1530
- }
1531
- const before = trusted.size;
1532
- for (const f of fps) trusted.add(f);
1533
- if (trusted.size !== before || !Array.isArray(known)) {
1534
- store[identity] = Array.from(trusted).sort();
1535
- await this.saveTofu(store);
1536
- }
1537
- }
1538
- async loadTofu() {
1539
- try {
1540
- const fs = await import("fs");
1541
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
1542
- const data = JSON.parse(raw);
1543
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
1544
- } catch {
1545
- return {};
1546
- }
1547
- }
1548
- async saveTofu(store) {
1549
- const fs = await import("fs");
1550
- const path = await import("path");
1551
- const directory = path.dirname(this.tofuPath) || ".";
1552
- fs.mkdirSync(directory, { recursive: true });
1553
- const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
1554
- try {
1555
- fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
1556
- try {
1557
- fs.chmodSync(tmp, 384);
1558
- } catch {
1559
- }
1560
- fs.renameSync(tmp, this.tofuPath);
1561
- } catch (e) {
1562
- try {
1563
- fs.unlinkSync(tmp);
1564
- } catch {
1565
- }
1566
- throw e;
1567
- }
1568
- }
1569
- // --- sealing ---
1570
- /**
1571
- * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
1572
- * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
1573
- * `binary` (audio only) is sealed under the same data key as the body.
1574
- */
1575
- seal(args) {
1576
- if (this.orgPubs === null || this.orgPubs.length === 0) {
1577
- throw new PrivateInferenceError(
1578
- "private inference: org key not resolved yet (call resolveOrgKey first)"
1579
- );
1580
- }
1581
- let affinity = null;
1582
- if (args.messages != null) {
1583
- affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1584
- }
1585
- const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
1586
- model: args.model,
1587
- stream: args.stream,
1588
- taskType: args.taskType,
1589
- affinityKey: affinity,
1590
- binary: args.binary ?? null
1591
- });
1592
- const topLevel = {
1593
- model: args.model,
1594
- stream: args.stream,
1595
- pendra_encrypted: envelope
1596
- };
1597
- return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1598
- }
1599
- get keyFetchUrl() {
1600
- return `${this.baseUrl}/v1/private-inference/key`;
1601
- }
1602
- };
1603
-
1604
1832
  // src/client.ts
1605
1833
  function envTruthy(v) {
1606
1834
  if (!v) return false;