pendra 0.16.0 → 0.17.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
@@ -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) {
@@ -645,9 +657,10 @@ async function readSealedReply(response) {
645
657
  });
646
658
  }
647
659
  throwIfInBandError(parsed, "The server reported an error");
648
- const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
660
+ const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
661
+ const inner = wrapper?.pendra_encrypted;
649
662
  if (!inner) throw unsealedReplyError();
650
- return inner;
663
+ return { inner, placement: wrapper.pendra };
651
664
  }
652
665
  function parseDecryptedJson(json, status) {
653
666
  try {
@@ -660,6 +673,392 @@ function parseDecryptedJson(json, status) {
660
673
  }
661
674
  }
662
675
 
676
+ // src/_placement.ts
677
+ var UTF8_EXT_PREFIX = "utf-8''";
678
+ function isPlainObject(v) {
679
+ return typeof v === "object" && v !== null && !Array.isArray(v);
680
+ }
681
+ function parseWorker(v) {
682
+ if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
683
+ return {
684
+ id: v.id,
685
+ name: typeof v.name === "string" && v.name ? v.name : null,
686
+ version: typeof v.version === "string" && v.version ? v.version : null
687
+ };
688
+ }
689
+ function placementFromBlock(block) {
690
+ if (!isPlainObject(block)) return void 0;
691
+ const worker = parseWorker(block.worker);
692
+ if (!worker) return void 0;
693
+ const requestId = block.request_id;
694
+ return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
695
+ }
696
+ function decodeWorkerNameHeader(raw) {
697
+ if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
698
+ try {
699
+ return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
700
+ } catch {
701
+ return raw;
702
+ }
703
+ }
704
+ function header(headers, name) {
705
+ if (!headers || typeof headers.get !== "function") return void 0;
706
+ return headers.get(name) || void 0;
707
+ }
708
+ function placementFromHeaders(headers) {
709
+ const id = header(headers, "X-Worker-Id");
710
+ if (!id) return void 0;
711
+ const rawName = header(headers, "X-Worker-Name");
712
+ const requestId = header(headers, "X-Request-Id");
713
+ const worker = {
714
+ id,
715
+ name: rawName ? decodeWorkerNameHeader(rawName) : null,
716
+ version: null
717
+ };
718
+ return requestId ? { worker, request_id: requestId } : { worker };
719
+ }
720
+ function sanitise(block) {
721
+ if ("worker" in block && block.worker !== null) {
722
+ const worker = parseWorker(block.worker);
723
+ if (worker) block.worker = worker;
724
+ else delete block.worker;
725
+ }
726
+ if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
727
+ delete block.request_id;
728
+ }
729
+ }
730
+ function withPlacement(result, headers, ...blocks) {
731
+ if (!isPlainObject(result)) return result;
732
+ const own = isPlainObject(result.pendra) ? result.pendra : void 0;
733
+ if (own) sanitise(own);
734
+ let placement;
735
+ for (const block of blocks) {
736
+ placement = placementFromBlock(block);
737
+ if (placement) break;
738
+ }
739
+ placement ?? (placement = placementFromHeaders(headers));
740
+ if (!placement) return result;
741
+ const merged = { ...own ?? {}, worker: placement.worker };
742
+ if (placement.request_id) merged.request_id = placement.request_id;
743
+ else delete merged.request_id;
744
+ result.pendra = merged;
745
+ return result;
746
+ }
747
+ function chunkPlacement(chunk) {
748
+ const block = chunk.pendra;
749
+ if (!isPlainObject(block)) return {};
750
+ sanitise(block);
751
+ const worker = block.worker;
752
+ const requestId = block.request_id;
753
+ return { worker: worker ?? void 0, requestId: requestId || void 0 };
754
+ }
755
+ var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
756
+
757
+ // src/_privateInferenceEngine.ts
758
+ var PrivateInferenceError = class extends Error {
759
+ constructor(message) {
760
+ super(message);
761
+ this.name = "PrivateInferenceError";
762
+ }
763
+ };
764
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
765
+ function parsePinnedFingerprints(pin) {
766
+ if (typeof pin !== "string") {
767
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
768
+ }
769
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
770
+ if (fps.length === 0) {
771
+ throw new PrivateInferenceError(
772
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
773
+ );
774
+ }
775
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
776
+ if (bad.length > 0) {
777
+ throw new PrivateInferenceError(
778
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
779
+ );
780
+ }
781
+ return new Set(fps);
782
+ }
783
+ function defaultTofuPath() {
784
+ const env = typeof process !== "undefined" ? process.env : void 0;
785
+ if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
786
+ const home = env?.HOME || env?.USERPROFILE || ".";
787
+ return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
788
+ }
789
+ function b64d2(s) {
790
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
791
+ const binary = atob(s);
792
+ const out = new Uint8Array(binary.length);
793
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
794
+ return out;
795
+ }
796
+ var PrivateInferenceEngine = class {
797
+ constructor(opts) {
798
+ this.orgPubs = null;
799
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
800
+ this.apiKey = opts.apiKey;
801
+ const pin = opts.pinnedFingerprint;
802
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
803
+ this.affinitySalt = opts.affinitySalt ?? null;
804
+ this.tofuPath = opts.tofuPath || defaultTofuPath();
805
+ }
806
+ // --- key resolution ---
807
+ cachedOrgPublicKeys() {
808
+ return this.orgPubs;
809
+ }
810
+ cachedOrgPublicKey() {
811
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
812
+ }
813
+ tofuIdentity() {
814
+ const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
815
+ return `${this.baseUrl}|${digest}`;
816
+ }
817
+ /**
818
+ * Drop the cached key set so the next call re-fetches it.
819
+ *
820
+ * The cache is otherwise held for the whole process lifetime, which is
821
+ * correct while a fleet keeps one key but fatal when it re-keys: a
822
+ * long-running server would go on sealing to a fingerprint no worker holds
823
+ * and fail EVERY request until someone restarted it. The API signals a re-key
824
+ * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
825
+ * lets the client recover on its own.
826
+ *
827
+ * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
828
+ * allowlist, so a fetch could only return fingerprints the pin already
829
+ * rejects. They surface the error instead, which is what pinning means.
830
+ */
831
+ invalidateOrgKey() {
832
+ this.orgPubs = null;
833
+ }
834
+ /** Whether this client seals only to an explicit fingerprint allowlist. */
835
+ get isPinned() {
836
+ return this.pinnedFingerprints !== null;
837
+ }
838
+ /**
839
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
840
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
841
+ * them (newest-seen first). The client seals to **all** of the returned keys
842
+ * so any worker holding any of them can serve the request. Throws
843
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
844
+ * intersection with the pin set.
845
+ */
846
+ async resolveOrgKey(fetchedKeys) {
847
+ if (this.orgPubs !== null) return this.orgPubs;
848
+ if (!fetchedKeys || fetchedKeys.length === 0) {
849
+ throw new PrivateInferenceError(
850
+ "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
851
+ );
852
+ }
853
+ const pubs = [];
854
+ const fps = [];
855
+ for (const entry of fetchedKeys) {
856
+ let pub;
857
+ try {
858
+ pub = b64d2(entry.public_key);
859
+ } catch (e) {
860
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
861
+ }
862
+ if (pub.length !== 32) {
863
+ throw new PrivateInferenceError(
864
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
865
+ );
866
+ }
867
+ pubs.push(pub);
868
+ fps.push(fingerprint(pub));
869
+ }
870
+ let accepted;
871
+ if (this.pinnedFingerprints !== null) {
872
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
873
+ if (accepted.length === 0) {
874
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
875
+ throw new PrivateInferenceError(
876
+ `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.`
877
+ );
878
+ }
879
+ } else {
880
+ await this.tofuTrust(fps);
881
+ accepted = pubs;
882
+ }
883
+ this.orgPubs = accepted;
884
+ return accepted;
885
+ }
886
+ async tofuTrust(fps) {
887
+ const store = await this.loadTofu();
888
+ const identity = this.tofuIdentity();
889
+ const known = store[identity];
890
+ const trusted = /* @__PURE__ */ new Set();
891
+ if (typeof known === "string") {
892
+ trusted.add(known);
893
+ } else if (Array.isArray(known)) {
894
+ for (const f of known) if (typeof f === "string") trusted.add(f);
895
+ }
896
+ const before = trusted.size;
897
+ for (const f of fps) trusted.add(f);
898
+ if (trusted.size !== before || !Array.isArray(known)) {
899
+ store[identity] = Array.from(trusted).sort();
900
+ await this.saveTofu(store);
901
+ }
902
+ }
903
+ async loadTofu() {
904
+ try {
905
+ const fs = await import("fs");
906
+ const raw = fs.readFileSync(this.tofuPath, "utf-8");
907
+ const data = JSON.parse(raw);
908
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
909
+ } catch {
910
+ return {};
911
+ }
912
+ }
913
+ async saveTofu(store) {
914
+ const fs = await import("fs");
915
+ const path = await import("path");
916
+ const directory = path.dirname(this.tofuPath) || ".";
917
+ fs.mkdirSync(directory, { recursive: true });
918
+ const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
919
+ try {
920
+ fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
921
+ try {
922
+ fs.chmodSync(tmp, 384);
923
+ } catch {
924
+ }
925
+ fs.renameSync(tmp, this.tofuPath);
926
+ } catch (e) {
927
+ try {
928
+ fs.unlinkSync(tmp);
929
+ } catch {
930
+ }
931
+ throw e;
932
+ }
933
+ }
934
+ // --- sealing ---
935
+ /**
936
+ * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
937
+ * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
938
+ * `binary` (audio only) is sealed under the same data key as the body.
939
+ */
940
+ seal(args) {
941
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
942
+ throw new PrivateInferenceError(
943
+ "private inference: org key not resolved yet (call resolveOrgKey first)"
944
+ );
945
+ }
946
+ let affinity = null;
947
+ if (args.messages != null) {
948
+ affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
949
+ }
950
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
951
+ model: args.model,
952
+ stream: args.stream,
953
+ taskType: args.taskType,
954
+ affinityKey: affinity,
955
+ binary: args.binary ?? null
956
+ });
957
+ const topLevel = {
958
+ model: args.model,
959
+ stream: args.stream,
960
+ pendra_encrypted: envelope
961
+ };
962
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
963
+ }
964
+ get keyFetchUrl() {
965
+ return `${this.baseUrl}/v1/private-inference/key`;
966
+ }
967
+ };
968
+
969
+ // src/resources/audio/speech.ts
970
+ var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
971
+ function decodeAudio(value) {
972
+ if (typeof value !== "string") return void 0;
973
+ const s = value.replace(/\s+/g, "");
974
+ if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
975
+ if (s.includes("=") && s.length % 4 !== 0) return void 0;
976
+ let bytes2;
977
+ try {
978
+ bytes2 = _internal.b64d(s);
979
+ } catch {
980
+ return void 0;
981
+ }
982
+ return bytes2.length > 0 ? bytes2 : void 0;
983
+ }
984
+ function isRecord2(v) {
985
+ return typeof v === "object" && v !== null && !Array.isArray(v);
986
+ }
987
+ var Speech = class {
988
+ constructor(client) {
989
+ this.client = client;
990
+ }
991
+ /**
992
+ * Turn text into spoken audio (OpenAI-compatible).
993
+ *
994
+ * @example
995
+ * ```ts
996
+ * import { writeFileSync } from "node:fs";
997
+ *
998
+ * const speech = await client.audio.speech.create({
999
+ * model: "qwen3-tts",
1000
+ * input: "Hello from Pendra.",
1001
+ * });
1002
+ * writeFileSync("speech.wav", speech.audio);
1003
+ * ```
1004
+ */
1005
+ async create(params) {
1006
+ if (!params.model || typeof params.model !== "string") {
1007
+ throw new Error("model must be a non-empty string");
1008
+ }
1009
+ if (typeof params.input !== "string" || !params.input.trim()) {
1010
+ throw new Error("input must be a non-empty string");
1011
+ }
1012
+ if (this.client.privateInferenceEnabled) {
1013
+ throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
1014
+ }
1015
+ const body = { model: params.model, input: params.input };
1016
+ if (params.voice != null) body.voice = params.voice;
1017
+ if (params.response_format != null) body.response_format = params.response_format;
1018
+ const headers = { Accept: "application/json" };
1019
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1020
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
1021
+ const { response } = await this.client._fetch("/api/v1/audio/speech", {
1022
+ method: "POST",
1023
+ body,
1024
+ headers,
1025
+ timeout
1026
+ });
1027
+ const text = await response.text();
1028
+ let parsed;
1029
+ try {
1030
+ parsed = JSON.parse(text);
1031
+ } catch {
1032
+ throw new APIResponseValidationError("Response was not valid JSON", {
1033
+ status: response.status,
1034
+ body: text
1035
+ });
1036
+ }
1037
+ throwIfInBandError(parsed, "The server reported an error");
1038
+ if (!isRecord2(parsed)) {
1039
+ throw new APIResponseValidationError("Response was not a speech result", {
1040
+ status: response.status,
1041
+ body: text
1042
+ });
1043
+ }
1044
+ const audio = decodeAudio(parsed.audio);
1045
+ if (!audio) {
1046
+ throw new APIResponseValidationError("Response did not contain decodable audio", {
1047
+ status: response.status,
1048
+ body: text
1049
+ });
1050
+ }
1051
+ const result = {
1052
+ audio,
1053
+ format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
1054
+ duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
1055
+ arrayBuffer: async () => audio.slice().buffer
1056
+ };
1057
+ if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
1058
+ return withPlacement(result, response.headers, result.pendra);
1059
+ }
1060
+ };
1061
+
663
1062
  // src/resources/audio/transcriptions.ts
