pendra 0.15.2 → 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.mjs CHANGED
@@ -13,21 +13,23 @@ var APIConnectionError = class extends APIError {
13
13
  }
14
14
  };
15
15
  var APIStatusError = class extends APIError {
16
- constructor(message, status) {
16
+ constructor(message, status, options = {}) {
17
17
  super(message, status);
18
18
  this.name = "APIStatusError";
19
19
  this.status = status;
20
+ this.body = options.body;
21
+ this.detail = options.detail;
20
22
  }
21
23
  };
22
24
  var AuthenticationError = class extends APIStatusError {
23
- constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY") {
24
- super(message, 401);
25
+ constructor(message = "Invalid API key \u2014 check your PENDRA_API_KEY", options = {}) {
26
+ super(message, 401, options);
25
27
  this.name = "AuthenticationError";
26
28
  }
27
29
  };
28
30
  var RateLimitError = class extends APIStatusError {
29
- constructor(message = "Rate limit exceeded") {
30
- super(message, 429);
31
+ constructor(message = "Rate limit exceeded", options = {}) {
32
+ super(message, 429, options);
31
33
  this.name = "RateLimitError";
32
34
  }
33
35
  };
@@ -58,6 +60,80 @@ var APIStreamError = class extends APIError {
58
60
  this.workerName = options.workerName;
59
61
  }
60
62
  };
63
+ var LOC_SOURCES = /* @__PURE__ */ new Set(["body", "query", "path", "header", "cookie"]);
64
+ function isRecord(value) {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
67
+ function nonEmptyString(value) {
68
+ return typeof value === "string" && value ? value : void 0;
69
+ }
70
+ function compactJson(value) {
71
+ try {
72
+ return JSON.stringify(value) ?? String(value);
73
+ } catch {
74
+ return String(value);
75
+ }
76
+ }
77
+ function messageFromItem(item) {
78
+ if (isRecord(item)) {
79
+ const msg = nonEmptyString(item.msg) ?? nonEmptyString(item.message);
80
+ if (msg) {
81
+ let field = typeof item.field === "string" ? item.field : void 0;
82
+ if (field === void 0) {
83
+ const loc = Array.isArray(item.loc) ? [...item.loc] : [];
84
+ if (loc.length && LOC_SOURCES.has(String(loc[0]))) loc.shift();
85
+ field = loc.map(String).join(".");
86
+ }
87
+ return field ? `${field}: ${msg}` : msg;
88
+ }
89
+ }
90
+ return messageFromDetail(item);
91
+ }
92
+ function messageFromDetail(detail) {
93
+ if (detail === void 0 || detail === null) return void 0;
94
+ if (typeof detail === "string") return detail || void 0;
95
+ if (Array.isArray(detail)) {
96
+ const parts = detail.map(messageFromItem).filter((p) => !!p);
97
+ return parts.length ? parts.join("; ") : void 0;
98
+ }
99
+ if (isRecord(detail)) {
100
+ const err = detail.error;
101
+ const nested = isRecord(err) ? nonEmptyString(err.message) : void 0;
102
+ const msg = nested ?? nonEmptyString(detail.message) ?? nonEmptyString(detail.msg);
103
+ if (msg) return msg;
104
+ return Object.keys(detail).length ? compactJson(detail) : void 0;
105
+ }
106
+ return compactJson(detail);
107
+ }
108
+ async function readErrorBody(response) {
109
+ let raw;
110
+ try {
111
+ raw = await response.text();
112
+ } catch {
113
+ return void 0;
114
+ }
115
+ if (!raw) return void 0;
116
+ try {
117
+ return JSON.parse(raw);
118
+ } catch {
119
+ return raw;
120
+ }
121
+ }
122
+ function statusErrorFromBody(status, body, fallback) {
123
+ const detail = isRecord(body) ? body.detail : void 0;
124
+ const err = isRecord(body) ? body.error : void 0;
125
+ let message = (isRecord(err) ? nonEmptyString(err.message) : void 0) ?? messageFromDetail(detail) ?? (isRecord(body) ? nonEmptyString(body.message) : void 0);
126
+ if (message === void 0) {
127
+ if (typeof body === "string") message = body || fallback;
128
+ else if (Array.isArray(body) ? body.length : isRecord(body) && Object.keys(body).length) {
129
+ message = compactJson(body);
130
+ } else message = fallback;
131
+ }
132
+ const options = { body, detail };
133
+ if (status === 401) return new AuthenticationError(message, options);
134
+ if (status === 429) return new RateLimitError(message, options);
135
+ return new APIStatusError(message, status, options);
136
+ }
61
137
 
62
138
  // src/_privateInference.ts
63
139
  import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
@@ -285,12 +361,23 @@ function sealRequest(orgPubs, body, opts) {
285
361
  }
286
362
  return { envelope, responseKeys };
287
363
  }
288
- var API_TIMING_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
289
- function isApiTimingChunk(frame) {
364
+ var API_TRAILER_CHUNK_KEYS = /* @__PURE__ */ new Set(["id", "object", "created", "model", "choices", "pendra"]);
365
+ var API_TRAILER_PENDRA_KEYS = /* @__PURE__ */ new Set(["timing", "worker", "request_id"]);
366
+ function isApiTrailerChunk(frame) {
290
367
  if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
291
368
  const obj = frame;
292
369
  const pendra = obj.pendra;
293
- 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;
370
+ 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)) {
371
+ return false;
372
+ }
373
+ const block = pendra;
374
+ const keys = Object.keys(block);
375
+ if (keys.length === 0 || !keys.every((k) => API_TRAILER_PENDRA_KEYS.has(k))) return false;
376
+ if ("worker" in block && (block.worker === null || typeof block.worker !== "object" || Array.isArray(block.worker))) {
377
+ return false;
378
+ }
379
+ if ("request_id" in block && typeof block.request_id !== "string") return false;
380
+ return true;
294
381
  }