664
1063
  var ENCODER = new TextEncoder();
665
1064
  var DECODER = new TextDecoder();
@@ -759,9 +1158,10 @@ var Transcriptions = class {
759
1158
  const format = params.response_format;
760
1159
  if (format === "text" || format === "srt" || format === "vtt") {
761
1160
  const text = await response.text();
762
- return { text };
1161
+ return withPlacement({ text }, response.headers);
763
1162
  }
764
- return await response.json();
1163
+ const result = await response.json();
1164
+ return withPlacement(result, response.headers, result.pendra);
765
1165
  }
766
1166
  /**
767
1167
  * Private-inference transcription. There is no multipart upload: the audio
@@ -796,9 +1196,11 @@ var Transcriptions = class {
796
1196
  timeout
797
1197
  }
798
1198
  );
799
- const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
1199
+ const { inner, placement } = await readSealedReply(response);
1200
+ const raw = DECODER.decode(decryptor.openResult(inner));
800
1201
  const parsed = parseDecryptedJson(raw, response.status);
801
- if (typeof parsed === "string") return { text: parsed };
1202
+ const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
1203
+ if (typeof parsed === "string") return place({ text: parsed });
802
1204
  if (typeof parsed === "object" && parsed !== null) {
803
1205
  if (typeof parsed.text !== "string") {
804
1206
  throw new APIResponseValidationError("Decrypted response was not a transcription", {
@@ -806,9 +1208,9 @@ var Transcriptions = class {
806
1208
  body: raw
807
1209
  });
808
1210
  }
809
- return parsed;
1211
+ return place(parsed);
810
1212
  }
811
- return { text: raw };
1213
+ return place({ text: raw });
812
1214
  }
813
1215
  };
814
1216
 
@@ -816,6 +1218,7 @@ var Transcriptions = class {
816
1218
  var Audio = class {
817
1219
  constructor(client) {
818
1220
  this.transcriptions = new Transcriptions(client);
1221
+ this.speech = new Speech(client);
819
1222
  }
820
1223
  };
821
1224
 
@@ -892,6 +1295,7 @@ var Stream = class {
892
1295
  this.decoder = new TextDecoder();
893
1296
  this.sse = new SseDecoder();
894
1297
  this.done = false;
1298
+ this.placement = new PlacementTracker();
895
1299
  if (!response.body) {
896
1300
  throw new Error("Response body is null \u2014 streaming not supported");
897
1301
  }
@@ -912,7 +1316,7 @@ var Stream = class {
912
1316
  this.done = true;
913
1317
  return;
914
1318
  }
915
- yield parseStreamFrame(data);
1319
+ yield this.placement.observe(parseStreamFrame(data));
916
1320
  }
917
1321
  if (readerDone) {
918
1322
  this.done = true;
@@ -923,11 +1327,39 @@ var Stream = class {
923
1327
  releaseReader(this.reader, this.controller, this.done);
924
1328
  }
925
1329
  }
1330
+ /**
1331
+ * The worker that served this stream, or `null` until the chunk reporting it
1332
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1333
+ * old to report it). Same as that chunk's `pendra.worker`.
1334
+ */
1335
+ get worker() {
1336
+ return this.placement.worker;
1337
+ }
1338
+ /**
1339
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1340
+ * `null` until then.
1341
+ */
1342
+ get requestId() {
1343
+ return this.placement.requestId;
1344
+ }
926
1345
  abort() {
927
1346
  this.done = true;
928
1347
  this.controller.abort();
929
1348
  }