295
382
  function unsealedReplyError() {
296
383
  return new Error(
@@ -428,6 +515,7 @@ function affinityKey(rawApiKey, model, messages, saltOverride) {
428
515
  const mac = hmac(sha256, salt, utf8(parts.join("\0")));
429
516
  return toHex(mac);
430
517
  }
518
+ var _internal = { b64, b64d, utf8, TEXT_DECODER };
431
519
 
432
520
  // src/_parsing.ts
433
521
  function asString(v) {
@@ -523,9 +611,10 @@ async function readSealedReply(response) {
523
611
  });
524
612
  }
525
613
  throwIfInBandError(parsed, "The server reported an error");
526
- const inner = typeof parsed === "object" && parsed !== null ? parsed.pendra_encrypted : void 0;
614
+ const wrapper = typeof parsed === "object" && parsed !== null ? parsed : void 0;
615
+ const inner = wrapper?.pendra_encrypted;
527
616
  if (!inner) throw unsealedReplyError();
528
- return inner;
617
+ return { inner, placement: wrapper.pendra };
529
618
  }
530
619
  function parseDecryptedJson(json, status) {
531
620
  try {
@@ -536,7 +625,393 @@ function parseDecryptedJson(json, status) {
536
625
  body: json
537
626
  });
538
627
  }
539
- }
628
+ }
629
+
630
+ // src/_placement.ts
631
+ var UTF8_EXT_PREFIX = "utf-8''";
632
+ function isPlainObject(v) {
633
+ return typeof v === "object" && v !== null && !Array.isArray(v);
634
+ }
635
+ function parseWorker(v) {
636
+ if (!isPlainObject(v) || typeof v.id !== "string" || !v.id) return void 0;
637
+ return {
638
+ id: v.id,
639
+ name: typeof v.name === "string" && v.name ? v.name : null,
640
+ version: typeof v.version === "string" && v.version ? v.version : null
641
+ };
642
+ }
643
+ function placementFromBlock(block) {
644
+ if (!isPlainObject(block)) return void 0;
645
+ const worker = parseWorker(block.worker);
646
+ if (!worker) return void 0;
647
+ const requestId = block.request_id;
648
+ return typeof requestId === "string" && requestId ? { worker, request_id: requestId } : { worker };
649
+ }
650
+ function decodeWorkerNameHeader(raw) {
651
+ if (raw.slice(0, UTF8_EXT_PREFIX.length).toLowerCase() !== UTF8_EXT_PREFIX) return raw;
652
+ try {
653
+ return decodeURIComponent(raw.slice(UTF8_EXT_PREFIX.length));
654
+ } catch {
655
+ return raw;
656
+ }
657
+ }
658
+ function header(headers, name) {
659
+ if (!headers || typeof headers.get !== "function") return void 0;
660
+ return headers.get(name) || void 0;
661
+ }
662
+ function placementFromHeaders(headers) {
663
+ const id = header(headers, "X-Worker-Id");
664
+ if (!id) return void 0;
665
+ const rawName = header(headers, "X-Worker-Name");
666
+ const requestId = header(headers, "X-Request-Id");
667
+ const worker = {
668
+ id,
669
+ name: rawName ? decodeWorkerNameHeader(rawName) : null,
670
+ version: null
671
+ };
672
+ return requestId ? { worker, request_id: requestId } : { worker };
673
+ }
674
+ function sanitise(block) {
675
+ if ("worker" in block && block.worker !== null) {
676
+ const worker = parseWorker(block.worker);
677
+ if (worker) block.worker = worker;
678
+ else delete block.worker;
679
+ }
680
+ if ("request_id" in block && block.request_id !== null && typeof block.request_id !== "string") {
681
+ delete block.request_id;
682
+ }
683
+ }
684
+ function withPlacement(result, headers, ...blocks) {
685
+ if (!isPlainObject(result)) return result;
686
+ const own = isPlainObject(result.pendra) ? result.pendra : void 0;
687
+ if (own) sanitise(own);
688
+ let placement;
689
+ for (const block of blocks) {
690
+ placement = placementFromBlock(block);
691
+ if (placement) break;
692
+ }
693
+ placement ?? (placement = placementFromHeaders(headers));
694
+ if (!placement) return result;
695
+ const merged = { ...own ?? {}, worker: placement.worker };
696
+ if (placement.request_id) merged.request_id = placement.request_id;
697
+ else delete merged.request_id;
698
+ result.pendra = merged;
699
+ return result;
700
+ }
701
+ function chunkPlacement(chunk) {
702
+ const block = chunk.pendra;
703
+ if (!isPlainObject(block)) return {};
704
+ sanitise(block);
705
+ const worker = block.worker;
706
+ const requestId = block.request_id;
707
+ return { worker: worker ?? void 0, requestId: requestId || void 0 };
708
+ }
709
+ var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
710
+
711
+ // src/_privateInferenceEngine.ts
712
+ var PrivateInferenceError = class extends Error {
713
+ constructor(message) {
714
+ super(message);
715
+ this.name = "PrivateInferenceError";
716
+ }
717
+ };
718
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
719
+ function parsePinnedFingerprints(pin) {
720
+ if (typeof pin !== "string") {
721
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
722
+ }
723
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
724
+ if (fps.length === 0) {
725
+ throw new PrivateInferenceError(
726
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
727
+ );
728
+ }
729
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
730
+ if (bad.length > 0) {
731
+ throw new PrivateInferenceError(
732
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
733
+ );
734
+ }
735
+ return new Set(fps);
736
+ }
737
+ function defaultTofuPath() {
738
+ const env = typeof process !== "undefined" ? process.env : void 0;
739
+ if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
740
+ const home = env?.HOME || env?.USERPROFILE || ".";
741
+ return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
742
+ }
743
+ function b64d2(s) {
744
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
745
+ const binary = atob(s);
746
+ const out = new Uint8Array(binary.length);
747
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
748
+ return out;
749
+ }
750
+ var PrivateInferenceEngine = class {
751
+ constructor(opts) {
752
+ this.orgPubs = null;
753
+ this.baseUrl = opts.baseUrl.replace(/\/$/, "");
754
+ this.apiKey = opts.apiKey;
755
+ const pin = opts.pinnedFingerprint;
756
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
757
+ this.affinitySalt = opts.affinitySalt ?? null;
758
+ this.tofuPath = opts.tofuPath || defaultTofuPath();
759
+ }
760
+ // --- key resolution ---
761
+ cachedOrgPublicKeys() {
762
+ return this.orgPubs;
763
+ }
764
+ cachedOrgPublicKey() {
765
+ return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
766
+ }
767
+ tofuIdentity() {
768
+ const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
769
+ return `${this.baseUrl}|${digest}`;
770
+ }
771
+ /**
772
+ * Drop the cached key set so the next call re-fetches it.
773
+ *
774
+ * The cache is otherwise held for the whole process lifetime, which is
775
+ * correct while a fleet keeps one key but fatal when it re-keys: a
776
+ * long-running server would go on sealing to a fingerprint no worker holds
777
+ * and fail EVERY request until someone restarted it. The API signals a re-key
778
+ * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
779
+ * lets the client recover on its own.
780
+ *
781
+ * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
782
+ * allowlist, so a fetch could only return fingerprints the pin already
783
+ * rejects. They surface the error instead, which is what pinning means.
784
+ */
785
+ invalidateOrgKey() {
786
+ this.orgPubs = null;
787
+ }
788
+ /** Whether this client seals only to an explicit fingerprint allowlist. */
789
+ get isPinned() {
790
+ return this.pinnedFingerprints !== null;
791
+ }
792
+ /**
793
+ * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
794
+ * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
795
+ * them (newest-seen first). The client seals to **all** of the returned keys
796
+ * so any worker holding any of them can serve the request. Throws
797
+ * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
798
+ * intersection with the pin set.
799
+ */
800
+ async resolveOrgKey(fetchedKeys) {
801
+ if (this.orgPubs !== null) return this.orgPubs;
802
+ if (!fetchedKeys || fetchedKeys.length === 0) {
803
+ throw new PrivateInferenceError(
804
+ "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
805
+ );
806
+ }
807
+ const pubs = [];
808
+ const fps = [];
809
+ for (const entry of fetchedKeys) {
810
+ let pub;
811
+ try {
812
+ pub = b64d2(entry.public_key);
813
+ } catch (e) {
814
+ throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
815
+ }
816
+ if (pub.length !== 32) {
817
+ throw new PrivateInferenceError(
818
+ `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
819
+ );
820
+ }
821
+ pubs.push(pub);
822
+ fps.push(fingerprint(pub));
823
+ }
824
+ let accepted;
825
+ if (this.pinnedFingerprints !== null) {
826
+ accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
827
+ if (accepted.length === 0) {
828
+ const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
829
+ throw new PrivateInferenceError(
830
+ `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.`
831
+ );
832
+ }
833
+ } else {
834
+ await this.tofuTrust(fps);
835
+ accepted = pubs;
836
+ }
837
+ this.orgPubs = accepted;
838
+ return accepted;
839
+ }
840
+ async tofuTrust(fps) {
841
+ const store = await this.loadTofu();
842
+ const identity = this.tofuIdentity();
843
+ const known = store[identity];
844
+ const trusted = /* @__PURE__ */ new Set();
845
+ if (typeof known === "string") {
846
+ trusted.add(known);
847
+ } else if (Array.isArray(known)) {
848
+ for (const f of known) if (typeof f === "string") trusted.add(f);
849
+ }
850
+ const before = trusted.size;
851
+ for (const f of fps) trusted.add(f);
852
+ if (trusted.size !== before || !Array.isArray(known)) {
853
+ store[identity] = Array.from(trusted).sort();
854
+ await this.saveTofu(store);
855
+ }
856
+ }
857
+ async loadTofu() {
858
+ try {
859
+ const fs = await import("fs");
860
+ const raw = fs.readFileSync(this.tofuPath, "utf-8");
861
+ const data = JSON.parse(raw);
862
+ return data && typeof data === "object" && !Array.isArray(data) ? data : {};
863
+ } catch {
864
+ return {};
865
+ }
866
+ }
867
+ async saveTofu(store) {
868
+ const fs = await import("fs");
869
+ const path = await import("path");
870
+ const directory = path.dirname(this.tofuPath) || ".";
871
+ fs.mkdirSync(directory, { recursive: true });
872
+ const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
873
+ try {
874
+ fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
875
+ try {
876
+ fs.chmodSync(tmp, 384);
877
+ } catch {
878
+ }
879
+ fs.renameSync(tmp, this.tofuPath);
880
+ } catch (e) {
881
+ try {
882
+ fs.unlinkSync(tmp);
883
+ } catch {
884
+ }
885
+ throw e;
886
+ }
887
+ }
888
+ // --- sealing ---
889
+ /**
890
+ * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
891
+ * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
892
+ * `binary` (audio only) is sealed under the same data key as the body.
893
+ */
894
+ seal(args) {
895
+ if (this.orgPubs === null || this.orgPubs.length === 0) {
896
+ throw new PrivateInferenceError(
897
+ "private inference: org key not resolved yet (call resolveOrgKey first)"
898
+ );
899
+ }
900
+ let affinity = null;
901
+ if (args.messages != null) {
902
+ affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
903
+ }
904
+ const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
905
+ model: args.model,
906
+ stream: args.stream,
907
+ taskType: args.taskType,
908
+ affinityKey: affinity,
909
+ binary: args.binary ?? null
910
+ });
911
+ const topLevel = {
912
+ model: args.model,
913
+ stream: args.stream,
914
+ pendra_encrypted: envelope
915
+ };
916
+ return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
917
+ }
918
+ get keyFetchUrl() {
919
+ return `${this.baseUrl}/v1/private-inference/key`;
920
+ }
921
+ };
922
+
923
+ // src/resources/audio/speech.ts
924
+ var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
925
+ function decodeAudio(value) {
926
+ if (typeof value !== "string") return void 0;
927
+ const s = value.replace(/\s+/g, "");
928
+ if (!s || !BASE64_RE.test(s) || s.replace(/=+$/, "").length % 4 === 1) return void 0;
929
+ if (s.includes("=") && s.length % 4 !== 0) return void 0;
930
+ let bytes2;
931
+ try {
932
+ bytes2 = _internal.b64d(s);
933
+ } catch {
934
+ return void 0;
935
+ }
936
+ return bytes2.length > 0 ? bytes2 : void 0;
937
+ }
938
+ function isRecord2(v) {
939
+ return typeof v === "object" && v !== null && !Array.isArray(v);
940
+ }
941
+ var Speech = class {
942
+ constructor(client) {
943
+ this.client = client;
944
+ }
945
+ /**
946
+ * Turn text into spoken audio (OpenAI-compatible).
947
+ *
948
+ * @example
949
+ * ```ts
950
+ * import { writeFileSync } from "node:fs";
951
+ *
952
+ * const speech = await client.audio.speech.create({
953
+ * model: "qwen3-tts",
954
+ * input: "Hello from Pendra.",
955
+ * });
956
+ * writeFileSync("speech.wav", speech.audio);
957
+ * ```
958
+ */
959
+ async create(params) {
960
+ if (!params.model || typeof params.model !== "string") {
961
+ throw new Error("model must be a non-empty string");
962
+ }
963
+ if (typeof params.input !== "string" || !params.input.trim()) {
964
+ throw new Error("input must be a non-empty string");
965
+ }
966
+ if (this.client.privateInferenceEnabled) {
967
+ throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
968
+ }
969
+ const body = { model: params.model, input: params.input };
970
+ if (params.voice != null) body.voice = params.voice;
971
+ if (params.response_format != null) body.response_format = params.response_format;
972
+ const headers = { Accept: "application/json" };
973
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
974
+ const timeout = Math.max(this.client.timeout ?? 0, 3e5);
975
+ const { response } = await this.client._fetch("/api/v1/audio/speech", {
976
+ method: "POST",
977
+ body,
978
+ headers,
979
+ timeout
980
+ });
981
+ const text = await response.text();
982
+ let parsed;
983
+ try {
984
+ parsed = JSON.parse(text);
985
+ } catch {
986
+ throw new APIResponseValidationError("Response was not valid JSON", {
987
+ status: response.status,
988
+ body: text
989
+ });
990
+ }
991
+ throwIfInBandError(parsed, "The server reported an error");
992
+ if (!isRecord2(parsed)) {
993
+ throw new APIResponseValidationError("Response was not a speech result", {
994
+ status: response.status,
995
+ body: text
996
+ });
997
+ }
998
+ const audio = decodeAudio(parsed.audio);
999
+ if (!audio) {
1000
+ throw new APIResponseValidationError("Response did not contain decodable audio", {
1001
+ status: response.status,
1002
+ body: text
1003
+ });
1004
+ }
1005
+ const result = {
1006
+ audio,
1007
+ format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
1008
+ duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
1009
+ arrayBuffer: async () => audio.slice().buffer
1010
+ };
1011
+ if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
1012
+ return withPlacement(result, response.headers, result.pendra);
1013
+ }
1014
+ };
540
1015
 
541
1016
  // src/resources/audio/transcriptions.ts
542
1017
  var ENCODER = new TextEncoder();
@@ -574,21 +1049,6 @@ function asBlob(file) {
574
1049
  }
575
1050
  return { blob: new Blob([content]), filename };
576
1051
  }
577
- async function extractErrorDetail(response) {
578
- let raw = "";
579
- try {
580
- raw = await response.text();
581
- } catch {
582
- return response.statusText;
583
- }
584
- if (!raw) return response.statusText;
585
- try {
586
- const body = JSON.parse(raw);
587
- return body.detail ?? body.error?.message ?? raw;
588
- } catch {
589
- return raw;
590
- }
591
- }
592
1052
  var Transcriptions = class {
593
1053
  constructor(client) {
594
1054
  this.client = client;
@@ -646,21 +1106,16 @@ var Transcriptions = class {
646
1106
  }
647
1107
  clearTimeout(timeoutId);
648
1108
  if (response.status >= 400) {
649
- const detail = await extractErrorDetail(response);
650
- if (response.status === 401) {
651
- throw new AuthenticationError(detail);
652
- }
653
- if (response.status === 429) {
654
- throw new RateLimitError(detail);
655
- }
656
- throw new APIStatusError(detail, response.status);
1109
+ const body = await readErrorBody(response);
1110
+ throw statusErrorFromBody(response.status, body, response.statusText);
657
1111
  }
658
1112
  const format = params.response_format;
659
1113
  if (format === "text" || format === "srt" || format === "vtt") {
660
1114
  const text = await response.text();
661
- return { text };
1115
+ return withPlacement({ text }, response.headers);
662
1116
  }
663
- return await response.json();
1117
+ const result = await response.json();
1118
+ return withPlacement(result, response.headers, result.pendra);
664
1119
  }
665
1120
  /**
666
1121
  * Private-inference transcription. There is no multipart upload: the audio
@@ -695,9 +1150,11 @@ var Transcriptions = class {
695
1150
  timeout
696
1151
  }
697
1152
  );
698
- const raw = DECODER.decode(decryptor.openResult(await readSealedReply(response)));
1153
+ const { inner, placement } = await readSealedReply(response);
1154
+ const raw = DECODER.decode(decryptor.openResult(inner));
699
1155
  const parsed = parseDecryptedJson(raw, response.status);
700
- if (typeof parsed === "string") return { text: parsed };
1156
+ const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
1157
+ if (typeof parsed === "string") return place({ text: parsed });
701
1158
  if (typeof parsed === "object" && parsed !== null) {
702
1159
  if (typeof parsed.text !== "string") {
703
1160
  throw new APIResponseValidationError("Decrypted response was not a transcription", {
@@ -705,9 +1162,9 @@ var Transcriptions = class {
705
1162
  body: raw
706
1163
  });
707
1164
  }
708
- return parsed;
1165
+ return place(parsed);
709
1166
  }
710
- return { text: raw };
1167
+ return place({ text: raw });
711
1168
  }
712
1169
  };
713
1170
 
@@ -715,6 +1172,7 @@ var Transcriptions = class {
715
1172
  var Audio = class {
716
1173
  constructor(client) {
717
1174
  this.transcriptions = new Transcriptions(client);
1175
+ this.speech = new Speech(client);
718
1176
  }
719
1177
  };
720
1178
 
@@ -791,6 +1249,7 @@ var Stream = class {
791
1249
  this.decoder = new TextDecoder();
792
1250
  this.sse = new SseDecoder();
793
1251
  this.done = false;
1252
+ this.placement = new PlacementTracker();
794
1253
  if (!response.body) {
795
1254
  throw new Error("Response body is null \u2014 streaming not supported");
796
1255
  }
@@ -811,7 +1270,7 @@ var Stream = class {
811
1270
  this.done = true;
812
1271
  return;
813
1272
  }
814
- yield parseStreamFrame(data);
1273
+ yield this.placement.observe(parseStreamFrame(data));
815
1274
  }
816
1275
  if (readerDone) {
817
1276
  this.done = true;
@@ -822,11 +1281,39 @@ var Stream = class {
822
1281
  releaseReader(this.reader, this.controller, this.done);
823
1282
  }
824
1283
  }
1284
+ /**
1285
+ * The worker that served this stream, or `null` until the chunk reporting it
1286
+ * — the trailer, just before `[DONE]` — has been iterated (and on an API too
1287
+ * old to report it). Same as that chunk's `pendra.worker`.
1288
+ */
1289
+ get worker() {
1290
+ return this.placement.worker;
1291
+ }
1292
+ /**
1293
+ * Pendra's id for this request, reported alongside {@link Stream.worker};
1294
+ * `null` until then.
1295
+ */
1296
+ get requestId() {
1297
+ return this.placement.requestId;
1298
+ }
825
1299
  abort() {
826
1300
  this.done = true;
827
1301
  this.controller.abort();
828
1302
  }
829
1303
  };
1304
+ var PlacementTracker = class {
1305
+ constructor() {
1306
+ this.worker = null;
1307
+ this.requestId = null;
1308
+ }
1309
+ /** Record `chunk`'s placement, if it carries any, and hand it back. */
1310
+ observe(chunk) {
1311
+ const { worker, requestId } = chunkPlacement(chunk);
1312
+ if (worker) this.worker = worker;
1313
+ if (requestId) this.requestId = requestId;
1314
+ return chunk;
1315
+ }
1316
+ };
830
1317
  async function readWithIdleTimeout(reader, idleTimeoutMs) {
831
1318
  if (!idleTimeoutMs) return reader.read();
832
1319
  let timer;
@@ -862,6 +1349,7 @@ var EncryptedStream = class {
862
1349
  this.openedAny = false;
863
1350
  this.declared = false;
864
1351
  this.terminated = false;
1352
+ this.placement = new PlacementTracker();
865
1353
  if (!response.body) {
866
1354
  throw new Error("Response body is null \u2014 streaming not supported");
867
1355
  }
@@ -903,9 +1391,9 @@ var EncryptedStream = class {
903
1391
  }
904
1392
  const inner = frame?.pendra_encrypted;
905
1393
  if (!inner) {
906
- if (isApiTimingChunk(frame)) {
1394
+ if (isApiTrailerChunk(frame)) {
907
1395
  this.checkEnded();
908
- yield parseStreamFrame(data);
1396
+ yield this.placement.observe(parseStreamFrame(data));
909
1397
  continue;
910
1398
  }
911
1399
  parseStreamFrame(data);
@@ -933,7 +1421,7 @@ var EncryptedStream = class {
933
1421
  return;
934
1422
  }
935
1423
  if (!chunkJson) continue;
936
- yield parseStreamFrame(chunkJson, "Decrypted stream frame");
1424
+ yield this.placement.observe(parseStreamFrame(chunkJson, "Decrypted stream frame"));
937
1425
  }
938
1426
  if (readerDone) {
939
1427
  this.checkEnded();
@@ -955,6 +1443,14 @@ var EncryptedStream = class {
955
1443
  throw truncatedStreamError();
956
1444
  }
957
1445
  }
1446
+ /** Same as `Stream.worker`: set once the trailer chunk has been iterated. */
1447
+ get worker() {
1448
+ return this.placement.worker;
1449
+ }
1450
+ /** Same as `Stream.requestId`. */
1451
+ get requestId() {
1452
+ return this.placement.requestId;
1453
+ }
958
1454
  abort() {
959
1455
  this.aborted = true;
960
1456
  this.done = true;
@@ -975,7 +1471,9 @@ var Completions = class {
975
1471
  for (const [key, value] of Object.entries(rest)) {
976
1472
  if (value != null) body[key] = value;
977
1473
  }
978
- const headers = params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0;
1474
+ const headers = {};
1475
+ if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
1476
+ if (params.stream) headers[PLACEMENT_OPT_IN_HEADER] = "1";
979
1477
  if (this.client.privateInferenceEnabled) {
980
1478
  return this.createEncrypted(params, body, headers);
981
1479
  }
@@ -990,7 +1488,8 @@ var Completions = class {
990
1488
  "/api/v1/chat/completions",
991
1489
  { method: "POST", body, headers }
992
1490
  );
993
- return parseCompletion(response);
1491
+ const completion = await parseCompletion(response);
1492
+ return withPlacement(completion, response.headers, completion.pendra);
994
1493
  }
995
1494
  async createEncrypted(params, body, headers) {
996
1495
  const engine = await this.client._privateEngine();
@@ -1030,7 +1529,8 @@ var Completions = class {
1030
1529
  throw unsealedReplyError();
1031
1530
  }
1032
1531
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1033
- return parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1532
+ const completion = parseDecryptedCompletion(DECODER3.decode(plain), response.status);
1533
+ return withPlacement(completion, response.headers, completion.pendra, wrapper.pendra);
1034
1534
  }
1035
1535
  };
1036
1536
 
@@ -1099,7 +1599,8 @@ var Embeddings = class {
1099
1599
  "/api/v1/embeddings",
1100
1600
  { method: "POST", body, headers }
1101
1601
  );
1102
- return await response.json();
1602
+ const result = await response.json();
1603
+ return withPlacement(result, response.headers, result.pendra);
1103
1604
  }
1104
1605
  async createEncrypted(model, body, headers) {
1105
1606
  const engine = await this.client._privateEngine();
@@ -1118,7 +1619,8 @@ var Embeddings = class {
1118
1619
  throw unsealedReplyError();
1119
1620
  }
1120
1621
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1121
- return JSON.parse(DECODER4.decode(plain));
1622
+ const result = JSON.parse(DECODER4.decode(plain));
1623
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1122
1624
  }
1123
1625
  };
1124
1626
 
@@ -1161,7 +1663,8 @@ var Generations = class {
1161
1663
  "/api/v1/images/generations",
1162
1664
  { method: "POST", body, headers }
1163
1665
  );
1164
- return await response.json();
1666
+ const result = await response.json();
1667
+ return withPlacement(result, response.headers, result.pendra);
1165
1668
  }
1166
1669
  async createEncrypted(model, body, headers) {
1167
1670
  const engine = await this.client._privateEngine();
@@ -1175,7 +1678,8 @@ var Generations = class {
1175
1678
  "/api/v1/images/generations",
1176
1679
  { method: "POST", body: topLevel, headers }
1177
1680
  );
1178
- const plain = decryptor.openResult(await readSealedReply(response));
1681
+ const { inner, placement } = await readSealedReply(response);
1682
+ const plain = decryptor.openResult(inner);
1179
1683
  const parsed = parseDecryptedJson(DECODER5.decode(plain), response.status);
1180
1684
  if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
1181
1685
  throw new APIResponseValidationError("Decrypted response was not an image generation", {
@@ -1183,7 +1687,8 @@ var Generations = class {
1183
1687
  body: DECODER5.decode(plain)
1184
1688
  });
1185
1689
  }
1186
- return parsed;
1690
+ const result = parsed;
1691
+ return withPlacement(result, response.headers, result.pendra, placement);
1187
1692
  }
1188
1693
  };
1189
1694
 
@@ -1261,7 +1766,8 @@ var Rerank = class {
1261
1766
  "/api/v1/rerank",
1262
1767
  { method: "POST", body, headers }
1263
1768
  );
1264
- return await response.json();
1769
+ const result = await response.json();
1770
+ return withPlacement(result, response.headers, result.pendra);
1265
1771
  }
1266
1772
  async createEncrypted(model, body, headers) {
1267
1773
  const engine = await this.client._privateEngine();
@@ -1280,226 +1786,15 @@ var Rerank = class {
1280
1786
  throw unsealedReplyError();
1281
1787
  }
1282
1788
  const plain = decryptor.openResult(wrapper.pendra_encrypted);
1283
- return JSON.parse(DECODER6.decode(plain));
1789
+ const result = JSON.parse(DECODER6.decode(plain));
1790
+ return withPlacement(result, response.headers, result.pendra, wrapper.pendra);
1284
1791
  }
1285
1792
  };
1286
1793
 
1287
1794
  // src/version.ts
1288
- var VERSION = "0.15.2";
1795
+ var VERSION = "0.17.0";
1289
1796
  var USER_AGENT = `pendra-node/${VERSION}`;
1290
1797
 
1291
- // src/_privateInferenceEngine.ts
1292
- var PrivateInferenceError = class extends Error {
1293
- constructor(message) {
1294
- super(message);
1295
- this.name = "PrivateInferenceError";
1296
- }
1297
- };
1298
- var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1299
- function parsePinnedFingerprints(pin) {
1300
- if (typeof pin !== "string") {
1301
- throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1302
- }
1303
- const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1304
- if (fps.length === 0) {
1305
- throw new PrivateInferenceError(
1306
- "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1307
- );
1308
- }
1309
- const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1310
- if (bad.length > 0) {
1311
- throw new PrivateInferenceError(
1312
- `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1313
- );
1314
- }
1315
- return new Set(fps);
1316
- }
1317
- function defaultTofuPath() {
1318
- const env = typeof process !== "undefined" ? process.env : void 0;
1319
- if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
1320
- const home = env?.HOME || env?.USERPROFILE || ".";
1321
- return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
1322
- }
1323
- function b64d2(s) {
1324
- if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
1325
- const binary = atob(s);
1326
- const out = new Uint8Array(binary.length);
1327
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
1328
- return out;
1329
- }
1330
- var PrivateInferenceEngine = class {
1331
- constructor(opts) {
1332
- this.orgPubs = null;
1333
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1334
- this.apiKey = opts.apiKey;
1335
- const pin = opts.pinnedFingerprint;
1336
- this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1337
- this.affinitySalt = opts.affinitySalt ?? null;
1338
- this.tofuPath = opts.tofuPath || defaultTofuPath();
1339
- }
1340
- // --- key resolution ---
1341
- cachedOrgPublicKeys() {
1342
- return this.orgPubs;
1343
- }
1344
- cachedOrgPublicKey() {
1345
- return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
1346
- }
1347
- tofuIdentity() {
1348
- const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
1349
- return `${this.baseUrl}|${digest}`;
1350
- }
1351
- /**
1352
- * Drop the cached key set so the next call re-fetches it.
1353
- *
1354
- * The cache is otherwise held for the whole process lifetime, which is
1355
- * correct while a fleet keeps one key but fatal when it re-keys: a
1356
- * long-running server would go on sealing to a fingerprint no worker holds
1357
- * and fail EVERY request until someone restarted it. The API signals a re-key
1358
- * with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
1359
- * lets the client recover on its own.
1360
- *
1361
- * Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
1362
- * allowlist, so a fetch could only return fingerprints the pin already
1363
- * rejects. They surface the error instead, which is what pinning means.
1364
- */
1365
- invalidateOrgKey() {
1366
- this.orgPubs = null;
1367
- }
1368
- /** Whether this client seals only to an explicit fingerprint allowlist. */
1369
- get isPinned() {
1370
- return this.pinnedFingerprints !== null;
1371
- }
1372
- /**
1373
- * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1374
- * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1375
- * them (newest-seen first). The client seals to **all** of the returned keys
1376
- * so any worker holding any of them can serve the request. Throws
1377
- * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1378
- * intersection with the pin set.
1379
- */
1380
- async resolveOrgKey(fetchedKeys) {
1381
- if (this.orgPubs !== null) return this.orgPubs;
1382
- if (!fetchedKeys || fetchedKeys.length === 0) {
1383
- throw new PrivateInferenceError(
1384
- "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
1385
- );
1386
- }
1387
- const pubs = [];
1388
- const fps = [];
1389
- for (const entry of fetchedKeys) {
1390
- let pub;
1391
- try {
1392
- pub = b64d2(entry.public_key);
1393
- } catch (e) {
1394
- throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1395
- }
1396
- if (pub.length !== 32) {
1397
- throw new PrivateInferenceError(
1398
- `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1399
- );
1400
- }
1401
- pubs.push(pub);
1402
- fps.push(fingerprint(pub));
1403
- }
1404
- let accepted;
1405
- if (this.pinnedFingerprints !== null) {
1406
- accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1407
- if (accepted.length === 0) {
1408
- const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
1409
- throw new PrivateInferenceError(
1410
- `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.`
1411
- );
1412
- }
1413
- } else {
1414
- await this.tofuTrust(fps);
1415
- accepted = pubs;
1416
- }
1417
- this.orgPubs = accepted;
1418
- return accepted;
1419
- }
1420
- async tofuTrust(fps) {
1421
- const store = await this.loadTofu();
1422
- const identity = this.tofuIdentity();
1423
- const known = store[identity];
1424
- const trusted = /* @__PURE__ */ new Set();
1425
- if (typeof known === "string") {
1426
- trusted.add(known);
1427
- } else if (Array.isArray(known)) {
1428
- for (const f of known) if (typeof f === "string") trusted.add(f);
1429
- }
1430
- const before = trusted.size;
1431
- for (const f of fps) trusted.add(f);
1432
- if (trusted.size !== before || !Array.isArray(known)) {
1433
- store[identity] = Array.from(trusted).sort();
1434
- await this.saveTofu(store);
1435
- }
1436
- }
1437
- async loadTofu() {
1438
- try {
1439
- const fs = await import("fs");
1440
- const raw = fs.readFileSync(this.tofuPath, "utf-8");
1441
- const data = JSON.parse(raw);
1442
- return data && typeof data === "object" && !Array.isArray(data) ? data : {};
1443
- } catch {
1444
- return {};
1445
- }
1446
- }
1447
- async saveTofu(store) {
1448
- const fs = await import("fs");
1449
- const path = await import("path");
1450
- const directory = path.dirname(this.tofuPath) || ".";
1451
- fs.mkdirSync(directory, { recursive: true });
1452
- const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
1453
- try {
1454
- fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
1455
- try {
1456
- fs.chmodSync(tmp, 384);
1457
- } catch {
1458
- }
1459
- fs.renameSync(tmp, this.tofuPath);
1460
- } catch (e) {
1461
- try {
1462
- fs.unlinkSync(tmp);
1463
- } catch {
1464
- }
1465
- throw e;
1466
- }
1467
- }
1468
- // --- sealing ---
1469
- /**
1470
- * Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
1471
- * `messages` (chat only) drives the affinity token; pass undefined for non-chat.
1472
- * `binary` (audio only) is sealed under the same data key as the body.
1473
- */
1474
- seal(args) {
1475
- if (this.orgPubs === null || this.orgPubs.length === 0) {
1476
- throw new PrivateInferenceError(
1477
- "private inference: org key not resolved yet (call resolveOrgKey first)"
1478
- );
1479
- }
1480
- let affinity = null;
1481
- if (args.messages != null) {
1482
- affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
1483
- }
1484
- const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
1485
- model: args.model,
1486
- stream: args.stream,
1487
- taskType: args.taskType,
1488
- affinityKey: affinity,
1489
- binary: args.binary ?? null
1490
- });
1491
- const topLevel = {
1492
- model: args.model,
1493
- stream: args.stream,
1494
- pendra_encrypted: envelope
1495
- };
1496
- return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
1497
- }
1498
- get keyFetchUrl() {
1499
- return `${this.baseUrl}/v1/private-inference/key`;
1500
- }
1501
- };
1502
-
1503
1798
  // src/client.ts
1504
1799
  function envTruthy(v) {
1505
1800
  if (!v) return false;
@@ -1609,19 +1904,7 @@ var Pendra = class {
1609
1904
  );
1610
1905
  }
1611
1906
  if (!response.ok) {
1612
- let message;
1613
- try {
1614
- const body = await response.json();
1615
- if (typeof body.detail === "string") message = body.detail;
1616
- else if (typeof body.error?.message === "string") message = body.error.message;
1617
- else if (body.detail != null) message = JSON.stringify(body.detail);
1618
- else message = response.statusText;
1619
- } catch {
1620
- message = response.statusText;
1621
- }
1622
- if (response.status === 401) throw new AuthenticationError(message);
1623
- if (response.status === 429) throw new RateLimitError(message);
1624
- throw new APIStatusError(message, response.status);
1907
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1625
1908
  }
1626
1909
  const json = await response.json();
1627
1910
  await engine.resolveOrgKey(json.keys ?? []);
@@ -1659,19 +1942,7 @@ var Pendra = class {
1659
1942
  clearTimeout(timeoutId);
1660
1943
  if (!response.ok) {
1661
1944
  this.invalidateKeyCacheIfRekeyed(response);
1662
- let message;
1663
- try {
1664
- const body = await response.json();
1665
- if (typeof body.detail === "string") message = body.detail;
1666
- else if (typeof body.error?.message === "string") message = body.error.message;
1667
- else if (body.detail != null) message = JSON.stringify(body.detail);
1668
- else message = response.statusText;
1669
- } catch {
1670
- message = response.statusText;
1671
- }
1672
- if (response.status === 401) throw new AuthenticationError(message);
1673
- if (response.status === 429) throw new RateLimitError(message);
1674
- throw new APIStatusError(message, response.status);
1945
+ throw statusErrorFromBody(response.status, await readErrorBody(response), response.statusText);
1675
1946
  }
1676
1947
  return { response, controller };
1677
1948
  }