930
1349
  };
1350
+ var PlacementTracker = class {
1351
+ constructor() {
1352
+ this.worker = null;
1353
+ this.requestId = null;
1354
+ }
1355
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1356
+ observe(chunk) {
1357
+ const { worker, requestId } = chunkPlacement(chunk);
1358
+ if (worker) this.worker = worker;
1359
+ if (requestId) this.requestId = requestId;
1360
+ return chunk;
1361
+ }
1362
+ };
931
1363
  async function readWithIdleTimeout(reader, idleTimeoutMs) {
932
1364
  if (!idleTimeoutMs) return reader.read();
933
1365
  let timer;
@@ -963,6 +1395,7 @@ var EncryptedStream = class {
963
1395
  this.openedAny = false;
964
1396
  this.declared = false;
965
1397
  this.terminated = false;
1398
+ this.placement = new PlacementTracker();
966
1399
  if (!response.body) {
967
1400
  throw new Error("Response body is null \u2014 streaming not supported");
968
1401
  }
@@ -1004,9 +1437,9 @@ var EncryptedStream = class {
1004
1437
  }
1005
1438
  const inner = frame?.pendra_encrypted;
1006
1439
  if (!inner) {
1007
- if (isApiTimingChunk(frame)) {
1440
+ if (isApiTrailerChunk(frame)) {
1008
1441
  this.checkEnded();
1009
- yield parseStreamFrame(data);
1442
+ yield this.placement.observe(parseStreamFrame(data));
1010
1443
  continue;
1011
1444
  }
1012
1445
  parseStreamFrame(data);
@@ -1034,7 +1467,7 @@ var EncryptedStream = class {
1034
1467
  return;
1035
1468
  }
1036
1469
  if (!chunkJson) continue;
1037
- yield parseStreamFrame(chunkJson, "Decrypted stream frame");
1470
+ yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
1038
1471
  }
1039
1472
  if (readerDone) {
1040
1473
  this.checkEnded();
@@ -1056,6 +1489,14 @@ var EncryptedStream = class {
1056
1489
  throw truncatedStreamError();
1057
1490
  }
1058
1491
  }
1492
+ /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
1493
+ get worker() {
1494
+ return this.placement.worker;
1495
+ }
1496
+ /** Same as `Stream.requestId`. */
1497
+ get requestId() {
1498
+ return this.placement.requestId;
1499
+ }
1059
1500
  abort() {
1060
1501
  this.aborted = true;
1061
1502
  this.done = true;
@@ -1076,7 +1517,9 @@ var Completions = class {
1076
1517
  for (const [key, value] of Object.entries(rest)) {
1077
1518
  if (value != null) body[key] = value;
1078
1519
  }
1079
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1520
+ const headers = {};
1521
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1522
+ if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
1080
1523
  if (this.client.privateInferenceEnabled) {
1081
1524
  return this.createEncrypted(params, body, headers);
1082
1525
  }
@@ -1091,7 +1534,8 @@ var Completions = class {
1091
1534
  "/api/v1/chat/completions",
1092
1535
  { method: "POST", body, headers }
1093
1536
  );
1094
- return parseCompletion(response);
1537
+ const completion = await parseCompletion(response);
1538
+ return withPlacement(completion, response.headers, completion.pendra);
1095
1539
  }
1096
1540
  async createEncrypted(params, body, headers) {
1097
1541
  const engine = await this.client._privateEngine();
@@ -1131,7 +1575,8 @@ var Completions = class {
1131
1575
  throw unsealedReplyError();
1132
1576
  }
1133
1577
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1134
- return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1578
+ const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1579
+ return withPlacement(completion, response.headers, completion.pendra, wrapper.pendra);
1135
1580
  }
1136
1581
  };
1137
1582
 
@@ -1200,7 +1645,8 @@ var Embeddings = class {
1200
1645
  "/api/v1/embeddings",
1201
1646
  { method: "POST", body, headers }
1202
1647
  );
1203
- return await response.json();
1648
+ const result = await response.json();
1649
+ return withPlacement(result, response.headers, result.pendra);
1204
1650
  }
1205
1651
  async createEncrypted(model, body, headers) {
1206
1652
  const engine = await this.client._privateEngine();
@@ -1219,7 +1665,8 @@ var Embeddings = class {
1219
1665
  throw unsealedReplyError();
1220
1666
  }
1221
1667
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1222
- return JSON.parse(DECODER4.decode(plain));
1668
+ const result = JSON.parse(DECODER4.decode(plain));
1669
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1223
1670
  }
1224
1671
  };
1225
1672
 
@@ -1262,7 +1709,8 @@ var Generations = class {
1262
1709
  "/api/v1/images/generations",
1263
1710
  { method: "POST", body, headers }
1264
1711
  );
1265
- return await response.json();
1712
+ const result = await response.json();
1713
+ return withPlacement(result, response.headers, result.pendra);
1266
1714
  }
1267
1715
  async createEncrypted(model, body, headers) {
1268
1716
  const engine = await this.client._privateEngine();
@@ -1276,7 +1724,8 @@ var Generations = class {
1276
1724
  "/api/v1/images/generations",
1277
1725
  { method: "POST", body: topLevel, headers }
1278
1726
  );
1279
- const plain = decryptor.openResult(await readSealedReply(response));
1727
+ const { inner, placement } = await readSealedReply(response);
1728
+ const plain = decryptor.openResult(inner);
1280
1729
  const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1281
1730
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1282
1731
  throw new APIResponseValidationError("Decrypted response was not an image generation", {
@@ -1284,7 +1733,8 @@ var Generations = class {
1284
1733
  body: DECODER5.decode(plain)
1285
1734
  });
1286
1735
  }
1287
- return parsed;
1736
+ const result = parsed;
1737
+ return withPlacement(result, response.headers, result.pendra, placement);
1288
1738
  }
1289
1739
  };
1290
1740
 
@@ -1362,7 +1812,8 @@ var Rerank = class {
1362
1812
  "/api/v1/rerank",
1363
1813
  { method: "POST", body, headers }
1364
1814
  );
1365
- return await response.json();
1815
+ const result = await response.json();
1816
+ return withPlacement(result, response.headers, result.pendra);
1366
1817
  }
1367
1818
  async createEncrypted(model, body, headers) {
1368
1819
  const engine = await this.client._privateEngine();
@@ -1381,226 +1832,15 @@ var Rerank = class {
1381
1832
  throw unsealedReplyError();
1382
1833
  }
1383
1834
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1384
- return JSON.parse(DECODER6.decode(plain));
1835
+ const result = JSON.parse(DECODER6.decode(plain));
1836
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1385
1837
  }
1386
1838
  };
1387
1839
 
1388
1840
  // src/version.ts
1389
- var VERSION = "0.16.0";
1841
+ var VERSION = "0.17.0";
1390
1842
  var USER_AGENT = `pendra-node/${VERSION}`;
1391
1843
 
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
1844
  // src/client.ts
1605
1845
  function envTruthy(v) {
1606
1846
  if (!v) return false;